: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(metrics): guide agents from metrics to traces and past empty results (#113970)
Daniel Viscad222e2dad3c4
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex d41801825b1b..a80f147bee3c 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -296,6 +296,17 @@ class _MetricQueryResponseSerializer(serializers.Serializer):many=True,help_text="One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels.",)+ hint = serializers.CharField(+ required=False,+ help_text="Set only when the query returned no points: what to check before querying again.",+ )+++_NO_SERIES_HINT = (+ "The query returned no points, and the same query will return the same result. Look up the exact metric "+ "name and type with metric-names-list, remove or loosen filters, or widen the time range. With a formula, "+ "check that the clauses group by the same labels: only series with matching labels combine."+)class _MetricAnomalyBodySerializer(serializers.Serializer):@@ -965,7 +976,10 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):request=request,)- return Response({"results": [asdict(s) for s in series]}, status=status.HTTP_200_OK)+ response_data: dict = {"results": [asdict(s) for s in series]}+ if not any(s.points for s in series):+ response_data["hint"] = _NO_SERIES_HINT+ return Response(response_data, status=status.HTTP_200_OK)@extend_schema(request=_MetricSamplesRequestSerializer, responses={200: _MetricSamplesResponseSerializer})@action(detail=False, methods=["POST"], required_scopes=["metrics:read"])diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex f16ef6dfc4f6..e81d28832115 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -374,6 +374,23 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_query_with_no_matching_series_returns_a_hint(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "missing_metric",+ "aggregation": "max",+ "dateFrom": (timezone.now() - dt.timedelta(hours=1)).isoformat(),+ }+ },+ content_type="application/json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(all(series["points"] == [] for series in response.json()["results"]))+ self.assertIn("metric-names-list", response.json()["hint"])+def test_query_returns_aggregated_points(self):anchor = timezone.now().replace(microsecond=0)seed_metric(@@ -405,6 +422,7 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)body = response.json()self.assertIn("results", body)+ self.assertNotIn("hint", body)self.assertEqual(len(body["results"]), 1)series = body["results"][0]self.assertEqual(series["labels"], {})diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 2c399d321e59..ed3cbfdab3e9 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -513,6 +513,8 @@ export interface _MetricQueryRequestApi {export interface _MetricQueryResponseApi {/** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */results: _MetricSeriesApi[]+ /** Set only when the query returned no points: what to check before querying again. */+ hint?: string}export interface _MetricSamplesBodyApi {diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yamlindex 374482cb8f19..d1803b13d969 100644--- a/products/metrics/mcp/tools.yaml+++ b/products/metrics/mcp/tools.yaml@@ -52,3 +52,4 @@ tools:response:include:- results+ - hintdiff --git a/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md b/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.mdindex 28aef77bae7b..9e348b69399d 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md@@ -8,7 +8,7 @@ The three observability tables — `posthog.metrics`, `posthog.trace_spans`, `lo**`trace_id` format:** All three tables store `trace_id` as base64-encoded 16 bytes. Joins are direct equality (no decoding needed). Use `hex(tryBase64Decode(trace_id))` to display in hex.-> ⚠️ **Status (as of PR [#50936](https://github.com/PostHog/posthog/pull/50936)):** exemplar extraction is not yet wired up in `rust/capture-logs/src/metric_record.rs` — the `_exemplars` argument is prefixed with underscore (unused). Every metric row has `trace_id = ''` today. The example query below describes the intended pattern but returns empty until exemplars are populated. The "Works today" alternative further down uses `posthog.trace_spans` directly as the starting point and works against current data.+> **Exemplars are sparse.** Only metric points whose SDK attached an exemplar carry a `trace_id`. An empty result from the query below means no spans or logs matched the chosen trace (the trace may not be exported or retained); it does not prove the metric has no exemplars. Count `trace_id != ''` rows in `posthog.metrics` for the same metric and window first. Use the span-anchored alternative further down when that count is zero, or when the exemplar traces have no retained spans or logs. In the second case, try the next exemplar from the variant query below before you fall back.## Pattern@@ -62,9 +62,9 @@ ORDER BY timestamp- **`status_code = 2` is Error** in `posthog.trace_spans` (OTel semantics). Use this column to flag error spans inline in the result.- If you need to drill into the span tree visually, take the resulting `trace_id` and call `posthog:apm-trace-get` to get the full waterfall.-## Works today: span-anchored correlation+## Fallback: span-anchored correlation-Until metric exemplars are populated by ingestion, anchor on a span instead. Find an interesting trace (slowest error, longest duration, specific service), then pull its logs.+When the metric has no exemplar points in the window, or none of its exemplar traces has retained spans or logs, anchor on a span instead. Find an interesting trace (slowest error, longest duration, specific service), then pull its logs.```sqlWITH slow_error_trace AS (diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md b/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.mdindex e51644a0f693..b882bfbdef13 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md@@ -45,7 +45,7 @@ OpenTelemetry spans. One row per span. Backed by ClickHouse `trace_spans_distrib- **`trace_id`, `span_id`, `parent_span_id` are base64-encoded bytes**, not hex. The MCP layer (`posthog:query-apm-spans`, `posthog:apm-trace-get`) converts to hex via `hex(tryBase64Decode(...))` for display. Raw HogQL queries against this table see the base64 form.- **`parent_span_id` of a root span** is `'AAAAAAAAAAA='` (12-char base64 of 8 zero bytes), not null. **Use `is_root_span` to find trace entries** — don't string-match the padding.- **Use `hex(tryBase64Decode(trace_id))` to display trace_ids in hex** for human-readable output.-- Cross-signal joins by `trace_id` work against `logs` (both store base64). For `posthog.metrics`, exemplar extraction is not yet wired up in the ingestion pipeline — see the metrics reference for the current state.+- Cross-signal joins by `trace_id` work against `logs` (both store base64). For `posthog.metrics`, only points with an exemplar carry a `trace_id` (filter `trace_id != ''`) — see the metrics reference.- User HogQL queries on `posthog.trace_spans` are capped at 50 GB read per query.## `posthog.trace_attributes`diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md b/products/posthog_ai/skills/querying-posthog-data/references/models-logs.mdindex 92f3a44608e1..714ee7fd372e 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md@@ -41,7 +41,7 @@ OpenTelemetry log entries. One row per log line. Backed by ClickHouse `logs_dist- **Unset `trace_id` is `'AAAAAAAAAAAAAAAAAAAAAA=='`** (16 zero bytes encoded), not the hex zero-padded form. Use `trace_id != 'AAAAAAAAAAAAAAAAAAAAAA=='` to find logs with trace context. Or use the explicit decode: `tryBase64Decode(trace_id) != unhex('00000000000000000000000000000000')`.- **Use `hex(tryBase64Decode(trace_id))` to display trace_ids in hex** for human-readable output.- **Prefer `severity_text` over `severity_number` / `level`** for human-readable filters.-- Cross-signal joins by `trace_id` work against `posthog.trace_spans` (both store base64) and `posthog.metrics` _once exemplar extraction is wired up in ingestion_ — see the metrics reference for the current state.+- Cross-signal joins by `trace_id` work against `posthog.trace_spans` (both store base64) and `posthog.metrics` on points that carry an exemplar (filter `trace_id != ''`) — see the metrics reference.- User HogQL queries on `logs` are capped at 50 GB read per query.## `log_attributes`diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md b/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.mdindex 93c71c69d8c9..1cffc4c09fae 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md@@ -4,9 +4,9 @@ The `posthog.metrics` table holds OpenTelemetry metric data points from instrume**Namespacing:** Reference this table as `posthog.metrics`, not bare `metrics` — it's registered under the `posthog.` namespace in the HogQL database (see `posthog/hogql/database/database.py`). The same applies to `posthog.metric_attributes`. Bare names fail with "Unknown table" at HogQL compile time. (Asymmetric with `logs`, which is registered at root level.)-There is no typed `query-metrics` MCP tool yet — **HogQL is the primary interface for metrics**. The schema mirrors `logs` and `posthog.trace_spans` deliberately so cross-signal joins are cheap, and `trace_id` / `span_id` are first-class columns on every metric row (the OpenTelemetry exemplar pattern).+For time series (rates, increases, quantiles, formulas), prefer the typed `posthog:query-metrics` MCP tool. Use HogQL for exemplar lookups, cross-signal joins, and aggregations the typed tool doesn't expose. The schema mirrors `logs` and `posthog.trace_spans` deliberately so cross-signal joins are cheap, and `trace_id` / `span_id` are first-class columns on every metric row (the OpenTelemetry exemplar pattern).-> ⚠️ **Exemplar extraction is not yet wired up in the ingestion pipeline as of PR [#50936](https://github.com/PostHog/posthog/pull/50936)**. The `trace_id` and `span_id` columns exist on `posthog.metrics`, but `rust/capture-logs/src/metric_record.rs` currently ignores the `_exemplars` field (prefixed with underscore → unused). Every ingested metric row has `trace_id = ''` and `span_id = ''` today. The exemplar-based cross-signal correlation patterns documented below describe the intended capability once exemplar ingestion lands.+> **Exemplars are sparse.** Ingestion (`rust/capture-logs/src/metric_record.rs`) keeps the first exemplar with a valid trace ID on each data point. Only points whose SDK attached an exemplar carry a `trace_id` / `span_id`; most rows have `''`. When no point in the window has one, anchor cross-signal work on `posthog.trace_spans` instead.## `posthog.metrics`@@ -55,8 +55,8 @@ with `count() AS event_count`, `sum(value) AS total_value`, `min(value) AS min_v### Important notes- **Unit is metric-dependent.** Always check `unit` — `http.server.duration` may be reported in `ms`, `s`, or `ns` depending on the SDK. Don't assume.-- **`trace_id` is currently always empty string** because exemplar extraction isn't wired up (see warning above). The Rust ingestion uses `String::new()` for both `trace_id` and `span_id`. Filtering `trace_id != ''` correctly excludes unset rows once exemplars start landing.-- **`trace_id` will be base64-encoded** (matching `logs` and `posthog.trace_spans`) once exemplars are populated. Joins to those tables will be direct equality on `trace_id`. Use `hex(tryBase64Decode(trace_id))` to display in hex.+- **`trace_id` is empty string on points without an exemplar**, which is most rows (see the note above). Filter `trace_id != ''` to keep only exemplar points.+- **`trace_id` is base64-encoded** when set, matching `logs` and `posthog.trace_spans`. Joins to those tables are direct equality on `trace_id`. Use `hex(tryBase64Decode(trace_id))` to display in hex.- **Histograms store `histogram_bounds` and `histogram_counts` per row** — you need to expand them for quantile estimation. For a quick p95-ish summary, `value / count` gives the mean per-point.- **Choose the right temporality.** `delta` metrics measure activity in the interval; `cumulative` metrics are running totals. Summing `value` over time only makes sense for `delta`.- User HogQL queries on `posthog.metrics` are capped at 50 GB read per query.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 50da2fcfe3bb..f4d04bef50cd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -112625,6 +112625,8 @@ export namespace Schemas {export interface _MetricQueryResponse {/** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */results: _MetricSeries[];+ /** Set only when the query returned no points: what to check before querying again. */+ hint?: string;}export interface _MetricSamplesBody {diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.mdindex 57d87efcf238..a6f76c6574b7 100644--- a/services/mcp/src/templates/execute-sql-prompt.md+++ b/services/mcp/src/templates/execute-sql-prompt.md@@ -77,17 +77,17 @@ PostHog ingests OpenTelemetry signals into three ClickHouse-backed tables that a- `logs` — log entries. Common fields: `body` (also exposed as `message`), `severity_text`, `severity_number`, `service_name`, `attributes`, `resource_attributes`, `trace_id`, `span_id`, `timestamp`. Prefer `posthog:query-logs` for filtered list queries; reach for SQL for aggregations across services or joins with `posthog.trace_spans` / `posthog.metrics` by `trace_id`.- `posthog.trace_spans` — OpenTelemetry spans. Common fields: `trace_id`, `span_id`, `parent_span_id`, `is_root_span`, `name`, `service_name`, `kind` (0-5), `status_code` (0 Unset, 1 OK, 2 Error), `duration_nano`, `timestamp`, `end_time`, `attributes`, `resource_attributes`. Prefer `posthog:query-apm-spans` / `posthog:apm-trace-get` for span listing and full-trace fetches; reach for SQL for joins with `logs` / `posthog.metrics` by `trace_id`, exemplar lookups, or aggregations the typed tools don't expose.-- `posthog.metrics` — OpenTelemetry metric points. Common fields: `metric_name`, `metric_type` (counter/gauge/histogram), `value`, `count`, `histogram_bounds`, `histogram_counts`, `unit`, `aggregation_temporality` (`delta` or `cumulative`), `is_monotonic`, `service_name`, `trace_id`, `span_id`, `attributes`, `resource_attributes`, `timestamp`. No typed `query-metrics` tool — use SQL. A projection pre-aggregates by `(team_id, time_bucket, toStartOfMinute(timestamp), service_name, metric_name, metric_type, resource_fingerprint)` with `count/sum/min/max(value)`, so per-minute aggregations grouped by those keys are very cheap. **Important for counters:** check `aggregation_temporality` before aggregating — `SUM(value)` over a window is only correct for `delta`. For `cumulative` counters, the value is a running total, so use `argMax(value, timestamp)` (or `max(value) - min(value)` for a rate) to avoid double-counting. Always filter or split by `aggregation_temporality` when both regimes can appear for a given `metric_name`.+- `posthog.metrics` — OpenTelemetry metric points. Common fields: `metric_name`, `metric_type` (counter/gauge/histogram), `value`, `count`, `histogram_bounds`, `histogram_counts`, `unit`, `aggregation_temporality` (`delta` or `cumulative`), `is_monotonic`, `service_name`, `trace_id`, `span_id`, `attributes`, `resource_attributes`, `timestamp`. Prefer `posthog:query-metrics` for time series (rates, increases, quantiles, formulas); reach for SQL for exemplar lookups, joins with `logs` / `posthog.trace_spans`, or aggregations the typed tool doesn't expose. A projection pre-aggregates by `(team_id, time_bucket, toStartOfMinute(timestamp), service_name, metric_name, metric_type, resource_fingerprint)` with `count/sum/min/max(value)`, so per-minute aggregations grouped by those keys are very cheap. **Important for counters:** check `aggregation_temporality` before aggregating — `SUM(value)` over a window is only correct for `delta`. For `cumulative` counters, the value is a running total, so use `argMax(value, timestamp)` (or `max(value) - min(value)` for a rate) to avoid double-counting. Always filter or split by `aggregation_temporality` when both regimes can appear for a given `metric_name`.-All three share `team_id`, `time_bucket`, `service_name`, `resource_fingerprint`, and where applicable `trace_id`. `trace_id` on `posthog.metrics` is the OpenTelemetry exemplar pattern — a metric anomaly can be drilled into via a sample `trace_id` to pull the full trace and correlated logs. **Note:** exemplar extraction is not yet wired up in the ingestion pipeline (the `_exemplars` argument is unused in `rust/capture-logs/src/metric_record.rs`), so `posthog.metrics.trace_id` is always empty today. The pattern below describes the intended capability; the "works today" alternative anchors on `posthog.trace_spans` instead.+All three share `team_id`, `time_bucket`, `service_name`, `resource_fingerprint`, and where applicable `trace_id`. `trace_id` on `posthog.metrics` is the OpenTelemetry exemplar pattern — a metric anomaly can be drilled into via a sample `trace_id` to pull the full trace and correlated logs. Ingestion keeps the first exemplar of each data point, so only points whose SDK attached an exemplar carry a `trace_id`; most rows have `''`. Filter `trace_id != ''`, and when no point in the window has one, anchor on `posthog.trace_spans` instead, as in the example below.-**`trace_id` format:** Both `logs` and `posthog.trace_spans` store `trace_id` as a 24-character base64-encoded 16-byte value (e.g. hex `21EDB3A025A9ECD32ADF3E5D7548A4F4` encodes to `Ie2zoCWp7NMq3z5ddUik9A==`). The MCP API layer converts to hex via `hex(tryBase64Decode(trace_id))` for display. Raw HogQL queries see the base64 form. Unset = `'AAAAAAAAAAAAAAAAAAAAAA=='`. `posthog.metrics.trace_id` is a plain string, empty when unset (once exemplars land it will match the base64 format of the other two tables). Joins are direct equality on `trace_id`.+**`trace_id` format:** Both `logs` and `posthog.trace_spans` store `trace_id` as a 24-character base64-encoded 16-byte value (e.g. hex `21EDB3A025A9ECD32ADF3E5D7548A4F4` encodes to `Ie2zoCWp7NMq3z5ddUik9A==`). The MCP API layer converts to hex via `hex(tryBase64Decode(trace_id))` for display. Raw HogQL queries see the base64 form. Unset = `'AAAAAAAAAAAAAAAAAAAAAA=='`. `posthog.metrics.trace_id` uses the same base64 form when an exemplar is present and is `''` when unset. Joins are direct equality on `trace_id`.User HogQL queries against `logs`, `posthog.trace_spans`, and `posthog.metrics` are capped at 50 GB read per query to prevent unbounded scans.Always pass a tight `timestamp` window. Default to the last hour and widen only when justified.-### Example: three-signal correlation (works today, span-anchored)+### Example: three-signal correlation (span-anchored)<example>User: An error spike on `checkout` over the last hour — show me a sample slow error trace and the logs in that request.@@ -117,7 +117,7 @@ ORDER BY timestamp```<reasoning>-- Anchoring on `posthog.trace_spans` works today because spans always carry a populated `trace_id`. Once `posthog.metrics` exemplars land, the CTE can be swapped for `argMax(trace_id, value) FROM posthog.metrics WHERE … AND trace_id != ''` to drill from a metric spike instead.+- Anchoring on `posthog.trace_spans` always works because spans always carry a populated `trace_id`. To drill from a metric spike instead, swap the CTE for `argMax(trace_id, value) FROM posthog.metrics WHERE … AND trace_id != ''`; it returns a trace only when the service's SDK sends exemplars.- `trace_id` is stored as base64 in both `logs` and `posthog.trace_spans`, so direct equality works — no decoding needed.- `UNION ALL` with a `source` discriminator avoids three separate calls and keeps the timeline interleaved.- Note `logs` is root-level while `posthog.trace_spans` and `posthog.metrics` require the namespace prefix.diff --git a/services/mcp/src/tools/generated/metrics.ts b/services/mcp/src/tools/generated/metrics.tsindex 942277b69db0..9b00c951ec75 100644--- a/services/mcp/src/tools/generated/metrics.ts+++ b/services/mcp/src/tools/generated/metrics.ts@@ -75,7 +75,7 @@ const queryMetrics = (): ToolBase<ReturnType<typeof QueryMetricsSchema>, Schemaspath: `/api/projects/${encodeURIComponent(String(projectId))}/metrics/query/`,body,})- const filtered = pickResponseFields(result, ['results']) as typeof result+ const filtered = pickResponseFields(result, ['results', 'hint']) as typeof resultreturn filtered},})