:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): add per-symbol latency endpoint with period comparison (#64118)
Jon McCallum995c11ab50b9
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 49f31ae76cde..74e96a08a146 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -10136,6 +10136,98 @@],"type": "object"},+ "CachedTraceSpansSymbolStatsQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "cache_key": {+ "type": "string"+ },+ "cache_target_age": {+ "format": "date-time",+ "type": "string"+ },+ "calculation_trigger": {+ "description": "What triggered the calculation of the query, leave empty if user/immediate",+ "type": "string"+ },+ "error": {+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",+ "type": "string"+ },+ "granularity": {+ "$ref": "#/definitions/SymbolStatsGranularity",+ "description": "Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise."+ },+ "hogql": {+ "description": "Generated HogQL query.",+ "type": "string"+ },+ "is_cached": {+ "type": "boolean"+ },+ "last_refresh": {+ "format": "date-time",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "next_allowed_client_refresh": {+ "format": "date-time",+ "type": "string"+ },+ "query_metadata": {+ "type": "object"+ },+ "query_status": {+ "$ref": "#/definitions/QueryStatus",+ "description": "Query status indicates whether next to the provided data, a query is still running."+ },+ "resolved_compare_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The resolved previous/comparison period date range, when comparing against another period"+ },+ "resolved_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "description": "One row per bucket, ordered by line ascending.",+ "items": {+ "$ref": "#/definitions/SymbolStatsRow"+ },+ "type": "array"+ },+ "timezone": {+ "type": "string"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ },+ "warnings": {+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries.",+ "items": {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ "type": "array"+ }+ },+ "required": [+ "cache_key",+ "granularity",+ "is_cached",+ "last_refresh",+ "next_allowed_client_refresh",+ "results",+ "timezone"+ ],+ "type": "object"+ },"CachedTraceSpansTreeQueryResponse": {"additionalProperties": false,"properties": {@@ -29048,6 +29140,7 @@"TraceSpansAggregationQuery","TraceSpansTreeQuery","TraceSpansAttributeBreakdownQuery",+ "TraceSpansSymbolStatsQuery","SessionBatchEventsQuery","DataTableNode","DataVisualizationNode",@@ -40836,6 +40929,26 @@},"type": "object"},+ "SourceSymbol": {+ "additionalProperties": false,+ "description": "A source symbol (typically a function) the client wants production latency for, identified by its declaration line range. The client supplies these from its own AST/LSP — the server does not infer function boundaries (OTel `code.function.name` is frequently absent, and `code.line.number` may be a call site inside the body rather than the declaration line).",+ "properties": {+ "endLine": {+ "$ref": "#/definitions/positive_integer",+ "description": "Last line of the symbol's range, inclusive (1-based)."+ },+ "name": {+ "description": "Opaque identifier (e.g. the function name) echoed back on the matching result row.",+ "type": "string"+ },+ "startLine": {+ "$ref": "#/definitions/positive_integer",+ "description": "First line of the symbol's range, inclusive (1-based)."+ }+ },+ "required": ["startLine", "endLine"],+ "type": "object"+ },"SpanPropertyFilter": {"additionalProperties": false,"properties": {@@ -41679,6 +41792,157 @@"enum": ["button", "tab", "selector"],"type": "string"},+ "SymbolStatsGranularity": {+ "description": "Bucketing applied to a symbol-stats result: per source line, or per requested symbol range.",+ "enum": ["line", "symbol"],+ "type": "string"+ },+ "SymbolStatsPeriod": {+ "additionalProperties": false,+ "description": "Aggregated metrics for a symbol over a single time period. Used for the prior-period comparison.",+ "properties": {+ "busy_count": {+ "$ref": "#/definitions/integer",+ "description": "Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful."+ },+ "count": {+ "$ref": "#/definitions/integer",+ "description": "Number of spans attributed to this symbol in the period."+ },+ "error_count": {+ "$ref": "#/definitions/integer",+ "description": "Spans whose OTel status is Error (`status_code = 2`)."+ },+ "p50_busy_nano": {+ "description": "Median active (busy) time, in nanoseconds. Excludes time awaiting children.",+ "type": "number"+ },+ "p50_duration_nano": {+ "description": "Median wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "p95_busy_nano": {+ "description": "95th-percentile active (busy) time, in nanoseconds.",+ "type": "number"+ },+ "p95_duration_nano": {+ "description": "95th-percentile wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "p99_busy_nano": {+ "description": "99th-percentile active (busy) time, in nanoseconds.",+ "type": "number"+ },+ "p99_duration_nano": {+ "description": "99th-percentile wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "sum_duration_nano": {+ "description": "Total wall-clock span duration in the period, in nanoseconds (additive across spans).",+ "type": "number"+ }+ },+ "required": [+ "count",+ "error_count",+ "sum_duration_nano",+ "p50_duration_nano",+ "p95_duration_nano",+ "p99_duration_nano",+ "busy_count",+ "p50_busy_nano",+ "p95_busy_nano",+ "p99_busy_nano"+ ],+ "type": "object"+ },+ "SymbolStatsRow": {+ "additionalProperties": false,+ "description": "Production latency for one bucket of a source file: spans carrying OpenTelemetry `code.*` location attributes, aggregated by line (no `symbols`) or into a symbol's line range (`symbols` supplied). The flat fields are the current period; `previous` is the immediately-preceding equal-length window. One row per bucket with spans in either period.",+ "properties": {+ "busy_count": {+ "$ref": "#/definitions/integer",+ "description": "Spans in this symbol carrying an active/busy time attribute. 0 means busy_* are not meaningful."+ },+ "count": {+ "$ref": "#/definitions/integer",+ "description": "Number of spans attributed to this bucket."+ },+ "count_pct_change": {+ "description": "Percentage change in count vs the previous period (180 = +180%). Null when there is no baseline (previous count 0); use `previous.count`, not a null here, to detect a brand-new symbol.",+ "type": ["number", "null"]+ },+ "end_line": {+ "$ref": "#/definitions/integer",+ "description": "`endLine` of the matched symbol's range. Symbol mode only."+ },+ "error_count": {+ "$ref": "#/definitions/integer",+ "description": "Spans whose OTel status is Error (`status_code = 2`)."+ },+ "line": {+ "$ref": "#/definitions/integer",+ "description": "The bucket's anchor line: the source line in line mode, or the symbol's `startLine` in symbol mode."+ },+ "name": {+ "description": "Echoed `name` from the requested symbol. Symbol mode only.",+ "type": "string"+ },+ "p50_busy_nano": {+ "description": "Median active (busy) time, in nanoseconds. Excludes time awaiting children.",+ "type": "number"+ },+ "p50_duration_nano": {+ "description": "Median wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "p95_busy_nano": {+ "description": "95th-percentile active (busy) time, in nanoseconds.",+ "type": "number"+ },+ "p95_duration_nano": {+ "description": "95th-percentile wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "p95_duration_pct_change": {+ "description": "Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous p95 is 0 (no comparable baseline), which can happen even when previous.count > 0 — do not read null as \"new\".",+ "type": ["number", "null"]+ },+ "p99_busy_nano": {+ "description": "99th-percentile active (busy) time, in nanoseconds.",+ "type": "number"+ },+ "p99_duration_nano": {+ "description": "99th-percentile wall-clock span duration, in nanoseconds.",+ "type": "number"+ },+ "previous": {+ "$ref": "#/definitions/SymbolStatsPeriod",+ "description": "The same metrics over the immediately-preceding equal-length period."+ },+ "sum_duration_nano": {+ "description": "Total wall-clock span duration in this symbol, in nanoseconds (additive across spans).",+ "type": "number"+ }+ },+ "required": [+ "line",+ "count",+ "error_count",+ "sum_duration_nano",+ "p50_duration_nano",+ "p95_duration_nano",+ "p99_duration_nano",+ "busy_count",+ "p50_busy_nano",+ "p95_busy_nano",+ "p99_busy_nano",+ "previous",+ "count_pct_change",+ "p95_duration_pct_change"+ ],+ "type": "object"+ },"TableSettings": {"additionalProperties": false,"properties": {@@ -42715,6 +42979,101 @@"required": ["results"],"type": "object"},+ "TraceSpansSymbolStatsQuery": {+ "additionalProperties": false,+ "properties": {+ "dateRange": {+ "$ref": "#/definitions/DateRange"+ },+ "filePath": {+ "description": "Repo-relative path of the source file to aggregate (e.g. `src/flags/flag_matching.rs`). Matched as a path suffix against the recorded `code.file.path` / `code.filepath`, so a recorded path carrying an extra crate/workspace prefix still matches.",+ "type": "string"+ },+ "kind": {+ "const": "TraceSpansSymbolStatsQuery",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "response": {+ "$ref": "#/definitions/TraceSpansSymbolStatsQueryResponse"+ },+ "symbols": {+ "description": "Optional symbol (function) ranges to aggregate spans into. When supplied, each span is attributed to the smallest range that encloses its recorded line (one row per symbol). When omitted (or an empty list), spans are aggregated per source line (one row per instrumented line) — pass a single whole-file range for a file-level total.",+ "items": {+ "$ref": "#/definitions/SourceSymbol"+ },+ "type": "array"+ },+ "tags": {+ "$ref": "#/definitions/QueryLogTags"+ },+ "version": {+ "description": "version of the node, used for schema migrations",+ "type": "number"+ }+ },+ "required": ["dateRange", "filePath", "kind"],+ "type": "object"+ },+ "TraceSpansSymbolStatsQueryResponse": {+ "additionalProperties": false,+ "properties": {+ "error": {+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",+ "type": "string"+ },+ "granularity": {+ "$ref": "#/definitions/SymbolStatsGranularity",+ "description": "Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise."+ },+ "hogql": {+ "description": "Generated HogQL query.",+ "type": "string"+ },+ "modifiers": {+ "$ref": "#/definitions/HogQLQueryModifiers",+ "description": "Modifiers used when performing the query"+ },+ "query_status": {+ "$ref": "#/definitions/QueryStatus",+ "description": "Query status indicates whether next to the provided data, a query is still running."+ },+ "resolved_compare_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The resolved previous/comparison period date range, when comparing against another period"+ },+ "resolved_date_range": {+ "$ref": "#/definitions/ResolvedDateRangeResponse",+ "description": "The date range used for the query"+ },+ "results": {+ "description": "One row per bucket, ordered by line ascending.",+ "items": {+ "$ref": "#/definitions/SymbolStatsRow"+ },+ "type": "array"+ },+ "timings": {+ "description": "Measured timings for different parts of the query generation process",+ "items": {+ "$ref": "#/definitions/QueryTiming"+ },+ "type": "array"+ },+ "warnings": {+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries.",+ "items": {+ "$ref": "#/definitions/DataWarehouseSyncWarning"+ },+ "type": "array"+ }+ },+ "required": ["granularity", "results"],+ "type": "object"+ },"TraceSpansTreeQuery": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 2a1f00ee8b83..ab8ad296a1bb 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -115,6 +115,7 @@ export enum NodeKind {TraceSpansAggregationQuery = 'TraceSpansAggregationQuery',TraceSpansTreeQuery = 'TraceSpansTreeQuery',TraceSpansAttributeBreakdownQuery = 'TraceSpansAttributeBreakdownQuery',+ TraceSpansSymbolStatsQuery = 'TraceSpansSymbolStatsQuery',SessionBatchEventsQuery = 'SessionBatchEventsQuery',// Interface nodes@@ -3376,6 +3377,122 @@ export interface TraceSpansAttributeBreakdownQueryResponse extends AnalyticsQuerexport type CachedTraceSpansAttributeBreakdownQueryResponse =CachedQueryResponse<TraceSpansAttributeBreakdownQueryResponse>+/**+ * A source symbol (typically a function) the client wants production latency for, identified by its+ * declaration line range. The client supplies these from its own AST/LSP — the server does not infer+ * function boundaries (OTel `code.function.name` is frequently absent, and `code.line.number` may be a+ * call site inside the body rather than the declaration line).+ */+export interface SourceSymbol {+ /** Opaque identifier (e.g. the function name) echoed back on the matching result row. */+ name?: string+ /** First line of the symbol's range, inclusive (1-based). */+ startLine: positive_integer+ /** Last line of the symbol's range, inclusive (1-based). */+ endLine: positive_integer+}++/** Aggregated metrics for a symbol over a single time period. Used for the prior-period comparison. */+export interface SymbolStatsPeriod {+ /** Number of spans attributed to this symbol in the period. */+ count: integer+ /** Spans whose OTel status is Error (`status_code = 2`). */+ error_count: integer+ /** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */+ sum_duration_nano: number+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number+ /** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: integer+ /** Median active (busy) time, in nanoseconds. Excludes time awaiting children. */+ p50_busy_nano: number+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number+}++/**+ * Production latency for one bucket of a source file: spans carrying OpenTelemetry `code.*` location+ * attributes, aggregated by line (no `symbols`) or into a symbol's line range (`symbols` supplied). The+ * flat fields are the current period; `previous` is the immediately-preceding equal-length window. One+ * row per bucket with spans in either period.+ */+export interface SymbolStatsRow {+ /** The bucket's anchor line: the source line in line mode, or the symbol's `startLine` in symbol mode. */+ line: integer+ /** Echoed `name` from the requested symbol. Symbol mode only. */+ name?: string+ /** `endLine` of the matched symbol's range. Symbol mode only. */+ end_line?: integer+ /** Number of spans attributed to this bucket. */+ count: integer+ /** Spans whose OTel status is Error (`status_code = 2`). */+ error_count: integer+ /** Total wall-clock span duration in this symbol, in nanoseconds (additive across spans). */+ sum_duration_nano: number+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number+ /** Spans in this symbol carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: integer+ /** Median active (busy) time, in nanoseconds. Excludes time awaiting children. */+ p50_busy_nano: number+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number+ /** The same metrics over the immediately-preceding equal-length period. */+ previous: SymbolStatsPeriod+ /**+ * Percentage change in count vs the previous period (180 = +180%). Null when there is no baseline+ * (previous count 0); use `previous.count`, not a null here, to detect a brand-new symbol.+ */+ count_pct_change: number | null+ /**+ * Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous p95+ * is 0 (no comparable baseline), which can happen even when previous.count > 0 — do not read null as "new".+ */+ p95_duration_pct_change: number | null+}++export interface TraceSpansSymbolStatsQuery extends DataNode<TraceSpansSymbolStatsQueryResponse> {+ kind: NodeKind.TraceSpansSymbolStatsQuery+ dateRange: DateRange+ /**+ * Repo-relative path of the source file to aggregate (e.g. `src/flags/flag_matching.rs`).+ * Matched as a path suffix against the recorded `code.file.path` / `code.filepath`, so a+ * recorded path carrying an extra crate/workspace prefix still matches.+ */+ filePath: string+ /**+ * Optional symbol (function) ranges to aggregate spans into. When supplied, each span is attributed+ * to the smallest range that encloses its recorded line (one row per symbol). When omitted (or an+ * empty list), spans are aggregated per source line (one row per instrumented line) — pass a single+ * whole-file range for a file-level total.+ */+ symbols?: SourceSymbol[]+}++/** Bucketing applied to a symbol-stats result: per source line, or per requested symbol range. */+export type SymbolStatsGranularity = 'line' | 'symbol'++export interface TraceSpansSymbolStatsQueryResponse extends AnalyticsQueryResponseBase {+ /** One row per bucket, ordered by line ascending. */+ results: SymbolStatsRow[]+ /** Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise. */+ granularity: SymbolStatsGranularity+}++export type CachedTraceSpansSymbolStatsQueryResponse = CachedQueryResponse<TraceSpansSymbolStatsQueryResponse>+export interface FileSystemCount {count: numberentries: FileSystemEntry[]diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex a82bc3afddca..07aa717d5a91 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -566,6 +566,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {icon: IconLive,inMenu: false,},+ [NodeKind.TraceSpansSymbolStatsQuery]: {+ name: 'Trace Spans Symbol Stats',+ icon: IconLive,+ inMenu: false,+ },[NodeKind.WebAnalyticsExternalSummaryQuery]: {name: 'Web Analytics External Summary',icon: IconPieChart,diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex a19383e0e2c2..667d75ec7253 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -233,6 +233,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:| NodeKind.TRACE_SPANS_AGGREGATION_QUERY| NodeKind.TRACE_SPANS_TREE_QUERY| NodeKind.TRACE_SPANS_ATTRIBUTE_BREAKDOWN_QUERY+ | NodeKind.TRACE_SPANS_SYMBOL_STATS_QUERY):return {"product": Product.LLM_ANALYTICS}case (diff --git a/posthog/schema.py b/posthog/schema.pyindex cf27fdce5f17..5541250ea7f0 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -258,6 +258,7 @@ from posthog.schema_enums import (SurveyTabPosition as SurveyTabPosition,SurveyType as SurveyType,SurveyWidgetType as SurveyWidgetType,+ SymbolStatsGranularity as SymbolStatsGranularity,Tag as Tag,TaskExecutionStatus as TaskExecutionStatus,TaxonomicFilterGroupType as TaxonomicFilterGroupType,@@ -6737,6 +6738,18 @@ class SourceFieldInputConfig(BaseModel):type: SourceFieldInputConfigType+class SourceSymbol(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ endLine: conint(ge=1) = Field(..., description="Last line of the symbol's range, inclusive (1-based).")+ name: str | None = Field(+ default=None,+ description=("Opaque identifier (e.g. the function name) echoed back on the matching result row."),+ )+ startLine: conint(ge=1) = Field(..., description="First line of the symbol's range, inclusive (1-based).")++class SpanPropertyFilter(BaseModel):model_config = ConfigDict(extra="forbid",@@ -6946,6 +6959,90 @@ class SurveyQuestionSchema(BaseModel):upperBoundLabel: str | None = None+class SymbolStatsPeriod(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ busy_count: int = Field(+ ...,+ description=("Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful."),+ )+ count: int = Field(..., description="Number of spans attributed to this symbol in the period.")+ error_count: int = Field(..., description="Spans whose OTel status is Error (`status_code = 2`).")+ p50_busy_nano: float = Field(+ ...,+ description=("Median active (busy) time, in nanoseconds. Excludes time awaiting children."),+ )+ p50_duration_nano: float = Field(..., description="Median wall-clock span duration, in nanoseconds.")+ p95_busy_nano: float = Field(..., description="95th-percentile active (busy) time, in nanoseconds.")+ p95_duration_nano: float = Field(..., description="95th-percentile wall-clock span duration, in nanoseconds.")+ p99_busy_nano: float = Field(..., description="99th-percentile active (busy) time, in nanoseconds.")+ p99_duration_nano: float = Field(..., description="99th-percentile wall-clock span duration, in nanoseconds.")+ sum_duration_nano: float = Field(+ ...,+ description=("Total wall-clock span duration in the period, in nanoseconds (additive across spans)."),+ )+++class SymbolStatsRow(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ busy_count: int = Field(+ ...,+ description=("Spans in this symbol carrying an active/busy time attribute. 0 means busy_* are not meaningful."),+ )+ count: int = Field(..., description="Number of spans attributed to this bucket.")+ count_pct_change: float | None = Field(+ ...,+ description=(+ "Percentage change in count vs the previous period (180 = +180%). Null when"+ " there is no baseline (previous count 0); use `previous.count`, not a null"+ " here, to detect a brand-new symbol."+ ),+ )+ end_line: int | None = Field(+ default=None,+ description="`endLine` of the matched symbol's range. Symbol mode only.",+ )+ error_count: int = Field(..., description="Spans whose OTel status is Error (`status_code = 2`).")+ line: int = Field(+ ...,+ description=(+ "The bucket's anchor line: the source line in line mode, or the symbol's `startLine` in symbol mode."+ ),+ )+ name: str | None = Field(+ default=None,+ description="Echoed `name` from the requested symbol. Symbol mode only.",+ )+ p50_busy_nano: float = Field(+ ...,+ description=("Median active (busy) time, in nanoseconds. Excludes time awaiting children."),+ )+ p50_duration_nano: float = Field(..., description="Median wall-clock span duration, in nanoseconds.")+ p95_busy_nano: float = Field(..., description="95th-percentile active (busy) time, in nanoseconds.")+ p95_duration_nano: float = Field(..., description="95th-percentile wall-clock span duration, in nanoseconds.")+ p95_duration_pct_change: float | None = Field(+ ...,+ description=(+ "Percentage change in p95 duration vs the previous period (180 = +180%)."+ " Null when the previous p95 is 0 (no comparable baseline), which can"+ ' happen even when previous.count > 0 — do not read null as "new".'+ ),+ )+ p99_busy_nano: float = Field(..., description="99th-percentile active (busy) time, in nanoseconds.")+ p99_duration_nano: float = Field(..., description="99th-percentile wall-clock span duration, in nanoseconds.")+ previous: SymbolStatsPeriod = Field(+ ...,+ description=("The same metrics over the immediately-preceding equal-length period."),+ )+ sum_duration_nano: float = Field(+ ...,+ description=("Total wall-clock span duration in this symbol, in nanoseconds (additive across spans)."),+ )++class TableSettings(BaseModel):model_config = ConfigDict(extra="forbid",@@ -7272,6 +7369,51 @@ class TraceSpansQueryResponse(BaseModel):)+class TraceSpansSymbolStatsQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ granularity: SymbolStatsGranularity = Field(+ ...,+ description=("Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise."),+ )+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[SymbolStatsRow] = Field(..., description="One row per bucket, ordered by line ascending.")+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose latest"+ " sync failed, is paused, hit a billing limit, or is otherwise stale."+ " Results may not reflect current source data. Accumulated across every"+ " HogQL execution that contributes to this response — so insights backed by"+ " warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw"+ " HogQL queries."+ ),+ )++class TraceSpansTreeQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -11714,6 +11856,62 @@ class CachedTraceSpansQueryResponse(BaseModel):)+class CachedTraceSpansSymbolStatsQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ cache_key: str+ cache_target_age: AwareDatetime | None = None+ calculation_trigger: str | None = Field(+ default=None,+ description=("What triggered the calculation of the query, leave empty if user/immediate"),+ )+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ granularity: SymbolStatsGranularity = Field(+ ...,+ description=("Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise."),+ )+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ is_cached: bool+ last_refresh: AwareDatetime+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ next_allowed_client_refresh: AwareDatetime+ query_metadata: dict[str, Any] | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[SymbolStatsRow] = Field(..., description="One row per bucket, ordered by line ascending.")+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ warnings: list[DataWarehouseSyncWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose latest"+ " sync failed, is paused, hit a billing limit, or is otherwise stale."+ " Results may not reflect current source data. Accumulated across every"+ " HogQL execution that contributes to this response — so insights backed by"+ " warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw"+ " HogQL queries."+ ),+ )++class CachedTraceSpansTreeQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -20112,6 +20310,37 @@ class TraceQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class TraceSpansSymbolStatsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ dateRange: DateRange+ filePath: str = Field(+ ...,+ description=(+ "Repo-relative path of the source file to aggregate (e.g."+ " `src/flags/flag_matching.rs`). Matched as a path suffix against the"+ " recorded `code.file.path` / `code.filepath`, so a recorded path carrying"+ " an extra crate/workspace prefix still matches."+ ),+ )+ kind: Literal["TraceSpansSymbolStatsQuery"] = "TraceSpansSymbolStatsQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: TraceSpansSymbolStatsQueryResponse | None = None+ symbols: list[SourceSymbol] | None = Field(+ default=None,+ description=(+ "Optional symbol (function) ranges to aggregate spans into. When supplied,"+ " each span is attributed to the smallest range that encloses its recorded"+ " line (one row per symbol). When omitted (or an empty list), spans are"+ " aggregated per source line (one row per instrumented line) — pass a"+ " single whole-file range for a file-level total."+ ),+ )+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class TracesQuery(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex c908321475b1..df52e3707615 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2441,6 +2441,7 @@ class NodeKind(StrEnum):TRACE_SPANS_AGGREGATION_QUERY = "TraceSpansAggregationQuery"TRACE_SPANS_TREE_QUERY = "TraceSpansTreeQuery"TRACE_SPANS_ATTRIBUTE_BREAKDOWN_QUERY = "TraceSpansAttributeBreakdownQuery"+ TRACE_SPANS_SYMBOL_STATS_QUERY = "TraceSpansSymbolStatsQuery"SESSION_BATCH_EVENTS_QUERY = "SessionBatchEventsQuery"DATA_TABLE_NODE = "DataTableNode"DATA_VISUALIZATION_NODE = "DataVisualizationNode"@@ -3149,6 +3150,11 @@ class SurveyWidgetType(StrEnum):SELECTOR = "selector"+class SymbolStatsGranularity(StrEnum):+ LINE = "line"+ SYMBOL = "symbol"++class TaskExecutionStatus(StrEnum):PENDING = "pending"IN_PROGRESS = "in_progress"diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.pyindex df35fc63d51c..9bba56e275e7 100644--- a/products/tracing/backend/facade/api.py+++ b/products/tracing/backend/facade/api.py@@ -21,13 +21,16 @@ from typing import TYPE_CHECKINGfrom posthog.schema import (CachedTraceSpansAttributeBreakdownQueryResponse,CachedTraceSpansQueryResponse,+ CachedTraceSpansSymbolStatsQueryResponse,CompareFilter,DateRange,PropertyGroupFilter,+ SourceSymbol,TraceSpanBreakdownOrderBy,TraceSpanBreakdownType,TraceSpansAttributeBreakdownQueryResponse,TraceSpansQueryResponse,+ TraceSpansSymbolStatsQueryResponse,)from products.tracing.backend.attribute_breakdown_query_runner import (@@ -38,6 +41,7 @@ from products.tracing.backend.duration_histogram_query_runner import (run_duration_histogram_query as _run_duration_histogram_query,)from products.tracing.backend.self_time import annotate_self_time as _annotate_self_time+from products.tracing.backend.symbol_stats_query_runner import run_symbol_stats_query as _run_symbol_stats_queryif TYPE_CHECKING:from posthog.models import Team@@ -92,6 +96,22 @@ def run_attribute_breakdown_query()+def run_symbol_stats_query(+ *,+ team: "Team",+ file_path: str,+ date_range: DateRange,+ symbols: list[SourceSymbol] | None = None,+) -> TraceSpansSymbolStatsQueryResponse | CachedTraceSpansSymbolStatsQueryResponse:+ """Run per-line (no symbols) or per-symbol latency stats for one source file, vs the prior period."""+ return _run_symbol_stats_query(+ team=team,+ file_path=file_path,+ date_range=date_range,+ symbols=symbols,+ )++def run_duration_histogram_query(*,team: "Team",diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 5552876f5491..70342acaa030 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -27,6 +27,7 @@ from posthog.schema import (DateRange,ProductKey,PropertyGroupFilter,+ SourceSymbol,TraceSpanBreakdownOrderBy,TraceSpanBreakdownType,TraceSpansQuery,@@ -45,6 +46,7 @@ from ..facade.api import (run_attribute_breakdown_query,run_count_query,run_duration_histogram_query,+ run_symbol_stats_query,)from ..has_spans_query_runner import team_has_spansfrom ..logic import (@@ -415,6 +417,105 @@ class _TracingCountResponseSerializer(serializers.Serializer):count = serializers.IntegerField(help_text="Number of spans matching the filters.")+# Upper bound on symbols per request; each becomes a multiIf branch in the generated query.+_MAX_SYMBOLS = 1000+++class _SymbolStatsSymbolSerializer(serializers.Serializer):+ name = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Opaque identifier (e.g. the function name) echoed back on the matching result row.",+ )+ startLine = serializers.IntegerField(min_value=1, help_text="First line of the symbol's range, inclusive.")+ endLine = serializers.IntegerField(min_value=1, help_text="Last line of the symbol's range, inclusive.")+++class _SymbolStatsQueryBodySerializer(serializers.Serializer):+ filePath = serializers.CharField(+ help_text=(+ "Repo-relative path of the source file to aggregate (e.g. 'src/flags/flag_matching.rs'). "+ "Matched as a path suffix against the recorded OTel code.file.path / code.filepath, so a "+ "recorded path carrying an extra crate/workspace prefix still matches. Separators are normalized."+ ),+ )+ dateRange = _TracingDateRangeSerializer(+ required=False,+ help_text="Current period to aggregate over; the prior equal-length window is the comparison. Defaults to last 24h.",+ )+ symbols = _SymbolStatsSymbolSerializer(+ many=True,+ required=False,+ help_text=(+ "Optional symbol (function) line ranges, supplied by the client from its own AST/LSP. When "+ "given, each span is attributed to the smallest enclosing range (one row per symbol). When "+ "omitted (or an empty list), spans are aggregated per source line (one row per line); pass a "+ "single whole-file range for a file-level total."+ ),+ )+++class _SymbolStatsRequestSerializer(serializers.Serializer):+ query = _SymbolStatsQueryBodySerializer(help_text="The symbol-stats per-symbol aggregation query to execute.")+++class _SymbolStatsPeriodSerializer(serializers.Serializer):+ count = serializers.IntegerField(help_text="Number of spans attributed to this symbol in the period.")+ error_count = serializers.IntegerField(help_text="Spans whose OTel status is Error (status_code = 2).")+ sum_duration_nano = serializers.FloatField(+ help_text="Total wall-clock span duration in the period, in nanoseconds (additive across spans)."+ )+ p50_duration_nano = serializers.FloatField(help_text="Median wall-clock span duration, in nanoseconds.")+ p95_duration_nano = serializers.FloatField(help_text="95th-percentile wall-clock span duration, in nanoseconds.")+ p99_duration_nano = serializers.FloatField(help_text="99th-percentile wall-clock span duration, in nanoseconds.")+ busy_count = serializers.IntegerField(+ help_text="Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful."+ )+ p50_busy_nano = serializers.FloatField(+ help_text="Median active (busy) time, in nanoseconds. Excludes awaiting children."+ )+ p95_busy_nano = serializers.FloatField(help_text="95th-percentile active (busy) time, in nanoseconds.")+ p99_busy_nano = serializers.FloatField(help_text="99th-percentile active (busy) time, in nanoseconds.")+++class _SymbolStatsRowSerializer(_SymbolStatsPeriodSerializer):+ line = serializers.IntegerField(+ help_text="Bucket anchor: the source line (line mode) or the symbol's startLine (symbol mode)."+ )+ name = serializers.CharField(+ required=False, allow_null=True, help_text="Echoed name from the requested symbol (symbol mode only)."+ )+ end_line = serializers.IntegerField(+ required=False, allow_null=True, help_text="endLine of the matched symbol's range (symbol mode only)."+ )+ previous = _SymbolStatsPeriodSerializer(+ help_text="The same metrics over the immediately-preceding equal-length period."+ )+ count_pct_change = serializers.FloatField(+ allow_null=True,+ help_text=(+ "Percentage change in count vs the previous period (180 = +180%). Null when there is no "+ "baseline (previous count 0). Use `previous.count` — not a null here — to detect a new symbol."+ ),+ )+ p95_duration_pct_change = serializers.FloatField(+ allow_null=True,+ help_text=(+ "Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous "+ "p95 is 0 (no comparable baseline), which can occur even when previous.count > 0 — do not read "+ "null as 'new symbol'."+ ),+ )+++class _SymbolStatsResponseSerializer(serializers.Serializer):+ results = _SymbolStatsRowSerializer(many=True, help_text="One row per bucket, ordered by line ascending.")+ granularity = serializers.ChoiceField(+ choices=["line", "symbol"],+ help_text="Bucketing applied: 'line' when no symbols were supplied, 'symbol' otherwise.",+ )++def _encode_after_cursor(timestamp: str, **secondary: str) -> str:"""Encode a keyset `after` cursor as base64(json) of the boundary row's timestamp + secondary id.@@ -619,6 +720,77 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response(response.results, status=status.HTTP_200_OK)+ @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 {}++ file_path = query_data.get("filePath")+ if not file_path or not isinstance(file_path, str):+ return Response(+ {"detail": "`filePath` is required for symbol-stats queries."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ # symbols is optional: omitted/empty -> per-line aggregation; supplied -> per-symbol ranges.+ symbols: list[SourceSymbol] | None = None+ raw_symbols = query_data.get("symbols")+ if raw_symbols:+ if not isinstance(raw_symbols, list):+ return Response(+ {"detail": "`symbols` must be a list of {startLine, endLine} ranges."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if len(raw_symbols) > _MAX_SYMBOLS:+ # Each symbol expands to a multiIf branch; an unbounded list would inflate the generated+ # SQL past ClickHouse's parse limits before any row cap applies.+ return Response(+ {"detail": f"At most {_MAX_SYMBOLS} symbols may be requested at once."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ try:+ symbols = [self.get_model(s, SourceSymbol) for s in raw_symbols]+ except (ValidationError, ValueError, ParseError):+ return Response(+ {"detail": "Each symbol must be an object with integer `startLine` and `endLine`."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if any(symbol.startLine > symbol.endLine for symbol in symbols):+ # An inverted range matches no line, so the symbol would silently vanish from the results.+ return Response(+ {"detail": "Each symbol's `startLine` must be <= `endLine`."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if len({symbol.startLine for symbol in symbols}) != len(symbols):+ # Rows are keyed by startLine; duplicates would silently merge into one row with one name.+ return Response(+ {"detail": "Symbols must have distinct `startLine` values."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ date_range = self.get_model(query_data.get("dateRange", {"date_from": "-24h"}), DateRange)++ response = run_symbol_stats_query(team=self.team, file_path=file_path, date_range=date_range, symbols=symbols)+ granularity = response.granularity.value++ report_user_action(+ request.user,+ "tracing symbol stats queried",+ {+ "symbol_count": len(symbols or []),+ "matched_count": len(response.results),+ "granularity": granularity,+ },+ team=self.team,+ request=request,+ )++ return Response(+ {"results": [row.model_dump() for row in response.results], "granularity": granularity},+ status=status.HTTP_200_OK,+ )+@extend_schema(request=_TracingTimeseriesRequestSerializer)@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])def sparkline(self, request: Request, *args, **kwargs) -> Response:diff --git a/products/tracing/backend/symbol_stats_query_runner.py b/products/tracing/backend/symbol_stats_query_runner.pynew file mode 100644index 000000000000..873b8162ad57--- /dev/null+++ b/products/tracing/backend/symbol_stats_query_runner.py@@ -0,0 +1,425 @@+"""+Symbol-stats query runner.++Production latency for the functions in a single source file, aggregated from OpenTelemetry trace+spans that carry `code.*` source-location attributes. The client supplies the file path and the line+ranges of the symbols (functions) it cares about; the server attributes each span to the smallest+enclosing range and returns per-symbol stats (count, errors, total + p50/p95/p99 duration, and active+"busy" time where the SDK records it), each compared against the immediately-preceding equal-length+window.++Why ranges instead of grouping by line or function name:+- `code.function.name` is frequently absent in real spans, so the server can't group by function name.+- `code.line.number` may be a call site inside the body rather than the declaration line, so anchoring+ results to a single line is unreliable. A range supplied by the client's AST/LSP captures the span+ whether the SDK recorded the declaration or a call site.+- Percentiles do not compose, so they must be computed at range granularity here — the client cannot+ roll per-line percentiles up into a function.++The current and previous periods are computed in a single scan: the window is widened to span both,+and a per-span `is_current` flag drives conditional aggregates for each bucket.+"""++import math+import datetime as dt+from typing import TYPE_CHECKING+from zoneinfo import ZoneInfo++from posthog.schema import (+ CachedTraceSpansSymbolStatsQueryResponse,+ DateRange,+ IntervalType,+ PropertyGroupsMode,+ SourceSymbol,+ SymbolStatsGranularity,+ SymbolStatsPeriod,+ SymbolStatsRow,+ TraceSpansSymbolStatsQuery,+ TraceSpansSymbolStatsQueryResponse,+)++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode+from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange+from posthog.models.filters.mixins.utils import cached_property++from products.tracing.backend.logic import TIME_BUCKET_DATE_RANGE_WHERE++if TYPE_CHECKING:+ from posthog.models import Team+++# OTel deprecated `code.filepath`/`code.lineno` in favor of the stable+# `code.file.path`/`code.line.number`. Spans in the wild use either generation depending on the SDK+# version, so we read the first non-empty value across both. Current names come first; if OTel renames+# again, prepend the new name here. Ref:+# https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/+_CODE_FILE_PATH_KEYS = ["code.file.path", "code.filepath"]+_CODE_LINE_KEYS = ["code.line.number", "code.lineno"]++# Active span time excluding time spent awaiting children (Rust `tracing` style). Not standard OTel, so+# it is absent on most SDKs — surfaced as a parallel metric family the client uses only when present.+_BUSY_KEY = "busy_ns"++# Defensive ceiling on returned rows: one row per matched symbol (symbol mode) or per instrumented+# source line (line mode). Both are small in practice; this only guards a pathologically large file.+_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])+ 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],+ )+ return expr+++def _normalized_file_path_expr() -> ast.Expr:+ # Recorded paths may use Windows separators; normalize to '/' so suffix matching is uniform.+ return ast.Call(+ name="replaceAll",+ args=[_first_nonempty_str_attr(_CODE_FILE_PATH_KEYS), ast.Constant(value="\\"), ast.Constant(value="/")],+ )+++def _line_expr() -> ast.Expr:+ # Lines are 1-based, so a missing/unparseable line maps to 0, which falls outside every supplied+ # range (their startLine is >= 1) and is dropped by the outer `start_line > 0` filter.+ return ast.Call(name="toIntOrZero", args=[_first_nonempty_str_attr(_CODE_LINE_KEYS)])+++def _range_key_expr(symbols: list[SourceSymbol]) -> ast.Expr:+ # Map each span's line to the startLine of the smallest enclosing range, testing innermost-first+ # (largest startLine first) so a closure nested inside a function wins over the function. Conditions+ # reference the precomputed `raw_line` column (not the full line expression) so the multiIf stays small+ # regardless of symbol count. Spans matching no range fall through to 0 and are dropped downstream.+ args: list[ast.Expr] = []+ for symbol in sorted(symbols, key=lambda s: s.startLine, reverse=True):+ args.append(+ parse_expr(+ "raw_line >= {start} AND raw_line <= {end}",+ placeholders={+ "start": ast.Constant(value=symbol.startLine),+ "end": ast.Constant(value=symbol.endLine),+ },+ )+ )+ args.append(ast.Constant(value=symbol.startLine))+ args.append(ast.Constant(value=0))+ return ast.Call(name="multiIf", args=args)+++def _normalize_request_path(file_path: str) -> str:+ # The client sends a repo-relative path; strip a leading './' or '/' so the suffix match is+ # anchored on a path segment (otherwise endsWith on '/' + path would be distorted).+ path = file_path.replace("\\", "/").strip()+ while path.startswith("./"):+ path = path[2:]+ return path.lstrip("/")+++def _num(value: object) -> float:+ # quantileIf over a partition with no matching rows yields NaN; coerce it (and None) to 0.0 so the+ # response carries clean numbers and the client keys off the count, not NaN.+ f = float(value or 0) # type: ignore[arg-type]+ return 0.0 if math.isnan(f) else f+++def _pct_change(current: float, previous: float) -> float | None:+ # Undefined when there is no prior baseline — return null rather than a fake +inf so "new this+ # period" is distinguishable from a real delta.+ if previous <= 0:+ return None+ return (current - previous) / previous * 100.0+++class TraceSpansSymbolStatsQueryRunner(AnalyticsQueryRunner[TraceSpansSymbolStatsQueryResponse]):+ """Per-symbol latency stats for one source file, aggregated into client-supplied line ranges.++ Single-table ``GROUP BY`` over a window spanning the current and prior periods — no raw-span scan,+ no trace expansion, no ``GROUP BY trace_id``. One row per matched symbol, bounded by ``_MAX_RESULT_ROWS``.+ """++ query: TraceSpansSymbolStatsQuery+ cached_response: CachedTraceSpansSymbolStatsQueryResponse++ def __init__(self, query: TraceSpansSymbolStatsQuery, *args, **kwargs) -> None:+ super().__init__(query, *args, **kwargs)+ # UTC-pinned date constants (matching TIME_BUCKET_DATE_RANGE_WHERE) and Map-backed attribute+ # access both depend on these modifiers.+ self.modifiers.convertToProjectTimezone = False+ self.modifiers.propertyGroupsMode = PropertyGroupsMode.OPTIMIZED++ @cached_property+ def _now(self) -> dt.datetime:+ # One `now` shared by both windows so the current/previous boundary lines up exactly. UTC-aware+ # to match the runner's UTC pinning — a naive now() would shift the window by the server's offset+ # on a non-UTC host.+ return dt.datetime.now(tz=ZoneInfo("UTC"))++ @cached_property+ def query_date_range(self) -> QueryDateRange:+ return QueryDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ timezone_info=ZoneInfo("UTC"),+ now=self._now,+ )++ @cached_property+ def _previous_date_range(self) -> QueryPreviousPeriodDateRange:+ return QueryPreviousPeriodDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ timezone_info=ZoneInfo("UTC"),+ now=self._now,+ )++ @cached_property+ def settings(self) -> HogQLGlobalSettings:+ # Fail fast on a runaway scan — the path predicate is not backed by an index, and a wide window+ # over a hot attribute is expensive.+ return HogQLGlobalSettings(+ allow_experimental_object_type=False,+ max_execution_time=30,+ max_bytes_to_read=10_000_000_000,+ read_overflow_mode="throw",+ )++ def to_query(self) -> ast.SelectQuery:+ req = _normalize_request_path(self.query.filePath)++ # Segment-anchored suffix match: the recorded path equals the request, or ends with+ # '/' + request. So `feature-flags/src/flags/flag_matching.rs` matches a request for+ # `src/flags/flag_matching.rs`, while `crate-b/src/mod.rs` does not match `crate-a/src/mod.rs`.+ path_predicate = parse_expr(+ "{path} = {req} OR endsWith({path_dup}, {req_slash})",+ placeholders={+ "path": _normalized_file_path_expr(),+ "path_dup": _normalized_file_path_expr(),+ "req": ast.Constant(value=req),+ "req_slash": ast.Constant(value="/" + req),+ },+ )++ # Scan a single window spanning both periods: [previous start, current end). The previous window+ # ends exactly where the current one begins, so a span is "current" iff timestamp >= current start.+ current_start = self.query_date_range.date_from()+ scan_lower = self._previous_date_range.date_from()+ scan_upper = self.query_date_range.date_to()+ span_placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=scan_lower),+ "date_to": ast.Constant(value=scan_upper),+ }++ # The explicit timestamp bounds below (plus the day-grain time_bucket prune) fully define the+ # scan window, so no HogQLFilters/{filters} placeholder is needed — one source of truth.+ inner_where = ast.And(+ exprs=[+ parse_expr(TIME_BUCKET_DATE_RANGE_WHERE, placeholders=span_placeholders),+ parse_expr("timestamp >= {date_from} AND timestamp < {date_to}", placeholders=span_placeholders),+ path_predicate,+ ]+ )++ # Bucket each span by the smallest enclosing symbol range when symbols are supplied, otherwise by+ # its own source line. The line value is computed once as `raw_line` in the innermost scan; the+ # bucket key references that column (so the multiIf stays small). Either way the key is aliased+ # `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)+ query = parse_select(+ """+ SELECT+ line,+ countIf(is_current) AS count,+ countIf(is_current AND status_code = 2) AS error_count,+ sumIf(duration_nano, is_current) AS sum_duration_nano,+ quantileIf(0.5)(duration_nano, is_current) AS p50_duration_nano,+ quantileIf(0.95)(duration_nano, is_current) AS p95_duration_nano,+ quantileIf(0.99)(duration_nano, is_current) AS p99_duration_nano,+ countIf(is_current AND has_busy) AS busy_count,+ quantileIf(0.5)(busy_nano, is_current AND has_busy) AS p50_busy_nano,+ quantileIf(0.95)(busy_nano, is_current AND has_busy) AS p95_busy_nano,+ quantileIf(0.99)(busy_nano, is_current AND has_busy) AS p99_busy_nano,+ countIf(NOT is_current) AS prev_count,+ countIf((NOT is_current) AND status_code = 2) AS prev_error_count,+ sumIf(duration_nano, NOT is_current) AS prev_sum_duration_nano,+ quantileIf(0.5)(duration_nano, NOT is_current) AS prev_p50_duration_nano,+ quantileIf(0.95)(duration_nano, NOT is_current) AS prev_p95_duration_nano,+ quantileIf(0.99)(duration_nano, NOT is_current) AS prev_p99_duration_nano,+ countIf((NOT is_current) AND has_busy) AS prev_busy_count,+ quantileIf(0.5)(busy_nano, (NOT is_current) AND has_busy) AS prev_p50_busy_nano,+ quantileIf(0.95)(busy_nano, (NOT is_current) AND has_busy) AS prev_p95_busy_nano,+ quantileIf(0.99)(busy_nano, (NOT is_current) AND has_busy) AS prev_p99_busy_nano+ FROM (+ SELECT+ {bucket_key} AS line,+ status_code,+ duration_nano,+ busy_nano,+ has_busy,+ is_current+ FROM (+ SELECT+ {line_expr} AS raw_line,+ status_code,+ duration_nano,+ {busy_expr} AS busy_nano,+ {has_busy_expr} AS has_busy,+ timestamp >= {current_start} AS is_current+ FROM posthog.trace_spans+ WHERE {inner_where}+ )+ )+ WHERE line > 0+ GROUP BY line+ HAVING count > 0 OR prev_count > 0+ ORDER BY line ASC+ LIMIT {limit}+ """,+ placeholders={+ "bucket_key": bucket_key,+ "line_expr": _line_expr(),+ "busy_expr": ast.Call(name="toFloatOrZero", args=[busy_field]),+ # 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)}+ ),+ "current_start": ast.Constant(value=current_start),+ "inner_where": inner_where,+ "limit": ast.Constant(value=_MAX_RESULT_ROWS),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query++ def _calculate(self) -> TraceSpansSymbolStatsQueryResponse:+ # Symbol mode buckets by client-supplied ranges; line mode (no symbols) buckets by source line.+ granularity = SymbolStatsGranularity.SYMBOL if self.query.symbols else SymbolStatsGranularity.LINE++ # An empty path would degenerate the suffix match into "ends with '/'" — nothing to aggregate.+ if not _normalize_request_path(self.query.filePath):+ return TraceSpansSymbolStatsQueryResponse(results=[], granularity=granularity)++ response = execute_hogql_query(+ query_type=self.query.kind,+ query=self.to_query(),+ modifiers=self.modifiers,+ team=self.team,+ workload=Workload.LOGS,+ timings=self.timings,+ limit_context=self.limit_context,+ settings=self.settings,+ )++ # In symbol mode, map each row's bucket line (== the symbol's startLine) back to the requested+ # symbol so we can echo its name/endLine. Line mode has no symbols, so these stay null.+ symbols_by_start = {symbol.startLine: symbol for symbol in (self.query.symbols or [])}+ return TraceSpansSymbolStatsQueryResponse(+ results=[self._row_from_clickhouse(row, symbols_by_start) for row in response.results],+ granularity=granularity,+ )++ def _row_from_clickhouse(self, row: list, symbols_by_start: dict[int, SourceSymbol]) -> SymbolStatsRow:+ # Unpack positionally in the SELECT's column order — an added/removed column then fails loudly+ # on arity rather than silently shifting every index.+ (+ line,+ count,+ error_count,+ sum_duration_nano,+ p50_duration_nano,+ p95_duration_nano,+ p99_duration_nano,+ busy_count,+ p50_busy_nano,+ p95_busy_nano,+ p99_busy_nano,+ prev_count,+ prev_error_count,+ prev_sum_duration_nano,+ prev_p50_duration_nano,+ prev_p95_duration_nano,+ prev_p99_duration_nano,+ prev_busy_count,+ prev_p50_busy_nano,+ prev_p95_busy_nano,+ prev_p99_busy_nano,+ ) = row++ line = int(line)+ symbol = symbols_by_start.get(line)+ symbol_name, symbol_end_line = (symbol.name, symbol.endLine) if symbol else (None, None)+ current_count = count or 0+ current_p95 = _num(p95_duration_nano)+ previous = SymbolStatsPeriod(+ count=prev_count or 0,+ error_count=prev_error_count or 0,+ sum_duration_nano=_num(prev_sum_duration_nano),+ p50_duration_nano=_num(prev_p50_duration_nano),+ p95_duration_nano=_num(prev_p95_duration_nano),+ p99_duration_nano=_num(prev_p99_duration_nano),+ busy_count=prev_busy_count or 0,+ p50_busy_nano=_num(prev_p50_busy_nano),+ p95_busy_nano=_num(prev_p95_busy_nano),+ p99_busy_nano=_num(prev_p99_busy_nano),+ )+ return SymbolStatsRow(+ line=line,+ name=symbol_name,+ end_line=symbol_end_line,+ count=current_count,+ error_count=error_count or 0,+ sum_duration_nano=_num(sum_duration_nano),+ p50_duration_nano=_num(p50_duration_nano),+ p95_duration_nano=current_p95,+ p99_duration_nano=_num(p99_duration_nano),+ busy_count=busy_count or 0,+ p50_busy_nano=_num(p50_busy_nano),+ p95_busy_nano=_num(p95_busy_nano),+ p99_busy_nano=_num(p99_busy_nano),+ previous=previous,+ count_pct_change=_pct_change(current_count, previous.count),+ p95_duration_pct_change=_pct_change(current_p95, previous.p95_duration_nano),+ )++ def run(self, *args, **kwargs) -> TraceSpansSymbolStatsQueryResponse | CachedTraceSpansSymbolStatsQueryResponse:+ response = super().run(*args, **kwargs)+ assert isinstance(response, TraceSpansSymbolStatsQueryResponse | CachedTraceSpansSymbolStatsQueryResponse)+ return response+++def run_symbol_stats_query(+ *,+ team: "Team",+ file_path: str,+ date_range: DateRange,+ symbols: list[SourceSymbol] | None = None,+) -> TraceSpansSymbolStatsQueryResponse | CachedTraceSpansSymbolStatsQueryResponse:+ """Facade-friendly entry point: per-line (no symbols) or per-symbol latency stats for one source file."""+ query = TraceSpansSymbolStatsQuery(dateRange=date_range, filePath=file_path, symbols=symbols)+ runner = TraceSpansSymbolStatsQueryRunner(query, team)+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(response, TraceSpansSymbolStatsQueryResponse | CachedTraceSpansSymbolStatsQueryResponse)+ return responsediff --git a/products/tracing/backend/tests/test_symbol_stats.py b/products/tracing/backend/tests/test_symbol_stats.pynew file mode 100644index 000000000000..fd62091cf494--- /dev/null+++ b/products/tracing/backend/tests/test_symbol_stats.py@@ -0,0 +1,279 @@+import datetime as dt++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute++from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase++MS = 1_000_000 # ns per ms++# The query window is DATE_FROM..DATE_TO = 2026-06-02 07:00..09:00 (a 2h "current" period); the prior+# equal-length window is 05:00..07:00 ("previous"). "outside" spans sit on a different day and must be+# excluded from both.+_TS = {+ "current": dt.datetime(2026, 6, 2, 8, 0, 0),+ "previous": dt.datetime(2026, 6, 2, 6, 0, 0),+ "outside": dt.datetime(2026, 6, 1, 8, 0, 0),+}++# (file_path, line, generation, status_code, duration_ms, busy_ns | None, period)+#+# flag_matching.rs models match_flags [459, 826] with a closure [500, 520] nested inside it, plus+# evaluate_flags_in_level [900, 980]:+# - match_flags has spans in both periods (current is busier + slower → positive pct_change),+# - the closure is new this period (no previous spans → null pct_change),+# - evaluate went quiet (previous only, zero current → -100%).+SPANS = [+ ("feature-flags/src/flags/flag_matching.rs", 459, "current", 0, 100, 50000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 459, "current", 0, 100, 50000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 459, "current", 0, 100, 50000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 459, "current", 2, 100, 50000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 470, "current", 0, 100, 50000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 470, "current", 0, 100, 50000, "current"),+ # Previous-window match_flags spans use the LEGACY attribute generation, so the prior period is+ # aggregated via code.lineno/code.filepath while the current period uses the stable keys — exercising+ # both generations across the two buckets of one symbol. One is an error (covers prev_error_count).+ ("feature-flags/src/flags/flag_matching.rs", 459, "legacy", 0, 50, 50000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 459, "legacy", 0, 50, 50000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 459, "legacy", 2, 50, 50000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 510, "current", 0, 200, 80000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 510, "current", 0, 200, 80000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 510, "current", 0, 200, 80000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 510, "current", 0, 200, 80000, "current"),+ ("feature-flags/src/flags/flag_matching.rs", 900, "current", 0, 50, 20000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 900, "current", 0, 50, 20000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 900, "current", 0, 50, 20000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 900, "current", 0, 50, 20000, "previous"),+ ("feature-flags/src/flags/flag_matching.rs", 900, "current", 0, 50, 20000, "previous"),+ # Legacy attribute generation, no busy_ns — fn [10, 50], current only.+ ("svc/src/legacy.rs", 10, "legacy", 0, 30, None, "current"),+ ("svc/src/legacy.rs", 10, "legacy", 0, 30, None, "current"),+ ("svc/src/legacy.rs", 20, "legacy", 2, 30, None, "current"),+ # Both generations on one function must merge — fn [1, 100], current.+ ("svc/src/mixed.rs", 5, "legacy", 0, 40, None, "current"),+ ("svc/src/mixed.rs", 5, "legacy", 0, 40, None, "current"),+ ("svc/src/mixed.rs", 6, "current", 0, 40, None, "current"),+ ("svc/src/mixed.rs", 6, "current", 0, 40, None, "current"),+ ("svc/src/mixed.rs", 6, "current", 0, 40, None, "current"),+ # Same basename, different directories — fn [10, 30] in each, current.+ ("crate-a/src/mod.rs", 15, "current", 0, 10, None, "current"),+ ("crate-a/src/mod.rs", 15, "current", 0, 10, None, "current"),+ ("crate-b/src/mod.rs", 15, "current", 0, 10, None, "current"),+ ("crate-b/src/mod.rs", 15, "current", 0, 10, None, "current"),+ ("crate-b/src/mod.rs", 15, "current", 0, 10, None, "current"),+ # fn [1, 50]: two spans in the current window, one in the previous, one outside both (must be dropped).+ ("window/src/file.rs", 5, "current", 0, 10, None, "current"),+ ("window/src/file.rs", 5, "current", 0, 10, None, "current"),+ ("window/src/file.rs", 6, "current", 0, 10, None, "previous"),+ ("window/src/file.rs", 7, "current", 0, 10, None, "outside"),+]++FM_SYMBOLS = [+ {"name": "match_flags", "startLine": 459, "endLine": 826},+ {"name": "closure", "startLine": 500, "endLine": 520},+ {"name": "evaluate_flags_in_level", "startLine": 900, "endLine": 980},+]+++def _attr_map(path: str, line: int, generation: str, busy: int | None) -> str:+ if generation == "current":+ pairs = [("code.file.path__str", path), ("code.line.number__str", str(line))]+ else:+ pairs = [("code.filepath__str", path), ("code.lineno__str", str(line))]+ if busy is not None:+ pairs.append(("busy_ns__str", str(busy)))+ return "map(" + ", ".join(f"'{k}', '{v}'" for k, v in pairs) + ")"+++class TestTraceSpansSymbolStats(_TraceSpansTestBase):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls._recreate_trace_spans_tables()++ rows: list[str] = []+ for i, (path, line, generation, status_code, duration_ms, busy, period) in enumerate(SPANS):+ base = _TS[period]+ end = base + dt.timedelta(milliseconds=duration_ms)+ trace_id = _b64(i.to_bytes(16, "big"))+ span_id = _b64((1000 + i).to_bytes(8, "big"))+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")+ end_str = end.strftime("%Y-%m-%d %H:%M:%S.%f")+ rows.append(+ f"('019e8758-0000-0000-0000-{i:012d}', {cls.team.id}, '{trace_id}', '{span_id}', '', "+ f"'GET', 3, '{ts_str}', '{end_str}', '{ts_str}', {status_code}, 'svc', "+ f"{_attr_map(path, line, generation, busy)}, map())"+ )+ 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 _post(self, file_path: str, symbols: list[dict] | None = None) -> dict:+ query: dict = {"filePath": file_path, "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}}+ if symbols is not None:+ query["symbols"] = symbols+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/symbol-stats/",+ {"query": query},+ format="json",+ )+ self.assertEqual(response.status_code, 200, response.content)+ return response.json()++ def _symbol_stats(self, file_path: str, symbols: list[dict]) -> list[dict]:+ return self._post(file_path, symbols)["results"]++ def test_buckets_into_smallest_enclosing_range(self):+ # Suffix match: request the repo-relative path; recorded path carries a `feature-flags/` prefix.+ rows = self._symbol_stats("src/flags/flag_matching.rs", FM_SYMBOLS)+ by_line = {r["line"]: r for r in rows}++ # match_flags gets its declaration-line (459 ×4) + in-body (470 ×2) spans, but NOT the closure's+ # spans — line 510 lands in the closure, the innermost enclosing range.+ self.assertEqual(by_line[459]["count"], 6)+ self.assertEqual(by_line[459]["error_count"], 1)+ self.assertEqual(by_line[459]["name"], "match_flags")+ self.assertEqual(by_line[500]["count"], 4)+ self.assertEqual(by_line[500]["name"], "closure")+ # evaluate is current-empty but surfaces because it had spans in the previous period.+ self.assertEqual(by_line[900]["count"], 0)+ self.assertEqual([r["line"] for r in rows], [459, 500, 900])++ def test_duration_and_busy_metrics(self):+ by_line = {r["line"]: r for r in self._symbol_stats("src/flags/flag_matching.rs", FM_SYMBOLS)}+ # match_flags current: 6 spans all 100ms, busy 50000.+ self.assertEqual(by_line[459]["p95_duration_nano"], 100 * MS)+ self.assertEqual(by_line[459]["sum_duration_nano"], 6 * 100 * MS)+ self.assertEqual(by_line[459]["busy_count"], 6)+ self.assertEqual(by_line[459]["p50_busy_nano"], 50000)+ # closure current: 4 spans all 200ms.+ self.assertEqual(by_line[500]["p50_duration_nano"], 200 * MS)++ def test_compares_against_previous_period(self):+ by_line = {r["line"]: r for r in self._symbol_stats("src/flags/flag_matching.rs", FM_SYMBOLS)}++ # match_flags: current 6 spans @100ms vs previous 3 spans @50ms (recorded via legacy keys) → +100%.+ # The previous block exercises every prev_* aggregate, incl. the negated-condition error/sum/busy.+ previous = by_line[459]["previous"]+ self.assertEqual(previous["count"], 3)+ self.assertEqual(previous["error_count"], 1)+ self.assertEqual(previous["sum_duration_nano"], 3 * 50 * MS)+ self.assertEqual(previous["p95_duration_nano"], 50 * MS)+ self.assertEqual(previous["busy_count"], 3)+ self.assertEqual(previous["p50_busy_nano"], 50000)+ self.assertEqual(by_line[459]["count_pct_change"], 100.0)+ self.assertEqual(by_line[459]["p95_duration_pct_change"], 100.0)++ # closure: new this period (no previous spans) → pct_change is null, not a fake +inf.+ self.assertEqual(by_line[500]["previous"]["count"], 0)+ self.assertIsNone(by_line[500]["count_pct_change"])+ self.assertIsNone(by_line[500]["p95_duration_pct_change"])++ # evaluate: went quiet (previous only) → surfaces with -100%.+ self.assertEqual(by_line[900]["previous"]["count"], 5)+ self.assertEqual(by_line[900]["count_pct_change"], -100.0)+ self.assertEqual(by_line[900]["p95_duration_pct_change"], -100.0)++ def test_busy_absent_yields_zero_count_and_no_name(self):+ rows = self._symbol_stats("svc/src/legacy.rs", [{"startLine": 10, "endLine": 50}])+ by_line = {r["line"]: r for r in rows}+ # Legacy attribute generation still buckets (lines 10 and 20 fall in [10, 50]).+ self.assertEqual(by_line[10]["count"], 3)+ self.assertEqual(by_line[10]["error_count"], 1)+ # No busy_ns on these spans → busy family is not meaningful.+ self.assertEqual(by_line[10]["busy_count"], 0)+ self.assertEqual(by_line[10]["p50_busy_nano"], 0)+ # No name supplied, no prior-period spans.+ self.assertIsNone(by_line[10]["name"])+ self.assertEqual(by_line[10]["previous"]["count"], 0)+ self.assertIsNone(by_line[10]["count_pct_change"])++ def test_merges_both_attribute_generations(self):+ rows = self._symbol_stats("svc/src/mixed.rs", [{"startLine": 1, "endLine": 100}])+ self.assertEqual([(r["line"], r["count"]) for r in rows], [(1, 5)])++ @parameterized.expand([("crate-a/src/mod.rs", 2), ("crate-b/src/mod.rs", 3)])+ def test_same_basename_not_cross_attributed(self, file_path, expected_count):+ rows = self._symbol_stats(file_path, [{"startLine": 10, "endLine": 30}])+ self.assertEqual([(r["line"], r["count"]) for r in rows], [(10, expected_count)])++ def test_each_period_window_is_respected(self):+ rows = self._symbol_stats("window/src/file.rs", [{"startLine": 1, "endLine": 50}])+ by_line = {r["line"]: r for r in rows}+ # Two spans in the current window, one in the previous, one outside both. The outside span would+ # push current to 3 (or previous to 2) if it leaked, so the exact counts prove it was excluded.+ self.assertEqual(by_line[1]["count"], 2)+ self.assertEqual(by_line[1]["previous"]["count"], 1)+ self.assertEqual(by_line[1]["p95_duration_nano"], 10 * MS)+ self.assertEqual(by_line[1]["count_pct_change"], 100.0)++ def test_symbol_enclosing_no_spans_returns_empty(self):+ self.assertEqual(self._symbol_stats("src/flags/flag_matching.rs", [{"startLine": 1, "endLine": 5}]), [])++ def test_untraced_file_returns_empty(self):+ self.assertEqual(self._symbol_stats("does/not/exist.rs", [{"startLine": 1, "endLine": 100}]), [])++ def test_omitting_symbols_aggregates_per_line(self):+ # No symbols → one row per actual source line; lines are NOT collapsed into ranges.+ payload = self._post("src/flags/flag_matching.rs")+ self.assertEqual(payload["granularity"], "line")+ by_line = {r["line"]: r for r in payload["results"]}+ # 459, 470, 510 stay distinct (in symbol mode 470 folds into match_flags and 510 into the closure).+ self.assertEqual(sorted(by_line), [459, 470, 510, 900])+ self.assertEqual(by_line[459]["count"], 4)+ self.assertEqual(by_line[459]["previous"]["count"], 3)+ self.assertEqual(by_line[470]["count"], 2)+ self.assertEqual(by_line[510]["count"], 4)+ self.assertEqual(by_line[900]["count"], 0)+ self.assertEqual(by_line[900]["previous"]["count"], 5)+ # Line mode echoes no symbol identity.+ self.assertIsNone(by_line[459]["name"])+ self.assertIsNone(by_line[459]["end_line"])++ def test_single_whole_file_range_gives_file_total(self):+ payload = self._post("src/flags/flag_matching.rs", [{"name": "whole", "startLine": 1, "endLine": 100000}])+ self.assertEqual(payload["granularity"], "symbol")+ self.assertEqual(len(payload["results"]), 1)+ row = payload["results"][0]+ self.assertEqual(row["line"], 1)+ self.assertEqual(row["name"], "whole")+ self.assertEqual(row["end_line"], 100000)+ # Every current span in the file (459×4 + 470×2 + 510×4) folds into one bucket; previous = 459×3 + 900×5.+ self.assertEqual(row["count"], 10)+ self.assertEqual(row["previous"]["count"], 8)++ def test_symbol_mode_reports_symbol_granularity(self):+ self.assertEqual(self._post("src/flags/flag_matching.rs", FM_SYMBOLS)["granularity"], "symbol")++ def test_missing_file_path_returns_400(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/symbol-stats/",+ {"query": {"symbols": FM_SYMBOLS, "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}}},+ format="json",+ )+ self.assertEqual(response.status_code, 400, response.content)++ @parameterized.expand(+ [+ ("inverted_range", [{"startLine": 50, "endLine": 10}]),+ ("zero_start_line", [{"startLine": 0, "endLine": 5}]),+ ("duplicate_start_line", [{"startLine": 10, "endLine": 20}, {"startLine": 10, "endLine": 30}]),+ ("too_many_symbols", [{"startLine": i, "endLine": i} for i in range(1, 1002)]),+ ]+ )+ def test_invalid_symbols_return_400(self, _name, symbols):+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/symbol-stats/",+ {+ "query": {+ "filePath": "src/flags/flag_matching.rs",+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},+ "symbols": symbols,+ }+ },+ format="json",+ )+ self.assertEqual(response.status_code, 400, response.content)diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 441d92d12a89..59a9bd828f59 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -275,6 +275,129 @@ export interface _TracingQueryRequestApi {query: _TracingQueryBodyApi}+export interface _SymbolStatsSymbolApi {+ /**+ * Opaque identifier (e.g. the function name) echoed back on the matching result row.+ * @nullable+ */+ name?: string | null+ /**+ * First line of the symbol's range, inclusive.+ * @minimum 1+ */+ startLine: number+ /**+ * Last line of the symbol's range, inclusive.+ * @minimum 1+ */+ endLine: number+}++export interface _SymbolStatsQueryBodyApi {+ /** Repo-relative path of the source file to aggregate (e.g. 'src/flags/flag_matching.rs'). Matched as a path suffix against the recorded OTel code.file.path / code.filepath, so a recorded path carrying an extra crate/workspace prefix still matches. Separators are normalized. */+ filePath: string+ /** Current period to aggregate over; the prior equal-length window is the comparison. Defaults to last 24h. */+ dateRange?: _TracingDateRangeApi+ /** Optional symbol (function) line ranges, supplied by the client from its own AST/LSP. When given, each span is attributed to the smallest enclosing range (one row per symbol). When omitted (or an empty list), spans are aggregated per source line (one row per line); pass a single whole-file range for a file-level total. */+ symbols?: _SymbolStatsSymbolApi[]+}++export interface _SymbolStatsRequestApi {+ /** The symbol-stats per-symbol aggregation query to execute. */+ query: _SymbolStatsQueryBodyApi+}++export interface _SymbolStatsPeriodApi {+ /** Number of spans attributed to this symbol in the period. */+ count: number+ /** Spans whose OTel status is Error (status_code = 2). */+ error_count: number+ /** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */+ sum_duration_nano: number+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number+ /** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: number+ /** Median active (busy) time, in nanoseconds. Excludes awaiting children. */+ p50_busy_nano: number+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number+}++export interface _SymbolStatsRowApi {+ /** Number of spans attributed to this symbol in the period. */+ count: number+ /** Spans whose OTel status is Error (status_code = 2). */+ error_count: number+ /** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */+ sum_duration_nano: number+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number+ /** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: number+ /** Median active (busy) time, in nanoseconds. Excludes awaiting children. */+ p50_busy_nano: number+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number+ /** Bucket anchor: the source line (line mode) or the symbol's startLine (symbol mode). */+ line: number+ /**+ * Echoed name from the requested symbol (symbol mode only).+ * @nullable+ */+ name?: string | null+ /**+ * endLine of the matched symbol's range (symbol mode only).+ * @nullable+ */+ end_line?: number | null+ /** The same metrics over the immediately-preceding equal-length period. */+ previous: _SymbolStatsPeriodApi+ /**+ * Percentage change in count vs the previous period (180 = +180%). Null when there is no baseline (previous count 0). Use `previous.count` — not a null here — to detect a new symbol.+ * @nullable+ */+ count_pct_change: number | null+ /**+ * Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous p95 is 0 (no comparable baseline), which can occur even when previous.count > 0 — do not read null as 'new symbol'.+ * @nullable+ */+ p95_duration_pct_change: number | null+}++/**+ * * `line` - line+ * * `symbol` - symbol+ */+export type GranularityEnumApi = (typeof GranularityEnumApi)[keyof typeof GranularityEnumApi]++export const GranularityEnumApi = {+ Line: 'line',+ Symbol: 'symbol',+} as const++export interface _SymbolStatsResponseApi {+ /** One row per bucket, ordered by line ascending. */+ results: _SymbolStatsRowApi[]+ /** Bucketing applied: 'line' when no symbols were supplied, 'symbol' otherwise.+ *+ * * `line` - line+ * * `symbol` - symbol */+ granularity: GranularityEnumApi+}+export interface _TracingTraceRequestApi {/** Date range for the query. Defaults to last 24 hours. */dateRange?: _TracingDateRangeApidiff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 714aa0ad19c4..f4d7ae483141 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -13,6 +13,8 @@ import type {TracingSpansServiceNamesRetrieveParams,TracingSpansValuesRetrieveParams,_HasSpansResponseApi,+ _SymbolStatsRequestApi,+ _SymbolStatsResponseApi,_TracingAggregationRequestApi,_TracingAttributeBreakdownRequestApi,_TracingCountRequestApi,@@ -199,6 +201,23 @@ export const tracingSpansSparklineCreate = async (})}+export const getTracingSpansSymbolStatsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tracing/spans/symbol-stats/`+}++export const tracingSpansSymbolStatsCreate = async (+ projectId: string,+ _symbolStatsRequestApi: _SymbolStatsRequestApi,+ options?: RequestInit+): Promise<_SymbolStatsResponseApi> => {+ return apiMutator<_SymbolStatsResponseApi>(getTracingSpansSymbolStatsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_symbolStatsRequestApi),+ })+}+export const getTracingSpansTraceCreateUrl = (projectId: string, traceId: string) => {return `/api/projects/${projectId}/tracing/spans/trace/${traceId}/`}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 5b7db493f17d..b9fd26be4229 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -564,6 +564,52 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({.describe('The sparkline \/ duration-histogram query to execute.'),})+export const TracingSpansSymbolStatsCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ filePath: zod+ .string()+ .describe(+ "Repo-relative path of the source file to aggregate (e.g. 'src\/flags\/flag_matching.rs'). Matched as a path suffix against the recorded OTel code.file.path \/ code.filepath, so a recorded path carrying an extra crate\/workspace prefix still matches. Separators are normalized."+ ),+ 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(+ 'Current period to aggregate over; the prior equal-length window is the comparison. Defaults to last 24h.'+ ),+ symbols: zod+ .array(+ zod.object({+ name: zod+ .string()+ .nullish()+ .describe(+ 'Opaque identifier (e.g. the function name) echoed back on the matching result row.'+ ),+ startLine: zod.number().min(1).describe("First line of the symbol's range, inclusive."),+ endLine: zod.number().min(1).describe("Last line of the symbol's range, inclusive."),+ })+ )+ .optional()+ .describe(+ 'Optional symbol (function) line ranges, supplied by the client from its own AST\/LSP. When given, each span is attributed to the smallest enclosing range (one row per symbol). When omitted (or an empty list), spans are aggregated per source line (one row per line); pass a single whole-file range for a file-level total.'+ ),+ })+ .describe('The symbol-stats per-symbol aggregation query to execute.'),+})+export const tracingSpansTraceCreateBodyExcludeAttributesDefault = falseexport const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex 76c4b7761caa..85a2dc0e2a6c 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -206,3 +206,6 @@ tools:tracing-spans-has-spans-retrieve:operation: tracing_spans_has_spans_retrieveenabled: false+ tracing-spans-symbol-stats-create:+ operation: tracing_spans_symbol_stats_create+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 494a0540100c..48a8e9a100b5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22488,6 +22488,18 @@ export namespace Schemas {notes: string[];}+ /**+ * * `line` - line+ * * `symbol` - symbol+ */+ export type GranularityEnum = typeof GranularityEnum[keyof typeof GranularityEnum];+++ export const GranularityEnum = {+ Line: 'line',+ Symbol: 'symbol',+ } as const;+export interface Group {/*** @minimum -2147483648@@ -48633,6 +48645,29 @@ export namespace Schemas {url: string;}+ export interface _SymbolStatsPeriod {+ /** Number of spans attributed to this symbol in the period. */+ count: number;+ /** Spans whose OTel status is Error (status_code = 2). */+ error_count: number;+ /** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */+ sum_duration_nano: number;+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number;+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number;+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number;+ /** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: number;+ /** Median active (busy) time, in nanoseconds. Excludes awaiting children. */+ p50_busy_nano: number;+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number;+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number;+ }+export interface _TracingDateRange {/*** Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.@@ -48646,6 +48681,95 @@ export namespace Schemas {date_to?: string | null;}+ export interface _SymbolStatsSymbol {+ /**+ * Opaque identifier (e.g. the function name) echoed back on the matching result row.+ * @nullable+ */+ name?: string | null;+ /**+ * First line of the symbol's range, inclusive.+ * @minimum 1+ */+ startLine: number;+ /**+ * Last line of the symbol's range, inclusive.+ * @minimum 1+ */+ endLine: number;+ }++ export interface _SymbolStatsQueryBody {+ /** Repo-relative path of the source file to aggregate (e.g. 'src/flags/flag_matching.rs'). Matched as a path suffix against the recorded OTel code.file.path / code.filepath, so a recorded path carrying an extra crate/workspace prefix still matches. Separators are normalized. */+ filePath: string;+ /** Current period to aggregate over; the prior equal-length window is the comparison. Defaults to last 24h. */+ dateRange?: _TracingDateRange;+ /** Optional symbol (function) line ranges, supplied by the client from its own AST/LSP. When given, each span is attributed to the smallest enclosing range (one row per symbol). When omitted (or an empty list), spans are aggregated per source line (one row per line); pass a single whole-file range for a file-level total. */+ symbols?: _SymbolStatsSymbol[];+ }++ export interface _SymbolStatsRequest {+ /** The symbol-stats per-symbol aggregation query to execute. */+ query: _SymbolStatsQueryBody;+ }++ export interface _SymbolStatsRow {+ /** Number of spans attributed to this symbol in the period. */+ count: number;+ /** Spans whose OTel status is Error (status_code = 2). */+ error_count: number;+ /** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */+ sum_duration_nano: number;+ /** Median wall-clock span duration, in nanoseconds. */+ p50_duration_nano: number;+ /** 95th-percentile wall-clock span duration, in nanoseconds. */+ p95_duration_nano: number;+ /** 99th-percentile wall-clock span duration, in nanoseconds. */+ p99_duration_nano: number;+ /** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */+ busy_count: number;+ /** Median active (busy) time, in nanoseconds. Excludes awaiting children. */+ p50_busy_nano: number;+ /** 95th-percentile active (busy) time, in nanoseconds. */+ p95_busy_nano: number;+ /** 99th-percentile active (busy) time, in nanoseconds. */+ p99_busy_nano: number;+ /** Bucket anchor: the source line (line mode) or the symbol's startLine (symbol mode). */+ line: number;+ /**+ * Echoed name from the requested symbol (symbol mode only).+ * @nullable+ */+ name?: string | null;+ /**+ * endLine of the matched symbol's range (symbol mode only).+ * @nullable+ */+ end_line?: number | null;+ /** The same metrics over the immediately-preceding equal-length period. */+ previous: _SymbolStatsPeriod;+ /**+ * Percentage change in count vs the previous period (180 = +180%). Null when there is no baseline (previous count 0). Use `previous.count` — not a null here — to detect a new symbol.+ * @nullable+ */+ count_pct_change: number | null;+ /**+ * Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous p95 is 0 (no comparable baseline), which can occur even when previous.count > 0 — do not read null as 'new symbol'.+ * @nullable+ */+ p95_duration_pct_change: number | null;+ }++ export interface _SymbolStatsResponse {+ /** One row per bucket, ordered by line ascending. */+ results: _SymbolStatsRow[];+ /** Bucketing applied: 'line' when no symbols were supplied, 'symbol' otherwise.+ *+ * * `line` - line+ * * `symbol` - symbol */+ granularity: GranularityEnum;+ }+export interface _TracingAggregationQueryBody {/** Date range for the primary window. Defaults to last hour. */dateRange?: _TracingDateRange;