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): expose temporality + histogram columns in read paths (#67920)

Daniel Visca2bbe1a50eaae
diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.py
index 0f3614439dc1..3eb7e6f236ff 100644
--- a/posthog/hogql/database/schema/metrics.py
+++ b/posthog/hogql/database/schema/metrics.py
@@ -117,7 +117,26 @@ class MetricSamplesTable(Table):
"timestamp": DateTimeDatabaseField(
name="timestamp", nullable=False, description="When the metric was emitted (UTC)."
),
- "value": FloatDatabaseField(name="value", nullable=False, description="The emitted value."),
+ "value": FloatDatabaseField(
+ name="value",
+ nullable=False,
+ description="The emitted value. For histogram/summary points this is the distribution sum; pair with `count`.",
+ ),
+ "count": IntegerDatabaseField(
+ name="count",
+ nullable=False,
+ description="Observations behind this point: 1 for gauges/counters, the distribution count for histograms/summaries.",
+ ),
+ "histogram_bounds": StringJSONDatabaseField(
+ name="histogram_bounds",
+ nullable=False,
+ description="Histogram bucket boundaries; empty for non-histograms.",
+ ),
+ "histogram_counts": StringJSONDatabaseField(
+ name="histogram_counts",
+ nullable=False,
+ description="Per-bucket counts, aligned with `histogram_bounds`; empty for non-histograms.",
+ ),
"trace_id": StringDatabaseField(
name="trace_id",
nullable=False,
@@ -152,6 +171,14 @@ class MetricSeriesTable(Table):
description="OTel metric type (gauge, sum, histogram, summary, exponential_histogram).",
),
"unit": StringDatabaseField(name="unit", nullable=False),
+ "aggregation_temporality": StringDatabaseField(
+ name="aggregation_temporality",
+ nullable=False,
+ description="For counters: 'delta' or 'cumulative'. Decides whether rate() must diff. Empty for gauges.",
+ ),
+ "is_monotonic": BooleanDatabaseField(
+ name="is_monotonic", nullable=False, description="True for monotonically increasing counters."
+ ),
"service_name": StringDatabaseField(name="service_name", nullable=False),
"resource_attributes": MapStringDatabaseField(name="resource_attributes", nullable=False),
"attributes": MapStringDatabaseField(name="attributes", nullable=False),
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 5e094a1f6ad4..b1eedba87efe 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -170,7 +170,12 @@ class MetricEventSample:
metric_name: str
metric_type: str # OTel type: gauge | sum | histogram | summary | exponential_histogram
value: float
+ # Observations behind this point: 1 for gauges/counters, the distribution
+ # count for histograms/summaries (value is then the sum; avg = value/count).
+ count: int
unit: str
+ aggregation_temporality: str # "delta" | "cumulative" | "" (gauges)
+ is_monotonic: bool
service_name: str
trace_id: str
span_id: str
diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.py
index dbf953e36170..0d9b8bec1dee 100644
--- a/products/metrics/backend/metric_event_samples_query_runner.py
+++ b/products/metrics/backend/metric_event_samples_query_runner.py
@@ -7,7 +7,9 @@ first. It backs the Samples view and the metric->trace pivot.
Joins `posthog.metric_samples` (the tiny hot rows) to `posthog.metric_series`
(the deduped label set) on `series_fingerprint`. Samples are filtered + limited
first, then enriched with their series' labels; the series side is grouped so a
-ReplacingMergeTree duplicate never multiplies a sample.
+ReplacingMergeTree duplicate never multiplies a sample. metric_name comes from
+the sample row itself, so an emission whose series row hasn't landed yet still
+renders with its name (series-side fields fall back to empty).
"""
import datetime as dt
@@ -56,17 +58,20 @@ class MetricEventSamplesQueryRunner:
"""
SELECT
s.timestamp,
- ser.metric_name,
+ s.metric_name,
ser.metric_type,
s.value,
+ s.count,
ser.unit,
+ ser.aggregation_temporality,
+ ser.is_monotonic,
ser.service_name,
s.trace_id,
s.span_id,
ser.attributes,
ser.resource_attributes
FROM (
- SELECT team_id, metric_name, series_fingerprint, timestamp, value, trace_id, span_id
+ SELECT team_id, metric_name, series_fingerprint, timestamp, value, count, trace_id, span_id
FROM posthog.metric_samples
WHERE metric_name = {metric_name}
AND timestamp >= {date_from}
@@ -82,6 +87,8 @@ class MetricEventSamplesQueryRunner:
series_fingerprint,
any(metric_type) AS metric_type,
any(unit) AS unit,
+ any(aggregation_temporality) AS aggregation_temporality,
+ any(is_monotonic) AS is_monotonic,
any(service_name) AS service_name,
any(attributes) AS attributes,
any(resource_attributes) AS resource_attributes
@@ -117,12 +124,15 @@ class MetricEventSamplesQueryRunner:
"metric_name": row[1],
"metric_type": row[2],
"value": row[3],
- "unit": row[4],
- "service_name": row[5],
- "trace_id": row[6],
- "span_id": row[7],
- "attributes": dict(row[8]) if row[8] else {},
- "resource_attributes": dict(row[9]) if row[9] else {},
+ "count": int(row[4]),
+ "unit": row[5],
+ "aggregation_temporality": row[6],
+ "is_monotonic": bool(row[7]),
+ "service_name": row[8],
+ "trace_id": row[9],
+ "span_id": row[10],
+ "attributes": dict(row[11]) if row[11] else {},
+ "resource_attributes": dict(row[12]) if row[12] else {},
}
for row in response.results
]
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 0e9381732b74..1a0e382efeed 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -381,8 +381,17 @@ class _MetricEventSampleSerializer(serializers.Serializer):
metric_type = serializers.CharField(
help_text="OTel metric type: gauge, sum, histogram, summary, or exponential_histogram."
)
- value = serializers.FloatField(help_text="The emitted value.")
+ value = serializers.FloatField(
+ help_text="The emitted value. For histogram/summary points this is the distribution sum; pair with count."
+ )
+ count = serializers.IntegerField(
+ help_text="Observations behind this point: 1 for gauges/counters, the distribution count for histograms/summaries."
+ )
unit = serializers.CharField(help_text="Unit of the value, if any.")
+ aggregation_temporality = serializers.CharField(
+ help_text="For counters: 'delta' or 'cumulative' (decides whether rate() must diff). Empty for gauges."
+ )
+ is_monotonic = serializers.BooleanField(help_text="True for monotonically increasing counters.")
service_name = serializers.CharField(help_text="Service that emitted the metric.")
trace_id = serializers.CharField(
help_text="Trace this emission belongs to; empty if none. Use it to pivot to the trace.",
diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.py
index 00a2c5287fdf..faf5d7f44346 100644
--- a/products/metrics/backend/tests/_seeder.py
+++ b/products/metrics/backend/tests/_seeder.py
@@ -117,6 +117,11 @@ def seed_metric_event(
span_id: str = "",
attributes: Mapping[str, str] | None = None,
resource_attributes: Mapping[str, str] | None = None,
+ count: int = 1,
+ aggregation_temporality: str = "cumulative",
+ is_monotonic: bool = False,
+ histogram_bounds: list[float] | None = None,
+ histogram_counts: list[int] | None = None,
) -> None:
"""Insert one `metric_samples` row per `(timestamp, value)` point plus the
matching `metric_series` row, the way the ingest MVs split a metric.
@@ -139,6 +144,9 @@ def seed_metric_event(
"series_fingerprint": fingerprint,
"timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
"value": value,
+ "count": count,
+ "histogram_bounds": histogram_bounds or [],
+ "histogram_counts": histogram_counts or [],
"trace_id": trace_id,
"span_id": span_id,
"trace_flags": 0,
@@ -151,6 +159,8 @@ def seed_metric_event(
"series_fingerprint": fingerprint,
"metric_type": metric_type,
"unit": unit,
+ "aggregation_temporality": aggregation_temporality,
+ "is_monotonic": is_monotonic,
"service_name": service_name,
"resource_attributes": resource_attributes,
"attributes": attributes,
diff --git a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py b/products/metrics/backend/tests/test_metric_event_samples_query_runner.py
index 1b0d7fae914f..399e5d7ff607 100644
--- a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_event_samples_query_runner.py
@@ -97,6 +97,9 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
span_id="s1",
attributes={"route": "/x"},
resource_attributes={"service.version": "1.2"},
+ count=40,
+ aggregation_temporality="cumulative",
+ is_monotonic=True,
)
seed_metric_event(
team_id=self.team.id,
@@ -117,11 +120,39 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
oldest = samples[1]
self.assertEqual(oldest.metric_type, "histogram")
self.assertEqual(oldest.unit, "ms")
+ self.assertEqual(oldest.count, 40)
+ self.assertEqual(oldest.aggregation_temporality, "cumulative")
+ self.assertTrue(oldest.is_monotonic)
self.assertEqual(oldest.service_name, "api")
self.assertEqual(oldest.trace_id, "t1")
self.assertEqual(oldest.attributes, {"route": "/x"})
self.assertEqual(oldest.resource_attributes, {"service.version": "1.2"})
+ def test_orphan_sample_keeps_metric_name(self):
+ # A sample can outrun its series row (series-MV lag, or the rollout
+ # window where NULL-fingerprint series rows are dropped). It must still
+ # render under its own metric name, with series-side fields empty —
+ # regression guard for selecting metric_name from the LEFT JOIN side.
+ anchor = timezone.now().replace(microsecond=0)
+ sync_execute(
+ "INSERT INTO metric_samples1 (team_id, metric_name, series_fingerprint, timestamp, value) "
+ "VALUES (%(team_id)s, 'orphaned.metric', 42, %(ts)s, 7.0)",
+ {"team_id": self.team.id, "ts": anchor.strftime("%Y-%m-%d %H:%M:%S.%f")},
+ )
+
+ samples = list_metric_event_samples(
+ team=self.team,
+ metric_name="orphaned.metric",
+ date_from=anchor - dt.timedelta(hours=1),
+ date_to=anchor + dt.timedelta(hours=1),
+ )
+
+ self.assertEqual(len(samples), 1)
+ self.assertEqual(samples[0].metric_name, "orphaned.metric")
+ self.assertEqual(samples[0].value, 7.0)
+ self.assertEqual(samples[0].count, 1) # column default
+ self.assertEqual(samples[0].metric_type, "") # series side absent
+
def test_samples_api_requires_authentication(self):
self.client.logout()
response = self.client.post(
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index f6103cb8f0e1..0ecdbdfe3c76 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -419,10 +419,16 @@ export interface _MetricEventSampleApi {
metric_name: string
/** OTel metric type: gauge, sum, histogram, summary, or exponential_histogram. */
metric_type: string
- /** The emitted value. */
+ /** The emitted value. For histogram/summary points this is the distribution sum; pair with count. */
value: number
+ /** Observations behind this point: 1 for gauges/counters, the distribution count for histograms/summaries. */
+ count: number
/** Unit of the value, if any. */
unit: string
+ /** For counters: 'delta' or 'cumulative' (decides whether rate() must diff). Empty for gauges. */
+ aggregation_temporality: string
+ /** True for monotonically increasing counters. */
+ is_monotonic: boolean
/** Service that emitted the metric. */
service_name: string
/** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6456da9b5fb9..18bb16fc776e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54653,10 +54653,16 @@ export namespace Schemas {
metric_name: string;
/** OTel metric type: gauge, sum, histogram, summary, or exponential_histogram. */
metric_type: string;
- /** The emitted value. */
+ /** The emitted value. For histogram/summary points this is the distribution sum; pair with count. */
value: number;
+ /** Observations behind this point: 1 for gauges/counters, the distribution count for histograms/summaries. */
+ count: number;
/** Unit of the value, if any. */
unit: string;
+ /** For counters: 'delta' or 'cumulative' (decides whether rate() must diff). Empty for gauges. */
+ aggregation_temporality: string;
+ /** True for monotonically increasing counters. */
+ is_monotonic: boolean;
/** Service that emitted the metric. */
service_name: string;
/** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */