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(metrics): pin the OTel metric type in saved MetricsQuery insights (#70101)

Daniel Viscad4960fa2a3a6
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 957cfa0b35d3..c709301a72a4 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -31660,6 +31660,11 @@
"enum": ["eq", "neq", "regex", "not_regex"],
"type": "string"
},
+ "MetricsOtelType": {
+ "description": "OTel metric type; matches what ingest writes to `metric_type`",
+ "enum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],
+ "type": "string"
+ },
"MetricsQuery": {
"additionalProperties": false,
"properties": {
@@ -31724,6 +31729,10 @@
"metricName": {
"type": "string"
},
+ "metricType": {
+ "$ref": "#/definitions/MetricsOtelType",
+ "description": "Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series."
+ },
"name": {
"description": "Alias a formula refers to (e.g. \"a\"); must be unique within the query",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 66efd312223c..f85517665075 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3515,6 +3515,9 @@ export type MetricsAttributeScope = 'resource' | 'attribute' | 'auto'
export type MetricsFilterOp = 'eq' | 'neq' | 'regex' | 'not_regex'
+/** OTel metric type; matches what ingest writes to `metric_type` */
+export type MetricsOtelType = 'gauge' | 'sum' | 'histogram' | 'exponential_histogram' | 'summary'
+
export type MetricsAggregation =
| 'sum'
| 'avg'
@@ -3543,6 +3546,9 @@ export interface MetricsQueryClause {
name: string
metricName: string
aggregation: MetricsAggregation
+ /** Series identity includes the OTel type — one name can exist as e.g. both a
+ * counter and a gauge — so a clause pins it to avoid blending distinct series. */
+ metricType?: MetricsOtelType
filters?: MetricsQueryFilter[]
groupBy?: MetricsQueryGroupBy[]
/** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
diff --git a/posthog/schema.py b/posthog/schema.py
index 0f2198dfc944..ced506b0ed97 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -177,6 +177,7 @@ from posthog.schema_enums import (
MetricsAggregation as MetricsAggregation,
MetricsAttributeScope as MetricsAttributeScope,
MetricsFilterOp as MetricsFilterOp,
+ MetricsOtelType as MetricsOtelType,
MetricSummary as MetricSummary,
MrrOrGross as MrrOrGross,
MultipleBreakdownType as MultipleBreakdownType,
@@ -5454,6 +5455,14 @@ class MetricsQueryClause(BaseModel):
filters: list[MetricsQueryFilter] | None = None
groupBy: list[MetricsQueryGroupBy] | None = None
metricName: str
+ metricType: MetricsOtelType | None = Field(
+ default=None,
+ description=(
+ "Series identity includes the OTel type — one name can exist as e.g. both a"
+ " counter and a gauge — so a clause pins it to avoid blending distinct"
+ " series."
+ ),
+ )
name: str = Field(
...,
description=('Alias a formula refers to (e.g. "a"); must be unique within the query'),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index c1c3893e3307..20fc5eb99cdb 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2570,6 +2570,14 @@ class MetricsFilterOp(StrEnum):
NOT_REGEX = "not_regex"
+class MetricsOtelType(StrEnum):
+ GAUGE = "gauge"
+ SUM = "sum"
+ HISTOGRAM = "histogram"
+ EXPONENTIAL_HISTOGRAM = "exponential_histogram"
+ SUMMARY = "summary"
+
+
class MultiQuestionFormFieldType(StrEnum):
TEXT = "text"
NUMBER = "number"
diff --git a/products/metrics/backend/metrics_query_runner.py b/products/metrics/backend/metrics_query_runner.py
index ce96e678a133..875d06cf3503 100644
--- a/products/metrics/backend/metrics_query_runner.py
+++ b/products/metrics/backend/metrics_query_runner.py
@@ -28,7 +28,7 @@ from posthog.rbac.user_access_control import UserAccessControl
from products.metrics.backend.facade.api import run_metric_query
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType
if TYPE_CHECKING:
from posthog.models import User
@@ -68,6 +68,7 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):
name=clause.name,
metric_name=clause.metricName,
aggregation=MetricAggregation(clause.aggregation.value),
+ metric_type=MetricType(clause.metricType.value) if clause.metricType is not None else None,
filters=tuple(
MetricFilter(
key=f.key,
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index fecc814028d4..477867d2a8cb 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -20,7 +20,7 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rbac.user_access_control import UserAccessControlError
-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType
from products.metrics.backend.metrics_query_runner import MetricsQueryRunner
from products.metrics.backend.tests._seeder import seed_metric
@@ -38,6 +38,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
name="a",
metricName="http_requests_total",
aggregation="histogram_quantile",
+ metricType="histogram",
quantile=0.95,
filters=[MetricsQueryFilter(key="container", op="eq", value="capture", scope="attribute")],
groupBy=[MetricsQueryGroupBy(key="namespace")],
@@ -52,6 +53,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
clause = request.clauses[0]
assert clause.metric_name == "http_requests_total"
+ assert clause.metric_type is MetricType.HISTOGRAM
assert clause.aggregation is MetricAggregation.HISTOGRAM_QUANTILE
assert clause.quantile == 0.95
assert clause.filters[0].op is FilterOp.EQ
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 606f72f58d56..76b242879c0f 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -99,6 +99,7 @@ describe('metricsViewerLogic', () => {
name: 'a',
metricName: 'request_duration',
aggregation: 'quantile',
+ metricType: 'histogram',
quantile: 0.95,
filters: [{ key: 'namespace', op: 'eq', value: 'posthog' }],
groupBy: [{ key: 'container' }],
@@ -112,6 +113,30 @@ describe('metricsViewerLogic', () => {
expect(logic.values.metricsQueryNode).toBeNull()
})
+ // A type outside the API enum (or a metric missing from the picker list) must be
+ // omitted, not persisted — the backend rejects unknown metric types.
+ it('omits metricType from the node when the picked type is unknown', () => {
+ logic.actions.setMetricName('mystery_metric')
+ expect(logic.values.metricsQueryNode?.clauses[0]).not.toHaveProperty('metricType')
+ })
+
+ // The picker's items are live search results: typing a new search after picking
+ // a metric replaces them. The picked type must be latched, not derived, or a
+ // save at that moment silently persists an untyped (blendable) query.
+ it('keeps the picked metric type when the picker search results change', () => {
+ logic.actions.setMetricName('queue_depth')
+ metricNamePickerLogic.actions.loadItemsSuccess([{ name: 'http_requests', metric_type: 'sum' }] as any)
+ expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
+ })
+
+ it('backfills the metric type when the picker loads after the metric was set', () => {
+ metricNamePickerLogic.actions.loadItemsSuccess([])
+ logic.actions.setMetricName('queue_depth')
+ expect(logic.values.metricsQueryNode?.clauses[0]).not.toHaveProperty('metricType')
+ metricNamePickerLogic.actions.loadItemsSuccess(PICKER_ITEMS)
+ expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
+ })
+
// A failed query (bad regex, 500) used to render the same "No data" empty state as a genuinely
// empty result. The failure records the message so the viewer can show a real error instead.
// kea-loaders dispatches `<key>Failure(error.message, error)`, so the reducer reads the message.
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index fea08479f2b7..e9805da106a0 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -142,13 +142,21 @@ export const resolveDate = (value: string | null | undefined): string | null =>
return dj.isValid() ? dj.toISOString() : null
}
+// The picker reports raw ingest strings; only enum members may reach the API.
+const toKnownMetricType = (metricType: string | undefined): OtelMetricTypeEnumApi | null => {
+ const known = Object.values(OtelMetricTypeEnumApi) as string[]
+ return metricType && known.includes(metricType) ? (metricType as OtelMetricTypeEnumApi) : null
+}
+
export const metricsViewerLogic = kea<metricsViewerLogicType>([
path(['products', 'metrics', 'frontend', 'components', 'metricsViewerLogic']),
connect(() => ({
values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['items']],
+ actions: [metricNamePickerLogic, ['loadItemsSuccess']],
})),
actions({
setMetricName: (metricName: string) => ({ metricName }),
+ setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => ({ metricType }),
setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
// Auto-applied on metric switch — a separate action so usage tracking can
// tell it apart from the user picking an aggregation themselves.
@@ -168,6 +176,16 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}),
reducers({
metricName: ['' as string, { setMetricName: (_, { metricName }) => metricName }],
+ // The picked metric's type, latched at pick time (and backfilled if the
+ // picker list arrives later). Not derived from the picker's `items` —
+ // those are live search results, so typing a new search would wipe a
+ // derived value and queries/saves would silently go untyped. Sent with
+ // queries so a name that exists as several types (e.g. a counter and a
+ // gauge) charts only the picked one instead of blending them.
+ selectedMetricType: [
+ null as OtelMetricTypeEnumApi | null,
+ { setSelectedMetricType: (_, { metricType }) => metricType },
+ ],
aggregation: [
DEFAULT_AGGREGATION as MetricAggregation,
{
@@ -206,14 +224,27 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}),
listeners(({ actions, values, cache }) => ({
setMetricName: ({ metricName }) => {
+ const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type
+ actions.setSelectedMetricType(toKnownMetricType(metricType))
// Each metric type has one sensible default; a manual aggregation pick
// holds only until the next metric switch.
- const metricType = values.items.find((item) => item.name === metricName)?.metric_type
const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
if (recommended && recommended !== values.aggregation) {
actions.setRecommendedAggregation(recommended)
}
},
+ // Recovers the type when the metric name was set before the picker's list
+ // arrived (initial load); an already-latched type is left alone.
+ loadItemsSuccess: () => {
+ if (values.selectedMetricType !== null || !values.hasMetricName) {
+ return
+ }
+ const metricType = values.items.find((item) => item.name === values.metricName.trim())?.metric_type
+ const known = toKnownMetricType(metricType)
+ if (known) {
+ actions.setSelectedMetricType(known)
+ }
+ },
saveAsInsightFailure: ({ error }) => {
lemonToast.error(`Failed to save insight: ${error}`)
},
@@ -365,23 +396,28 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
})),
selectors({
hasMetricName: [(s) => [s.metricName], (metricName) => metricName.trim().length > 0],
- // The picked metric's type (from the names list). Sent with the query so
- // a name that exists as several types (e.g. a counter and a gauge)
- // charts only the picked one instead of blending them.
- selectedMetricType: [
- (s) => [s.metricName, s.items],
- (metricName, items): OtelMetricTypeEnumApi | null => {
- const metricType = items.find((item) => item.name === metricName.trim())?.metric_type
- const known = Object.values(OtelMetricTypeEnumApi) as string[]
- return metricType && known.includes(metricType) ? (metricType as OtelMetricTypeEnumApi) : null
- },
- ],
// The viewer state as a `MetricsQuery` schema node — what "Save as insight"
// persists, so the saved tile re-runs exactly what the viewer shows.
// The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.
metricsQueryNode: [
- (s) => [s.metricName, s.aggregation, s.dateFrom, s.dateTo, s.groupByKeys, s.queryFilters],
- (metricName, aggregation, dateFrom, dateTo, groupByKeys, queryFilters): MetricsQuery | null => {
+ (s) => [
+ s.metricName,
+ s.aggregation,
+ s.selectedMetricType,
+ s.dateFrom,
+ s.dateTo,
+ s.groupByKeys,
+ s.queryFilters,
+ ],
+ (
+ metricName,
+ aggregation,
+ selectedMetricType,
+ dateFrom,
+ dateTo,
+ groupByKeys,
+ queryFilters
+ ): MetricsQuery | null => {
const trimmedName = metricName.trim()
if (!trimmedName) {
return null
@@ -390,6 +426,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
name: 'a',
metricName: trimmedName,
aggregation: aggregation === 'p95' ? 'quantile' : aggregation,
+ // Pins the OTel type so the saved tile can't blend same-named
+ // series of different types (mirrors the live viewer's query).
+ ...(selectedMetricType ? { metricType: selectedMetricType } : {}),
...(aggregation === 'p95' ? { quantile: 0.95 } : {}),
...(queryFilters.length
? {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b48ce09d3fbe..8543835ba6f8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27966,11 +27966,24 @@ export namespace Schemas {
scope?: MetricsAttributeScope | null;
}
+ export type MetricsOtelType = typeof MetricsOtelType[keyof typeof MetricsOtelType];
+
+
+ export const MetricsOtelType = {
+ Gauge: 'gauge',
+ Sum: 'sum',
+ Histogram: 'histogram',
+ ExponentialHistogram: 'exponential_histogram',
+ Summary: 'summary',
+ } as const;
+
export interface MetricsQueryClause {
aggregation: MetricsAggregation;
filters?: MetricsQueryFilter[] | null;
groupBy?: MetricsQueryGroupBy[] | null;
metricName: string;
+ /** Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series. */
+ metricType?: MetricsOtelType | null;
/** Alias a formula refers to (e.g. "a"); must be unique within the query */
name: string;
/** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */