Skip to content

: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.

feat(tracing): surface span resource attributes (#63192)

Jon McCallum5a06b22e1695
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index 71fbc9bcb938..d07c8595eae5 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -359,9 +359,11 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
"trace_start": (result[13] or result[8]).replace(tzinfo=ZoneInfo("UTC")),
# OTel span attributes the user set, as a key-value map.
"attributes": result[14],
+ # OTel resource attributes (who/what emitted the span: service.version, host, k8s, ...).
+ "resource_attributes": result[15],
# Per-trace duration key (max matching-span duration); the offset-pagination key for
# the slowest/fastest sorts. Falls back to this row's own duration.
- "trace_duration": result[15] if result[15] is not None else result[10],
+ "trace_duration": result[16] if result[16] is not None else result[10],
}
results.append(row)
@@ -501,6 +503,7 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
{where} as matched_filter,
min(if({where_for_start}, timestamp, NULL)) OVER (PARTITION BY trace_id) as trace_start,
{attributes},
+ {resource_attributes},
max(if({where_for_start}, duration_nano, NULL)) OVER (PARTITION BY trace_id) as trace_duration
FROM posthog.trace_spans
WHERE {filters} AND trace_id IN ({trace_id_query}) LIMIT {limit}
@@ -511,10 +514,14 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
"trace_id_query": trace_id_query,
"limit": ast.Constant(value=(self.query.limit or 1) * limit_by_n),
"filters": ast.Placeholder(expr=ast.Field(chain=["filters"])),
- # The attribute map dominates payload size (db.statement holds multi-KB SQL). When
- # excluded we still SELECT a column so the positional result mapping stays stable —
- # an empty map instead of the real one.
+ # The attribute maps dominate payload size (db.statement holds multi-KB SQL;
+ # process.command_args etc. bulk up the resource map). When excluded we still
+ # SELECT a column so the positional result mapping stays stable — an empty map
+ # instead of the real one.
"attributes": parse_expr("map() AS attributes" if self.query.excludeAttributes else "attributes"),
+ "resource_attributes": parse_expr(
+ "map() AS resource_attributes" if self.query.excludeAttributes else "resource_attributes"
+ ),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 5a328fe1c319..270dbc2a8c6f 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -158,7 +158,7 @@ class _TracingQueryBodySerializer(serializers.Serializer):
excludeAttributes = serializers.BooleanField(
required=False,
default=False,
- help_text="Omit the per-span attributes map from results to keep payloads compact. Defaults to false.",
+ help_text="Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
)
@@ -174,7 +174,7 @@ class _TracingTraceRequestSerializer(serializers.Serializer):
excludeAttributes = serializers.BooleanField(
required=False,
default=False,
- help_text="Omit the per-span attributes map from results to keep payloads compact. Defaults to false.",
+ help_text="Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
)
diff --git a/products/tracing/backend/tests/test_exclude_attributes.py b/products/tracing/backend/tests/test_exclude_attributes.py
index 83f1be672704..80cb94e71107 100644
--- a/products/tracing/backend/tests/test_exclude_attributes.py
+++ b/products/tracing/backend/tests/test_exclude_attributes.py
@@ -37,16 +37,20 @@ class TestExcludeAttributes(ClickhouseTestMixin, APIBaseTest):
)
sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
- ts_str = dt.datetime(2026, 6, 2, 8, 0, 0).strftime("%Y-%m-%d %H:%M:%S.%f")
+ 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=5)).strftime("%Y-%m-%d %H:%M:%S.%f")
# `attributes` is an ALIAS over attributes_map_str whose keys carry a `__str` type suffix
# that left(k, -5) strips — so 'http.method__str' surfaces as 'http.method'.
+ # `resource_attributes` is a physical column, inserted as-is.
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) VALUES "
+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "
+ "resource_attributes) VALUES "
"("
f"'019e8754-0000-0000-0000-000000000001', {cls.team.id}, '{_b64((1).to_bytes(16, 'big'))}', "
- f"'{_b64((1).to_bytes(8, 'big'))}', '', 'GET /api', 2, '{ts_str}', '{ts_str}', '{ts_str}', 0, 'web', "
- "map('http.method__str', 'POST'))"
+ f"'{_b64((1).to_bytes(8, 'big'))}', '', 'GET /api', 2, '{ts_str}', '{end_str}', '{ts_str}', 0, 'web', "
+ "map('http.method__str', 'POST'), map('service.version', '1.2.3', 'host.name', 'web-1'))"
)
@classmethod
@@ -68,12 +72,16 @@ class TestExcludeAttributes(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- # excludeAttributes=False keeps the populated attribute map.
- ("included_by_default", False, {"http.method": "POST"}),
- # excludeAttributes=True: key stays present (positional mapping is stable) but the map is empty.
- ("omitted_when_excluded", True, {}),
+ # excludeAttributes=False keeps both populated maps.
+ ("included_by_default", False, {"http.method": "POST"}, {"service.version": "1.2.3", "host.name": "web-1"}),
+ # excludeAttributes=True: keys stay present (positional mapping is stable) but the maps are empty.
+ ("omitted_when_excluded", True, {}, {}),
]
)
- def test_attributes(self, _name, exclude, expected_attributes):
+ def test_attributes(self, _name, exclude, expected_attributes, expected_resource_attributes):
results = self._run(exclude=exclude)
self.assertEqual(results[0]["attributes"], expected_attributes)
+ self.assertEqual(results[0]["resource_attributes"], expected_resource_attributes)
+ # Guards the positional-index shift from adding the resource column: the per-trace duration
+ # key (the last SELECT column) must still land on the right value.
+ self.assertEqual(results[0]["trace_duration"], 5_000_000)
diff --git a/products/tracing/frontend/TraceWaterfallView.test.tsx b/products/tracing/frontend/TraceWaterfallView.test.tsx
index 04fccc6c90ba..a7ca9e54d1e9 100644
--- a/products/tracing/frontend/TraceWaterfallView.test.tsx
+++ b/products/tracing/frontend/TraceWaterfallView.test.tsx
@@ -28,6 +28,7 @@ function makeSpan(overrides: Partial<Span>): Span {
is_root_span: false,
matched_filter: true,
attributes: {},
+ resource_attributes: {},
...overrides,
}
}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
index 24b86a778ac8..06626be93449 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
@@ -35,6 +35,15 @@ export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanCo
return (
<div className="flex flex-col gap-2 p-2 bg-primary border-t border-border">
<SpanAttributes title="Attributes" attributes={attributes} emptyLabel="No attributes set on this span" />
+ {/* Sibling section after the span attributes — same split the logs detail view uses.
+ Often absent (non-k8s / no resource attrs), so hidden when empty to avoid noise. */}
+ {Object.keys(span.resource_attributes ?? {}).length > 0 && (
+ <SpanAttributes
+ title="Resource attributes"
+ attributes={span.resource_attributes}
+ emptyLabel="No resource attributes on this span"
+ />
+ )}
{showDetails && <SpanAttributes title="Span details" attributes={details} />}
</div>
)
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index b1c96d51a510..010dd6fbbfb3 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -192,7 +192,7 @@ export interface _TracingQueryBodyApi {
rootSpans?: boolean
/** Number of child spans to prefetch per trace (1-100). */
prefetchSpans?: number
- /** Omit the per-span attributes map from results to keep payloads compact. Defaults to false. */
+ /** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean
}
@@ -209,7 +209,7 @@ export interface _HasSpansResponseApi {
export interface _TracingTraceRequestApi {
/** Date range for the query. Defaults to last 24 hours. */
dateRange?: _TracingDateRangeApi
- /** Omit the per-span attributes map from results to keep payloads compact. Defaults to false. */
+ /** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean
}
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index 4cf655af70ee..a97d83ac940d 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -278,7 +278,9 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec
excludeAttributes: zod
.boolean()
.default(tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
.describe('The tracing spans query to execute.'),
})
@@ -391,7 +393,9 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
excludeAttributes: zod
.boolean()
.default(tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
.describe('The tracing spans query to execute.'),
})
@@ -504,7 +508,9 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({
excludeAttributes: zod
.boolean()
.default(tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
.describe('The tracing spans query to execute.'),
})
@@ -530,7 +536,9 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
excludeAttributes: zod
.boolean()
.default(tracingSpansTraceCreateBodyExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
export const tracingSpansTreeCreateBodyQueryOneCompareFilterOneCompareDefault = false
diff --git a/products/tracing/frontend/spanSummary.test.ts b/products/tracing/frontend/spanSummary.test.ts
index 48e4a15edbe1..689632ec7eb0 100644
--- a/products/tracing/frontend/spanSummary.test.ts
+++ b/products/tracing/frontend/spanSummary.test.ts
@@ -17,6 +17,7 @@ function makeSpan(overrides: Partial<Span>): Span {
is_root_span: false,
matched_filter: true,
attributes: {},
+ resource_attributes: {},
...overrides,
}
}
@@ -65,6 +66,27 @@ describe('deriveSpanSummary', () => {
expect(s.pod).toBe('load-generator-59f4b49995-w585b')
})
+ it('reads k8s chips from resource attributes (their OTel home)', () => {
+ const s = deriveSpanSummary(
+ makeSpan({
+ resource_attributes: { 'k8s.cluster.name': 'prod-eu', 'k8s.pod.name': 'web-abc12' },
+ })
+ )
+ expect(s.cluster).toBe('prod-eu')
+ expect(s.pod).toBe('web-abc12')
+ })
+
+ it('prefers resource-attribute k8s chips over span attributes when both are set', () => {
+ const s = deriveSpanSummary(
+ makeSpan({
+ attributes: { 'k8s.cluster.name': 'span-cluster', 'k8s.pod.name': 'span-pod' },
+ resource_attributes: { 'k8s.cluster.name': 'resource-cluster', 'k8s.pod.name': 'resource-pod' },
+ })
+ )
+ expect(s.cluster).toBe('resource-cluster')
+ expect(s.pod).toBe('resource-pod')
+ })
+
it.each([
['500', 'danger'],
['404', 'warning'],
diff --git a/products/tracing/frontend/spanSummary.ts b/products/tracing/frontend/spanSummary.ts
index 5cdbd790ba02..41362b5a0e53 100644
--- a/products/tracing/frontend/spanSummary.ts
+++ b/products/tracing/frontend/spanSummary.ts
@@ -88,6 +88,7 @@ export function getQueryText(span: Span): string | null {
export function deriveSpanSummary(span: Span): SpanSummary {
const attrs = span.attributes ?? {}
+ const resourceAttrs = span.resource_attributes ?? {}
const method = firstAttr(attrs, METHOD_KEYS)
const route = firstAttr(attrs, ROUTE_KEYS)
@@ -115,9 +116,9 @@ export function deriveSpanSummary(span: Span): SpanSummary {
timestamp: span.timestamp,
endTimestamp: span.end_time,
type: deriveType(attrs),
- // k8s.* are OTel *resource* attributes; these only resolve when the collector flattens them
- // into span attributes (our Span type carries no separate resource attributes). Absent → no chip.
- cluster: attrs['k8s.cluster.name'] || null,
- pod: attrs['k8s.pod.name'] || null,
+ // k8s.* are OTel *resource* attributes, so read the resource map first; fall back to span
+ // attributes for collectors that flatten them in. Absent in both → no chip.
+ cluster: resourceAttrs['k8s.cluster.name'] || attrs['k8s.cluster.name'] || null,
+ pod: resourceAttrs['k8s.pod.name'] || attrs['k8s.pod.name'] || null,
}
}
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index eb64981e57af..2cda9aed495a 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -33,6 +33,7 @@ const createMockSpan = (uuid: string, timestamp: string): Span => ({
is_root_span: true,
matched_filter: true,
attributes: {},
+ resource_attributes: {},
})
const mockSpans: Span[] = [
diff --git a/products/tracing/frontend/types.ts b/products/tracing/frontend/types.ts
index 664316081b27..1e0e000fcb78 100644
--- a/products/tracing/frontend/types.ts
+++ b/products/tracing/frontend/types.ts
@@ -14,6 +14,8 @@ export interface Span {
matched_filter: boolean
// OTel span attributes the user set, as a key-value map.
attributes: Record<string, string>
+ // OTel resource attributes (who/what emitted the span: service.version, host, k8s, ...).
+ resource_attributes: Record<string, string>
}
export const SPAN_KIND_LABELS: Record<number, string> = {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b31d3cf85ae9..ea0bc3acc669 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43916,7 +43916,7 @@ export namespace Schemas {
rootSpans?: boolean;
/** Number of child spans to prefetch per trace (1-100). */
prefetchSpans?: number;
- /** Omit the per-span attributes map from results to keep payloads compact. Defaults to false. */
+ /** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean;
}
@@ -43928,7 +43928,7 @@ export namespace Schemas {
export interface _TracingTraceRequest {
/** Date range for the query. Defaults to last 24 hours. */
dateRange?: _TracingDateRange;
- /** Omit the per-span attributes map from results to keep payloads compact. Defaults to false. */
+ /** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean;
}
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 6f766a6c85e8..ffc65cc2e04b 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -334,7 +334,9 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
excludeAttributes: zod
.boolean()
.default(tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
.describe('The tracing spans query to execute.'),
})
@@ -384,7 +386,9 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
excludeAttributes: zod
.boolean()
.default(tracingSpansTraceCreateBodyExcludeAttributesDefault)
- .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),
+ .describe(
+ 'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
+ ),
})
export const TracingSpansTreeCreateParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
index 49d4841eac31..120a831114dd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
@@ -31,7 +31,7 @@
},
"excludeAttributes": {
"default": false,
- "description": "Omit the per-span attributes map from results to keep payloads compact. Defaults to false.",
+ "description": "Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
"type": "boolean"
},
"trace_id": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
index 03e60e19db25..67b53909335e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
@@ -38,7 +38,7 @@
},
"excludeAttributes": {
"default": false,
- "description": "Omit the per-span attributes map from results to keep payloads compact. Defaults to false.",
+ "description": "Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
"type": "boolean"
},
"filterGroup": {