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): add temporality + histogram columns to events-model tables (#67604)

Daniel Viscac351bd4d0fa9
diff --git a/bin/clickhouse-metrics.sql b/bin/clickhouse-metrics.sql
index cdfa59749c13..e11b35d0f666 100644
--- a/bin/clickhouse-metrics.sql
+++ b/bin/clickhouse-metrics.sql
@@ -81,6 +81,8 @@ CREATE OR REPLACE TABLE metric_series1
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`metric_type` LowCardinality(String),
`unit` LowCardinality(String),
+ `aggregation_temporality` LowCardinality(String),
+ `is_monotonic` Bool DEFAULT false,
`service_name` LowCardinality(String),
`resource_attributes` Map(LowCardinality(String), String),
`attributes` Map(LowCardinality(String), String),
@@ -91,6 +93,7 @@ CREATE OR REPLACE TABLE metric_series1
)
ENGINE = ReplacingMergeTree(last_seen)
ORDER BY (team_id, metric_name, series_fingerprint)
+TTL toDateTime(last_seen) + INTERVAL 90 DAY DELETE
SETTINGS index_granularity = 8192;
create or replace TABLE metric_series AS metric_series1 ENGINE = Distributed('posthog', 'default', 'metric_series1');
@@ -102,6 +105,9 @@ CREATE OR REPLACE TABLE metric_samples1
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`timestamp` DateTime64(6) CODEC(DoubleDelta),
`value` Float64 CODEC(Gorilla),
+ `count` UInt64 DEFAULT 1,
+ `histogram_bounds` Array(Float64),
+ `histogram_counts` Array(UInt64),
`trace_id` String,
`span_id` String,
`trace_flags` Int32,
@@ -300,12 +306,14 @@ AS SELECT
reinterpretAsUInt64(assumeNotNull(series_fingerprint)) as series_fingerprint,
ifNull(metric_type, '') as metric_type,
ifNull(unit, '') as unit,
+ ifNull(aggregation_temporality, '') as aggregation_temporality,
+ ifNull(is_monotonic, 0) as is_monotonic,
ifNull(service_name, '') as service_name,
mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,
mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), attributes)) AS attributes,
timestamp as last_seen
FROM kafka_metrics_avro
-WHERE series_fingerprint IS NOT NULL
+WHERE kafka_metrics_avro.series_fingerprint IS NOT NULL
settings min_insert_block_size_rows=0, min_insert_block_size_bytes=0;
drop table if exists kafka_metrics_avro_to_metric_samples;
@@ -316,11 +324,14 @@ AS SELECT
reinterpretAsUInt64(assumeNotNull(series_fingerprint)) as series_fingerprint,
timestamp,
ifNull(value, 0) as value,
+ toUInt64(ifNull(count, 1)) as count,
+ histogram_bounds,
+ arrayMap(x -> toUInt64(x), histogram_counts) as histogram_counts,
trace_id,
span_id,
ifNull(trace_flags, 0) as trace_flags
FROM kafka_metrics_avro
-WHERE series_fingerprint IS NOT NULL
+WHERE kafka_metrics_avro.series_fingerprint IS NOT NULL
settings min_insert_block_size_rows=0, min_insert_block_size_bytes=0;
-- Kafka consumer lag tracking
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 5cbef65629ce..97d12c4038ec 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -39,8 +39,10 @@ class NodeRole(StrEnum):
# Roles that host replicated MergeTree data; valid ALTER TABLE targets.
+# LOGS hosts replicated tables too (metric_series1/metric_samples1 via migration
+# 0283); non-sharded ALTERs on it run via any_host_by_roles like the satellites.
DATA_NODE_ROLES: frozenset[NodeRole] = frozenset(
- {NodeRole.DATA, NodeRole.AI_EVENTS, NodeRole.AUX, NodeRole.OPS, NodeRole.SESSIONS}
+ {NodeRole.DATA, NodeRole.AI_EVENTS, NodeRole.AUX, NodeRole.LOGS, NodeRole.OPS, NodeRole.SESSIONS}
)
# Single-shard data clusters: ALTER runs on one host, replication propagates.
SINGLE_SHARD_DATA_NODE_ROLES: frozenset[NodeRole] = frozenset(
diff --git a/posthog/clickhouse/metrics/metric_events.py b/posthog/clickhouse/metrics/metric_events.py
index e7ba2bd49dcd..aee92ff617eb 100644
--- a/posthog/clickhouse/metrics/metric_events.py
+++ b/posthog/clickhouse/metrics/metric_events.py
@@ -22,6 +22,13 @@ from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, Repla
# Distinct from `metrics1` (pre-aggregated rollups for dashboards/alerts): this
# keeps every raw sample, for exact quantiles, per-emission drill-down, and the
# metric->trace pivot. Lives on the logs ClickHouse cluster next to logs/traces.
+#
+# aggregation_temporality/is_monotonic live on the series (rate() needs them to
+# know whether to diff) but are NOT in the fingerprint — a collector config change
+# should update the series via the Replacing dedup, not re-key it. Histogram
+# bucket arrays stay on the sample row, self-contained: exponential histograms
+# can rescale their buckets between emissions, so bounds can't live on the
+# deduped series row without silently misaligning a sample's counts.
SAMPLES_TABLE_NAME = "metric_samples1"
SAMPLES_DISTRIBUTED_TABLE_NAME = "metric_samples"
@@ -38,6 +45,8 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{SERIES_T
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`metric_type` LowCardinality(String),
`unit` LowCardinality(String),
+ `aggregation_temporality` LowCardinality(String),
+ `is_monotonic` Bool DEFAULT false,
`service_name` LowCardinality(String),
`resource_attributes` Map(LowCardinality(String), String),
`attributes` Map(LowCardinality(String), String),
@@ -48,6 +57,7 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{SERIES_T
)
ENGINE = {ReplacingMergeTree(SERIES_TABLE_NAME, replication_scheme=ReplicationScheme.REPLICATED, ver="last_seen")}
ORDER BY (team_id, metric_name, series_fingerprint)
+TTL toDateTime(last_seen) + INTERVAL 90 DAY DELETE
SETTINGS index_granularity = 8192
"""
@@ -61,6 +71,9 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{SAMPLES_
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`timestamp` DateTime64(6) CODEC(DoubleDelta),
`value` Float64 CODEC(Gorilla),
+ `count` UInt64 DEFAULT 1,
+ `histogram_bounds` Array(Float64),
+ `histogram_counts` Array(UInt64),
`trace_id` String,
`span_id` String,
`trace_flags` Int32,
diff --git a/posthog/clickhouse/migrations/0285_metric_series_temporality_samples_histograms.py b/posthog/clickhouse/migrations/0285_metric_series_temporality_samples_histograms.py
new file mode 100644
index 000000000000..cf3374dc1601
--- /dev/null
+++ b/posthog/clickhouse/migrations/0285_metric_series_temporality_samples_histograms.py
@@ -0,0 +1,70 @@
+from django.conf import settings
+
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+
+# The events-model tables can't answer rate() or histogram-quantile questions as
+# originally shipped: counters need aggregation_temporality/is_monotonic to know
+# whether to diff, and histogram points collapsed to their sum with the bucket
+# arrays dropped. Add both while the tables are empty (US) / freshly truncated at
+# the fingerprint cutover (EU), plus the series TTL so dead series age out 90 days
+# after their last sample (samples themselves expire at 30).
+#
+# This migration covers the storage tables only. The ingest MVs that populate the
+# new columns (and carry the table-qualified NULL-fingerprint guard) are
+# hand-managed, like all Avro Kafka-engine objects on the logs cluster — the
+# canonical definitions live in bin/clickhouse-metrics.sql and must be dropped and
+# recreated on each region as part of the fingerprint-cutover DDL. Until that
+# manual step runs, rows written by the old MVs simply leave the new columns at
+# their defaults.
+
+_DB = settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE
+
+ALTER_SERIES_BASE = f"""
+ALTER TABLE {_DB}.metric_series1
+ ADD COLUMN IF NOT EXISTS `aggregation_temporality` LowCardinality(String) AFTER unit,
+ ADD COLUMN IF NOT EXISTS `is_monotonic` Bool DEFAULT false AFTER aggregation_temporality
+"""
+
+ALTER_SERIES_TTL = f"""
+ALTER TABLE {_DB}.metric_series1
+ MODIFY TTL toDateTime(last_seen) + INTERVAL 90 DAY DELETE
+"""
+
+ALTER_SAMPLES_BASE = f"""
+ALTER TABLE {_DB}.metric_samples1
+ ADD COLUMN IF NOT EXISTS `count` UInt64 DEFAULT 1 AFTER value,
+ ADD COLUMN IF NOT EXISTS `histogram_bounds` Array(Float64) AFTER count,
+ ADD COLUMN IF NOT EXISTS `histogram_counts` Array(UInt64) AFTER histogram_bounds
+"""
+
+ALTER_SERIES_DISTRIBUTED = f"""
+ALTER TABLE {_DB}.metric_series
+ ADD COLUMN IF NOT EXISTS `aggregation_temporality` LowCardinality(String) AFTER unit,
+ ADD COLUMN IF NOT EXISTS `is_monotonic` Bool DEFAULT false AFTER aggregation_temporality
+"""
+
+ALTER_SAMPLES_DISTRIBUTED = f"""
+ALTER TABLE {_DB}.metric_samples
+ ADD COLUMN IF NOT EXISTS `count` UInt64 DEFAULT 1 AFTER value,
+ ADD COLUMN IF NOT EXISTS `histogram_bounds` Array(Float64) AFTER count,
+ ADD COLUMN IF NOT EXISTS `histogram_counts` Array(UInt64) AFTER histogram_bounds
+"""
+
+operations = [
+ run_sql_with_exceptions(
+ ALTER_SERIES_BASE, node_roles=[NodeRole.LOGS], sharded=False, is_alter_on_replicated_table=True
+ ),
+ run_sql_with_exceptions(
+ ALTER_SERIES_TTL, node_roles=[NodeRole.LOGS], sharded=False, is_alter_on_replicated_table=True
+ ),
+ run_sql_with_exceptions(
+ ALTER_SAMPLES_BASE, node_roles=[NodeRole.LOGS], sharded=False, is_alter_on_replicated_table=True
+ ),
+ run_sql_with_exceptions(
+ ALTER_SERIES_DISTRIBUTED, node_roles=[NodeRole.LOGS], sharded=False, is_alter_on_replicated_table=False
+ ),
+ run_sql_with_exceptions(
+ ALTER_SAMPLES_DISTRIBUTED, node_roles=[NodeRole.LOGS], sharded=False, is_alter_on_replicated_table=False
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index a756096508b9..d6319e3ddfb5 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0284_message_assets
+0285_metric_series_temporality_samples_histograms
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index 2a4284ed6776..1471b89eff48 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -3539,6 +3539,9 @@
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`timestamp` DateTime64(6) CODEC(DoubleDelta),
`value` Float64 CODEC(Gorilla),
+ `count` UInt64 DEFAULT 1,
+ `histogram_bounds` Array(Float64),
+ `histogram_counts` Array(UInt64),
`trace_id` String,
`span_id` String,
`trace_flags` Int32,
@@ -3565,6 +3568,8 @@
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`metric_type` LowCardinality(String),
`unit` LowCardinality(String),
+ `aggregation_temporality` LowCardinality(String),
+ `is_monotonic` Bool DEFAULT false,
`service_name` LowCardinality(String),
`resource_attributes` Map(LowCardinality(String), String),
`attributes` Map(LowCardinality(String), String),
@@ -3575,6 +3580,7 @@
)
ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_series1', '{replica}-{shard}', last_seen)
ORDER BY (team_id, metric_name, series_fingerprint)
+ TTL toDateTime(last_seen) + INTERVAL 90 DAY DELETE
SETTINGS index_granularity = 8192
'''
@@ -9631,6 +9637,9 @@
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`timestamp` DateTime64(6) CODEC(DoubleDelta),
`value` Float64 CODEC(Gorilla),
+ `count` UInt64 DEFAULT 1,
+ `histogram_bounds` Array(Float64),
+ `histogram_counts` Array(UInt64),
`trace_id` String,
`span_id` String,
`trace_flags` Int32,
@@ -9654,6 +9663,8 @@
`series_fingerprint` UInt64 CODEC(DoubleDelta),
`metric_type` LowCardinality(String),
`unit` LowCardinality(String),
+ `aggregation_temporality` LowCardinality(String),
+ `is_monotonic` Bool DEFAULT false,
`service_name` LowCardinality(String),
`resource_attributes` Map(LowCardinality(String), String),
`attributes` Map(LowCardinality(String), String),
@@ -9664,6 +9675,7 @@
)
ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_series1', '{replica}-{shard}', last_seen)
ORDER BY (team_id, metric_name, series_fingerprint)
+ TTL toDateTime(last_seen) + INTERVAL 90 DAY DELETE
SETTINGS index_granularity = 8192
'''