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): read charts, samples and autocomplete from the metrics2 tables (#97312)

Frank Hamand9c262001d330
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 31529c18fecc..a9cb0825c5aa 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -116,7 +116,6 @@ from posthog.hogql.database.schema.marketing_costs_precomputed import MarketingC
from posthog.hogql.database.schema.marketing_touchpoints_preaggregated import MarketingTouchpointsPreaggregatedTable
from posthog.hogql.database.schema.metrics import (
MetricAttributesTable,
- MetricSamplesTable,
MetricSeriesTable,
MetricsKafkaMetricsTable,
MetricsTable,
@@ -480,7 +479,6 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:
),
"billing_usage_records": TableNode(name="billing_usage_records", table=BillingUsageRecordsTable()),
"metrics": TableNode(name="metrics", table=MetricsTable()),
- "metric_samples": TableNode(name="metric_samples", table=MetricSamplesTable()),
"metric_series": TableNode(name="metric_series", table=MetricSeriesTable()),
"metric_attributes": TableNode(name="metric_attributes", table=MetricAttributesTable()),
"metrics_kafka_metrics": TableNode(name="metrics_kafka_metrics", table=MetricsKafkaMetricsTable()),
diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.py
index 3eb7e6f236ff..0d776065acd5 100644
--- a/posthog/hogql/database/schema/metrics.py
+++ b/posthog/hogql/database/schema/metrics.py
@@ -18,14 +18,16 @@ HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES = 50_000_000_000
class MetricsTable(Table):
- description: str = "OpenTelemetry metric data points (gauges, sums, histograms), one row per data point."
+ description: str = "OpenTelemetry metric data points (gauges, sums, histograms), one row per data point. Labels are not on the row: join `metric_series` on `series_fingerprint` for `attributes` and `resource_attributes`."
workload: Workload | None = Workload.LOGS # reuse LOGS workload for now
fields: dict[str, FieldOrTable] = {
- "uuid": StringDatabaseField(
- name="uuid", nullable=False, description="Unique identifier of this data point row."
- ),
"team_id": IntegerDatabaseField(name="team_id", nullable=False),
+ "series_fingerprint": IntegerDatabaseField(
+ name="series_fingerprint",
+ nullable=False,
+ description="Hash of the series' label set, assigned at ingest; join key to `metric_series`.",
+ ),
"trace_id": StringDatabaseField(
name="trace_id", nullable=False, description="Trace this metric exemplar is associated with, if any."
),
@@ -43,6 +45,9 @@ class MetricsTable(Table):
nullable=False,
description="When the collector observed/ingested the data point.",
),
+ "original_expiry_timestamp": DateTimeDatabaseField(
+ name="original_expiry_timestamp", nullable=False, description="When the data point leaves retention."
+ ),
"service_name": StringDatabaseField(
name="service_name", nullable=False, description="Name of the service that emitted the metric."
),
@@ -77,9 +82,6 @@ class MetricsTable(Table):
"is_monotonic": BooleanDatabaseField(
name="is_monotonic", nullable=False, description="True if the sum metric only increases."
),
- "resource_attributes": MapStringDatabaseField(
- name="resource_attributes", nullable=False, description="OpenTelemetry resource attributes as a string map."
- ),
"resource_fingerprint": IntegerDatabaseField(
name="resource_fingerprint",
nullable=False,
@@ -90,71 +92,22 @@ class MetricsTable(Table):
nullable=False,
description="Instrumentation scope (library/module) that emitted the metric.",
),
- "attributes": MapStringDatabaseField(
- name="attributes", nullable=False, description="Per-data-point OpenTelemetry attributes as a string map."
- ),
- }
-
- def to_printed_clickhouse(self, context):
- return "metrics"
-
- def to_printed_hogql(self):
- return "metrics"
-
-
-class MetricSamplesTable(Table):
- description: str = "Raw metric emissions: one tiny row per sample (value + timestamp), keyed to a series via `series_fingerprint` and carrying an optional `trace_id` for the metric->trace pivot. Join to `metric_series` for labels. Distinct from `metrics`, which is pre-aggregated."
- workload: Workload | None = Workload.LOGS
-
- fields: dict[str, FieldOrTable] = {
- "team_id": IntegerDatabaseField(name="team_id", nullable=False),
- "metric_name": StringDatabaseField(name="metric_name", nullable=False),
- "series_fingerprint": IntegerDatabaseField(
- name="series_fingerprint",
+ "has_labels": BooleanDatabaseField(
+ name="has_labels",
nullable=False,
- description="Hash of the series' label set; join key to `metric_series`.",
+ description="True when the ingested record carried the series labels; only such records write `metric_series` and `metric_attributes` rows.",
),
- "timestamp": DateTimeDatabaseField(
- name="timestamp", nullable=False, description="When the metric was emitted (UTC)."
- ),
- "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,
- description="Trace this emission belongs to; empty if none. Pivot to spans/logs.",
- ),
- "span_id": StringDatabaseField(name="span_id", nullable=False),
- "trace_flags": IntegerDatabaseField(name="trace_flags", nullable=False),
}
def to_printed_clickhouse(self, context):
- return "metric_samples"
+ return "metrics_distributed"
def to_printed_hogql(self):
- return "metric_samples"
+ return "metrics"
class MetricSeriesTable(Table):
- description: str = "One row per unique metric series (metric + label set), keyed by `series_fingerprint`. Labels are stored here once and joined to `metric_samples` at query time."
+ description: str = "One row per unique metric series (metric + label set), keyed by `series_fingerprint`. Labels are stored here once and joined to `metrics` at query time."
workload: Workload | None = Workload.LOGS
fields: dict[str, FieldOrTable] = {
@@ -163,7 +116,7 @@ class MetricSeriesTable(Table):
"series_fingerprint": IntegerDatabaseField(
name="series_fingerprint",
nullable=False,
- description="Hash of the label set; join key from `metric_samples`.",
+ description="Hash of the label set; join key from `metrics`.",
),
"metric_type": StringDatabaseField(
name="metric_type",
@@ -180,15 +133,24 @@ class MetricSeriesTable(Table):
name="is_monotonic", nullable=False, description="True for monotonically increasing counters."
),
"service_name": StringDatabaseField(name="service_name", nullable=False),
+ "instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),
"resource_attributes": MapStringDatabaseField(name="resource_attributes", nullable=False),
+ "resource_fingerprint": IntegerDatabaseField(
+ name="resource_fingerprint",
+ nullable=False,
+ description="Hash of `resource_attributes`; matches `metrics.resource_fingerprint`.",
+ ),
"attributes": MapStringDatabaseField(name="attributes", nullable=False),
"last_seen": DateTimeDatabaseField(
name="last_seen", nullable=False, description="Most recent sample timestamp seen for this series."
),
+ "original_expiry_timestamp": DateTimeDatabaseField(
+ name="original_expiry_timestamp", nullable=False, description="When the series leaves retention."
+ ),
}
def to_printed_clickhouse(self, context):
- return "metric_series"
+ return "metric_series_distributed"
def to_printed_hogql(self):
return "metric_series"
@@ -221,18 +183,16 @@ class MetricAttributesTable(Table):
nullable=False,
description="Number of data points with this key/value in the time bucket.",
),
- "resource_fingerprint": IntegerDatabaseField(
- name="resource_fingerprint",
- nullable=False,
- description="Hash of the resource attributes the count is scoped to.",
- ),
"service_name": StringDatabaseField(
name="service_name", nullable=False, description="Service the attribute counts are scoped to."
),
+ "original_expiry_time_bucket": DateTimeDatabaseField(
+ name="original_expiry_time_bucket", nullable=False, description="When the bucket leaves retention."
+ ),
}
def to_printed_clickhouse(self, context):
- return "metric_attributes"
+ return "metric_attributes_distributed"
def to_printed_hogql(self):
return "metric_attributes"
diff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.py
index f40bdc68185e..f5624181303d 100644
--- a/products/metrics/backend/anomaly.py
+++ b/products/metrics/backend/anomaly.py
@@ -31,7 +31,12 @@ from products.metrics.backend.facade.contracts import (
MetricSeries,
)
from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner
-from products.metrics.backend.metric_query_runner import _INTERVAL_LADDER, MetricQueryRunner, _pick_interval
+from products.metrics.backend.metric_query_runner import (
+ _INTERVAL_LADDER,
+ MetricQueryRunner,
+ _pick_interval,
+ time_range_expr,
+)
# How many label keys to drill into and how many movers to report.
MAX_CANDIDATE_KEYS = 4
@@ -226,28 +231,39 @@ def characterize_anomaly(
def _discover_candidate_keys(
team: Team, metric_name: str, date_from: dt.datetime, date_to: dt.datetime
) -> tuple[str, ...]:
- """Most common attribute keys on the metric's rows in the window, with
- service_name always considered (`attribute_field` resolves it to the
- first-class column). The dotted `service.name` resource attribute is
- normalized to `service_name` so the same key isn't drilled twice."""
+ """Most common attribute keys across the metric's series that reported in
+ the window, with service_name always considered (`attribute_field` resolves
+ it to the first-class column). The dotted `service.name` resource attribute
+ is normalized to `service_name` so the same key isn't drilled twice.
+
+ Keys are counted per series rather than per data point: the labels live on
+ `metric_series`, and a key carried by many series is the one worth drilling
+ into, whichever series scrapes fastest."""
query = parse_select(
"""
SELECT key, count() AS occurrences
FROM (
SELECT arrayJoin(arrayConcat(mapKeys(attributes), mapKeys(resource_attributes))) AS key
- FROM posthog.metrics
- WHERE metric_name = {metric_name}
- AND timestamp >= {date_from}
- AND timestamp < {date_to}
+ FROM (
+ SELECT any(attributes) AS attributes, any(resource_attributes) AS resource_attributes
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ AND series_fingerprint IN (
+ SELECT DISTINCT series_fingerprint
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND {time_range}
+ )
+ GROUP BY series_fingerprint
+ )
)
GROUP BY key
- ORDER BY occurrences DESC
+ ORDER BY occurrences DESC, key ASC
LIMIT {limit}
""",
placeholders={
"metric_name": ast.Constant(value=metric_name),
- "date_from": ast.Constant(value=date_from),
- "date_to": ast.Constant(value=date_to),
+ "time_range": time_range_expr(date_from, date_to),
"limit": ast.Constant(value=MAX_CANDIDATE_KEYS),
},
)
diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.py
index 5f48fa03624e..ff3a16c44d72 100644
--- a/products/metrics/backend/diagnostics.py
+++ b/products/metrics/backend/diagnostics.py
@@ -41,7 +41,9 @@ from products.metrics.backend.metric_query_runner import (
MetricQueryRunner,
_interval_step,
counter_lookback,
- filters_expr,
+ series_labels_query,
+ series_scope_expr,
+ time_range_expr,
type_filter_expr,
)
@@ -70,32 +72,46 @@ def _raw_samples_query(
filters: Sequence[MetricFilter],
metric_type: str | None,
) -> ast.SelectQuery:
+ # The labels are joined on after the LIMIT so the row bound applies to the
+ # data points read, not to the join output. A series without a row yet
+ # keeps its samples and shows empty labels.
query = parse_select(
"""
SELECT
- service_name,
- attributes,
- resource_attributes,
- metric_type,
- aggregation_temporality,
- timestamp,
- value
- FROM posthog.metrics
- WHERE metric_name = {metric_name}
- AND timestamp >= {date_from}
- AND timestamp < {date_to}
- AND {filters}
- AND {type_filter}
- ORDER BY timestamp ASC
- LIMIT {row_limit}
+ s.series_fingerprint,
+ s.service_name,
+ ser.attributes,
+ ser.resource_attributes,
+ s.metric_type,
+ s.aggregation_temporality,
+ s.timestamp,
+ s.value
+ FROM (
+ SELECT
+ series_fingerprint,
+ service_name,
+ metric_type,
+ aggregation_temporality,
+ timestamp,
+ value
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND {time_range}
+ AND {series_scope}
+ AND {type_filter}
+ ORDER BY timestamp ASC
+ LIMIT {row_limit}
+ ) AS s
+ LEFT JOIN {series_labels} AS ser ON s.series_fingerprint = ser.series_fingerprint
+ ORDER BY s.timestamp ASC
""",
placeholders={
"metric_name": ast.Constant(value=metric_name),
- "date_from": ast.Constant(value=date_from),
- "date_to": ast.Constant(value=bucket_end),
- "filters": filters_expr(filters),
+ "time_range": time_range_expr(date_from, bucket_end),
+ "series_scope": series_scope_expr(metric_name, filters),
"type_filter": type_filter_expr(metric_type),
"row_limit": ast.Constant(value=_MAX_ROWS_READ),
+ "series_labels": series_labels_query(metric_name),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -177,20 +193,23 @@ def decompose_bucket(
rows = response.results or []
rows_truncated = len(rows) >= _MAX_ROWS_READ
- # Group the raw rows into series, keyed the way a series is actually
- # identified: everything that isn't the timestamp or the value.
- grouped: dict[tuple, list[Sample]] = {}
- predecessors: dict[tuple, Sample] = {}
- identities: dict[tuple, tuple[str, dict[str, str], dict[str, str]]] = {}
+ # Group the raw rows into series by the fingerprint ingest assigned, which
+ # is the same identity the chart's window functions partition on.
+ grouped: dict[int, list[Sample]] = {}
+ predecessors: dict[int, Sample] = {}
+ identities: dict[int, tuple[str, dict[str, str], dict[str, str]]] = {}
resolved_type = metric_type or ""
temporality = ""
- for service_name, attributes, resource_attributes, row_metric_type, row_temporality, timestamp, value in rows:
- key = (
- service_name,
- tuple(sorted(dict(attributes).items())),
- tuple(sorted(dict(resource_attributes).items())),
- row_metric_type,
- )
+ for (
+ key,
+ service_name,
+ attributes,
+ resource_attributes,
+ row_metric_type,
+ row_temporality,
+ timestamp,
+ value,
+ ) in rows:
sample = Sample(timestamp=_as_utc(timestamp), value=float(value))
if sample.timestamp < bucket_start:
# Only a series' newest pre-bucket reading matters: it is the
@@ -200,7 +219,7 @@ def decompose_bucket(
predecessors[key] = sample
else:
grouped.setdefault(key, []).append(sample)
- identities.setdefault(key, (service_name, dict(attributes), dict(resource_attributes)))
+ identities.setdefault(key, (service_name, dict(attributes or {}), dict(resource_attributes or {})))
# A bucket normally holds one type and one temporality; when a name has
# been ingested as several, the first is enough to plan a reduction and
# the type check reports the blend separately.
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index f4a8cce3bfdb..2dc59bdac0ab 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -179,7 +179,7 @@ class MetricAnomalyReport:
@dataclass(frozen=True, slots=True)
class MetricEventSample:
- """A single raw metric emission: one `metric_samples` row enriched with its
+ """A single raw metric emission: one `metrics` row enriched with its
`metric_series` labels. Backs the Samples view and the metric->trace pivot.
Distinct from `MetricSeries`, which is aggregated at query time.
"""
diff --git a/products/metrics/backend/metric_attributes_query_runner.py b/products/metrics/backend/metric_attributes_query_runner.py
index ba52cf45b568..33f303dd126b 100644
--- a/products/metrics/backend/metric_attributes_query_runner.py
+++ b/products/metrics/backend/metric_attributes_query_runner.py
@@ -1,7 +1,7 @@
"""Attribute key/value autocomplete for the metrics filter bar.
-Queries the `metric_attributes` aggregate table (fed by MVs on `metrics1`)
-rather than the raw events table, mirroring the logs product's
+Queries the `metric_attributes` aggregate table (fed by MVs on the metrics
+ingest stream) rather than the raw data point table, mirroring the logs product's
`LogAttributesQueryRunner`/`LogValuesQueryRunner` pair. Keys are searched
across both datapoint ('metric') and resource attributes in one pass — the
viewer filters with scope 'auto', so the split is invisible to users.
@@ -26,10 +26,10 @@ from products.metrics.backend.search import ilike_pattern
# `metric_query_runner.attribute_field`.
_SERVICE_NAME_KEYS: frozenset[str] = frozenset({"service_name", "service.name"})
-# `time_bucket` floors timestamps to 10-minute buckets (see the MVs in
-# posthog/clickhouse/metrics/metrics1.py); widen the lower bound so points near
+# `time_bucket` floors timestamps to hourly buckets (see `_attributes_mv` in
+# posthog/clickhouse/metrics/metrics2.py); widen the lower bound so points near
# the window start aren't dropped with their bucket.
-_TIME_BUCKET_INTERVAL = dt.timedelta(minutes=10)
+_TIME_BUCKET_INTERVAL = dt.timedelta(hours=1)
# Without an explicit window, suggest from recent data only — same lookback the
# metric names picker uses.
diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.py
index c6ca25dcdc8f..5f9ffb77060f 100644
--- a/products/metrics/backend/metric_event_samples_query_runner.py
+++ b/products/metrics/backend/metric_event_samples_query_runner.py
@@ -1,15 +1,16 @@
-"""Raw metric emissions for a metric, from the metric_samples/metric_series split.
+"""Raw metric emissions for a metric, from the metrics/metric_series split.
-Unlike `MetricQueryRunner` (which aggregates `metrics1` into a time series), this
+Unlike `MetricQueryRunner` (which aggregates `metrics` into a time series), this
returns individual emissions — value, attributes, and the trace linkage — newest
first. It backs the Samples view and the metric->trace pivot.
-Joins `posthog.metric_samples` (the tiny hot rows) to `posthog.metric_series`
+Joins `posthog.metrics` (one row per data point) 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. 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).
+ReplacingMergeTree duplicate never multiplies a sample. Everything except the
+two label maps comes from the sample row itself, so an emission whose series
+row hasn't landed yet still renders with its name and type (labels fall back
+to empty).
Trace/span ids are stored base64-encoded (as capture-logs writes exemplars) but
cross the API boundary as hex, matching the tracing product's contract — so a
@@ -24,7 +25,7 @@ from typing import Any
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES
-from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
@@ -32,7 +33,7 @@ from posthog.models import Team
from products.metrics.backend.facade.contracts import MetricFilter
from products.metrics.backend.facade.enums import MetricType
-from products.metrics.backend.metric_query_runner import filters_expr, type_filter_expr
+from products.metrics.backend.metric_query_runner import series_scope_expr, time_range_expr, type_filter_expr
# This runs on the ClickHouse cluster shared with the live logs/traces
# products, so cap how much one request may read. Same budget the chart
@@ -76,9 +77,9 @@ class MetricEventSamplesQueryRunner:
if not metric_name and not trace_id:
raise ValueError("metric_name or trace_id is required")
if not metric_name and (filters or metric_type is not None):
- # Label filters and the type constraint scope series of ONE metric; without a
- # name there is no series set to scope, so honoring them would silently drop
- # every orphan emission across all metrics.
+ # Label filters scope the series of ONE metric; without a name there is no
+ # series set to scope. The type constraint is kept to the same rule so the
+ # trace pivot stays a plain "everything this trace touched" view.
raise ValueError("filters and metric_type require metric_name")
if date_to <= date_from:
raise ValueError("date_to must be after date_from")
@@ -100,58 +101,42 @@ class MetricEventSamplesQueryRunner:
self.metric_type = metric_type
self.limit = limit
- def _series_scope_expr(self) -> ast.Expr:
- """Restrict the emissions to the series the caller's label filters select.
-
- Labels live only on `metric_series`, so the predicate has to be an IN
- over fingerprints, and it has to sit inside the sample subquery before
- its LIMIT. Filtering after the LIMIT would take the newest `limit`
- emissions across every series and then discard most of them, so a
- filtered view would look almost empty while the chart shows plenty.
-
- TRUE when nothing is pinned, which keeps the orphan case working: a
- sample whose series row hasn't landed yet still renders. Once a filter
- or a metric type is pinned there is no way to tell whether an orphan
- belongs to the selection, so it drops out.
- """
- if not self.filters and self.metric_type is None:
- return ast.Constant(value=True)
- return parse_expr(
- """
- series_fingerprint IN (
- SELECT series_fingerprint
- FROM posthog.metric_series
- WHERE metric_name = {metric_name}
- AND {type_filter}
- AND {filters}
- )
- """,
- placeholders={
- "metric_name": ast.Constant(value=self.metric_name),
- "type_filter": type_filter_expr(self.metric_type.value if self.metric_type else None),
- "filters": filters_expr(self.filters),
- },
- )
-
def run(self) -> list[dict[str, Any]]:
# The trace filter is an always-present predicate that is a no-op when no
# trace is given, so the optional clause never has to be spliced into the
# query string (which would collide with the HogQL placeholder braces) —
# an empty {trace_id} matches every row. Samples are filtered + limited in
- # the CTE, then left-joined to the deduped series for labels. The series
- # side reads only the label sets of the matched samples: without that
- # bound, a query with no metric name (the trace pivot) would aggregate
- # every series in the project just to enrich at most {limit} rows.
+ # the CTE, then left-joined to the deduped series for labels. The label
+ # filters sit inside the CTE, before its LIMIT: filtering after the LIMIT
+ # would take the newest `limit` emissions across every series and then
+ # discard most of them, so a filtered view would look almost empty while
+ # the chart shows plenty. The series side reads only the label sets of
+ # the matched samples: without that bound, a query with no metric name
+ # (the trace pivot) would aggregate every series in the project just to
+ # enrich at most {limit} rows.
query = parse_select(
"""
WITH matched_samples AS (
- SELECT team_id, metric_name, series_fingerprint, timestamp, value, count, trace_id, span_id
- FROM posthog.metric_samples
+ SELECT
+ team_id,
+ metric_name,
+ series_fingerprint,
+ timestamp,
+ value,
+ count,
+ trace_id,
+ span_id,
+ metric_type,
+ unit,
+ aggregation_temporality,
+ is_monotonic,
+ service_name
+ FROM posthog.metrics
WHERE ({metric_name} = '' OR metric_name = {metric_name})
- AND timestamp >= {date_from}
- AND timestamp < {date_to}
+ AND {time_range}
AND ({trace_id} = '' OR trace_id = {trace_id})
AND ({span_id} = '' OR span_id = {span_id})
+ AND {type_filter}
AND {series_scope}
ORDER BY timestamp DESC
LIMIT {limit}
@@ -159,13 +144,13 @@ class MetricEventSamplesQueryRunner:
SELECT
s.timestamp,
s.metric_name,
- ser.metric_type,
+ s.metric_type,
s.value,
s.count,
- ser.unit,
- ser.aggregation_temporality,
- ser.is_monotonic,
- ser.service_name,
+ s.unit,
+ s.aggregation_temporality,
+ s.is_monotonic,
+ s.service_name,
hex(tryBase64Decode(s.trace_id)) AS trace_id,
hex(tryBase64Decode(s.span_id)) AS span_id,
ser.attributes,
@@ -176,11 +161,6 @@ class MetricEventSamplesQueryRunner:
team_id,
metric_name,
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
FROM posthog.metric_series
@@ -196,11 +176,11 @@ class MetricEventSamplesQueryRunner:
""",
placeholders={
"metric_name": ast.Constant(value=self.metric_name),
- "date_from": ast.Constant(value=self.date_from),
- "date_to": ast.Constant(value=self.date_to),
+ "time_range": time_range_expr(self.date_from, self.date_to),
"trace_id": ast.Constant(value=self.trace_id),
"span_id": ast.Constant(value=self.span_id),
- "series_scope": self._series_scope_expr(),
+ "type_filter": type_filter_expr(self.metric_type.value if self.metric_type else None),
+ "series_scope": series_scope_expr(self.metric_name, self.filters),
"limit": ast.Constant(value=self.limit),
},
)
diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.py
index bc9b429678b2..1b44399e3ea2 100644
--- a/products/metrics/backend/metric_names_query_runner.py
+++ b/products/metrics/backend/metric_names_query_runner.py
@@ -2,11 +2,11 @@
Reads `metric_series` (one row per metric + label-set) rather than the raw
`metrics` datapoint table. Both are fed from the same Kafka Avro stream, so
-they carry the same names, but the series table is two orders of magnitude
-smaller for the same window — on a busy team, ~3.6M rows against ~800M. It also
-sorts by `(team_id, metric_name, series_fingerprint)`, so `metric_name` is the
-leading key once `team_id` is pinned, where `metrics1` buries it behind
-`time_bucket` and `service_name`.
+they carry the same names, but the series table holds one row per series
+where the datapoint table holds one per scrape, so it is orders of magnitude
+smaller for the same window. It also sorts by `(team_id, metric_name,
+series_fingerprint)` with a materialized `last_seen`, so the lookback needs no
+scan over the datapoint rows.
No FINAL. ReplacingMergeTree duplicates share `(team_id, metric_name,
series_fingerprint)`, and `max(last_seen)` picks the row FINAL would keep, since
@@ -44,7 +44,8 @@ _QUERY_SETTINGS = HogQLGlobalSettings(
read_overflow_mode="break",
)
-# `metric_series` drops rows 90 days past `last_seen`; `metrics1` has no TTL.
+# Both `metric_series` and `metrics` expire at the same `original_expiry_timestamp`,
+# which ingest sets to the team's retention (90 days by default).
# A lookback beyond this would quietly return fewer names than the raw table has.
SERIES_RETENTION = dt.timedelta(days=90)
@@ -98,9 +99,9 @@ class MetricNamesQueryRunner:
# selection: a sender that omits the `service.name` resource attribute
# lands in the group the overview labels "unknown".
self.services = tuple(sorted(set(services)))
- # Sparklines read `metric_samples`, whose ordering puts `timestamp`
- # behind `series_fingerprint`, so the scan is the expensive part of a
- # name lookup. Callers that only need the type (anomaly defaults) skip it.
+ # Sparklines read the `metrics` data points, so the scan is the
+ # expensive part of a name lookup. Callers that only need the type
+ # (anomaly defaults) skip it.
self.include_sparklines = include_sparklines
def _build_query(self) -> ast.SelectQuery:
@@ -203,31 +204,32 @@ class MetricNamesQueryRunner:
def _sparklines(self, names: Sequence[str]) -> dict[str, list[float]]:
"""A small recent shape per metric, for the catalog cards.
- Reads `metric_samples` (raw emissions) rather than the pre-aggregated
- `metrics` table, so a series written without a metrics row still draws —
- the same reason the name list reads `metric_series`. Each metric is
- bucketed onto a fixed grid and averaged per bucket across its series; a
- card only shows direction and spikes, so per-series fidelity is not worth
- the rows it would cost. Only the names this page returned are read, so a
- scoped picker never scans the whole samples table.
+ Reads the raw `metrics` data points. Each metric is bucketed onto a
+ fixed grid and averaged per bucket across its series; a card only shows
+ direction and spikes, so per-series fidelity is not worth the rows it
+ would cost. Only the names this page returned are read, so a scoped
+ picker never scans the whole table.
"""
if not names:
return {}
- # The grid anchors to the query's `now()`: bucket edges land on the
- # window endpoints, so the window always holds exactly MAX_POINTS buckets
- # (a bare toStartOfInterval aligns to wall-clock boundaries and a window
- # starting mid-bucket intersects one extra).
+ # The grid anchors to the window start: bucket edges land on the window
+ # endpoints, so the window always holds exactly MAX_POINTS buckets (a
+ # bare toStartOfInterval aligns to wall-clock boundaries and a window
+ # starting mid-bucket intersects one extra). The anchor is computed here
+ # rather than from the query's `now()` so the predicate below and the
+ # grid agree on the same instant.
bucket_seconds = max(int(SPARKLINE_WINDOW.total_seconds()) // SPARKLINE_MAX_POINTS, 1)
- window_seconds = int(SPARKLINE_WINDOW.total_seconds())
+ window_start = dt.datetime.now(dt.UTC) - SPARKLINE_WINDOW
query = parse_select(
"""
SELECT
metric_name AS name,
- toDateTime(intDiv(toUnixTimestamp(timestamp) - toUnixTimestamp(now() - {window_interval}), {bucket_seconds}) * {bucket_seconds} + toUnixTimestamp(now() - {window_interval})) AS bucket_start,
+ toDateTime(intDiv(toUnixTimestamp(timestamp) - toUnixTimestamp({window_start}), {bucket_seconds}) * {bucket_seconds} + toUnixTimestamp({window_start})) AS bucket_start,
avg(value) AS bucket_value
- FROM posthog.metric_samples
- WHERE timestamp > now() - {window_interval}
+ FROM posthog.metrics
+ WHERE timestamp > {window_start}
+ AND time_bucket >= {bucket_from}
AND metric_name IN {names}
AND series_fingerprint IN {series_scope}
GROUP BY name, bucket_start
@@ -235,7 +237,11 @@ class MetricNamesQueryRunner:
""",
placeholders={
"bucket_seconds": ast.Constant(value=bucket_seconds),
- "window_interval": ast.Call(name="toIntervalSecond", args=[ast.Constant(value=window_seconds)]),
+ "window_start": ast.Constant(value=window_start),
+ # `metrics` sorts by `time_bucket` (the UTC hour) before
+ # `timestamp`, so the hour bound is what lets ClickHouse skip
+ # everything older than the window.
+ "bucket_from": ast.Constant(value=window_start.replace(minute=0, second=0, microsecond=0)),
"names": ast.Tuple(exprs=[ast.Constant(value=name) for name in names]),
# A sample carries no service column; its series_fingerprint is
# the link back to the series row that does. Without this scope,
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 08ae5c919658..045a5e2dd3c3 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -7,10 +7,16 @@ range, with a choice of aggregation. Modelled after the logs
isn't going through HogQL `DataNode` caching, schema-gen or the data-viz
pipeline yet.
-Every aggregation resolves per physical series (`_series_key_exprs`) before
+Every aggregation resolves per physical series (`_series_key_expr`) before
combining across series: instant aggregations reduce each series to its last
sample in the bucket, counter functions diff within a series. Aggregating raw
samples instead would weight a series by how often it was scraped.
+
+Storage is the `metrics` / `metric_series` split: a data point row carries only
+its `series_fingerprint`, and the label maps live once per series on
+`metric_series`. Label filters therefore become a fingerprint IN-list resolved
+on the series table (`series_scope_expr`), and group-by labels come from a join
+to the series table after the per-series reduction (`_splice_group_columns`).
"""
import re
@@ -57,31 +63,26 @@ _QUERY_SETTINGS = HogQLGlobalSettings(
read_overflow_mode="throw",
)
-# The OTel service name is a first-class `metrics1` column (extracted at
-# ingest from the `service.name` resource attribute); both spellings resolve
-# to it so filters/group-bys match real ingested rows.
+# The OTel service name is a first-class column on both `metrics` and
+# `metric_series` (extracted at ingest from the `service.name` resource
+# attribute); both spellings resolve to it so filters/group-bys match real
+# ingested rows.
_SERVICE_NAME_KEYS: frozenset[str] = frozenset({"service_name", "service.name"})
-# Synthetic per-data-point attribute ingest stamps on a point whose timestamp it
-# had to override. Never part of a series' identity — see `_series_key_exprs`.
-_ORIGINAL_TIMESTAMP_KEY = "$originalTimestamp"
-
def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
"""Build the HogQL AST node that accesses a metric attribute by name.
- This is the single seam between the upcoming filter / group-by / rate /
- histogram-quantile work (PR3-PR6) and the underlying `metrics1` storage
- shape. When the Snuffle-style streams-table rewrite lands, only this
- function changes — every call site keeps working.
+ The expression reads the `attributes` / `resource_attributes` maps, which
+ exist only on `metric_series`, so it must land in a scope where that table
+ (or a subquery re-exporting those columns) is visible.
`scope` resolves *where* the attribute lives:
- ``"resource"`` — look in ``resource_attributes`` only (Prometheus-style
`service.name`, `k8s.pod.name` — set once per scrape target).
- - ``"attribute"`` — look in ``attributes`` only (the alias view of
- ``attributes_map_str`` that strips the 5-char ``__str`` type tag from
- each key). Per-data-point labels like ``http.method`` live here.
+ - ``"attribute"`` — look in ``attributes`` only. Per-data-point labels
+ like ``http.method`` live here.
- ``"auto"`` (default) — try resource first, fall back to attribute if
empty. Map lookups in ClickHouse return ``''`` for missing keys, not
NULL, so the fallback compares against the empty string.
@@ -117,41 +118,21 @@ def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
)
-def _series_key_exprs() -> list[ast.Expr]:
+def _series_key_expr() -> ast.Expr:
"""Identifies the physical series a row belongs to.
Every aggregation resolves per series before combining across series, so
all three query builders share this definition rather than restating it.
- `metric_type` belongs to the identity, not just to filtering: one name can
- be ingested as both a counter and a gauge, and `metric_type` is optional on
- the query, so an unconstrained query sees both sets of rows at once.
-
- `$originalTimestamp` is dropped back out of `attributes`. Ingest adds it to
- the map for a point whose timestamp is more than a day off, carrying a
- per-sample value, and deliberately fingerprints the series before adding it
- (`compute_series_fingerprint` in `rust/capture-logs/src/metric_record.rs`).
- Keeping it would shatter a skewed exporter's series into one series per
- sample, which is the exact weighting these keys exist to prevent.
-
- `resource_attributes` appears here rather than its `resource_fingerprint`
- digest so that the key stays exact — a hash collision would merge two
- targets into one series.
-
- These are grouping and partitioning keys only; a query that also needs the
- attributes themselves reads them off `posthog.metrics` in the same scope,
- because a column aliased `attributes` in a scope that already resolves the
- `attributes` map collides with it.
+ `series_fingerprint` is assigned once at ingest over the metric name, the
+ metric type, the service name and both label maps (`compute_series_fingerprint`
+ in `rust/capture-logs/src/metric_record.rs`), so it already separates a
+ counter from a gauge of the same name. Ingest fingerprints the series
+ before it adds the synthetic `$originalTimestamp` attribute to a skewed
+ point, so that per-sample value never shatters a series into one series
+ per sample.
"""
- return [
- ast.Field(chain=["service_name"]),
- ast.Field(chain=["resource_attributes"]),
- parse_expr(
- "mapFilter((k, v) -> k != {synthetic}, attributes)",
- placeholders={"synthetic": ast.Constant(value=_ORIGINAL_TIMESTAMP_KEY)},
- ),
- ast.Field(chain=["metric_type"]),
- ]
+ return ast.Field(chain=["series_fingerprint"])
def _aggregation_expr(name: str, value: ast.Expr) -> ast.Expr:
@@ -311,9 +292,9 @@ def _align_to_interval(timestamp: dt.datetime, interval: str, *, tzinfo: ZoneInf
# Prometheus's default lookback delta. One interval step on its own is not
# enough when the scrape interval is coarser than the bucket — a 60s scrape on
-# a `second` or `minute` chart — and `metrics1` is partitioned by day with
-# `timestamp` last in the sort key, so reaching back five minutes inside a day
-# reads the same partitions as reaching back one.
+# a `second` or `minute` chart — and `metrics` sorts by an hourly `time_bucket`
+# with `timestamp` last in the key, so reaching back five minutes inside an hour
+# reads the same granules as reaching back one.
_MIN_COUNTER_LOOKBACK = dt.timedelta(minutes=5)
@@ -370,6 +351,38 @@ def filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr:
return ast.And(exprs=conditions)
+def time_range_expr(date_from: dt.datetime, date_to: dt.datetime) -> ast.Expr:
+ """Bound a `metrics` read to `[date_from, date_to)`.
+
+ The `timestamp` pair is the exact bound. The `time_bucket` pair is what
+ lets ClickHouse skip granules: `metrics` sorts by `(team_id, metric_name,
+ time_bucket, ...)` and is partitioned by expiry, so a bare `timestamp`
+ predicate prunes nothing inside a metric and the read covers the metric's
+ whole retention. `time_bucket` is `toStartOfHour(timestamp)` in UTC, so
+ the bounds snap to the UTC hour here rather than in HogQL, where
+ `toStartOfHour` follows the project's timezone and lands on :30 for a
+ half-hour offset.
+ """
+ return parse_expr(
+ """
+ timestamp >= {date_from}
+ AND timestamp < {date_to}
+ AND time_bucket >= {bucket_from}
+ AND time_bucket <= {bucket_to}
+ """,
+ placeholders={
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ "bucket_from": ast.Constant(value=_utc_hour(date_from)),
+ "bucket_to": ast.Constant(value=_utc_hour(date_to)),
+ },
+ )
+
+
+def _utc_hour(value: dt.datetime) -> dt.datetime:
+ return value.astimezone(dt.UTC).replace(minute=0, second=0, microsecond=0)
+
+
def type_filter_expr(metric_type: str | None) -> ast.Expr:
"""Constrains rows to one metric type. A name can exist as several
types (a counter and a gauge); their series are distinct and must not
@@ -382,6 +395,59 @@ def type_filter_expr(metric_type: str | None) -> ast.Expr:
return parse_expr("metric_type = {metric_type}", placeholders={"metric_type": ast.Constant(value=metric_type)})
+def series_scope_expr(metric_name: str, filters: Sequence[MetricFilter]) -> ast.Expr:
+ """Restrict `metrics` rows to the series the label filters select.
+
+ Labels live only on `metric_series`, so a filter becomes an IN over the
+ fingerprints of the matching series. The subquery is pinned to one metric
+ name because the series table sorts by `(team_id, metric_name,
+ series_fingerprint)`, which keeps the lookup to that metric's series.
+
+ TRUE when there are no filters, so a data point whose series row has not
+ landed yet still counts. Once a filter is set there is no label set to
+ match such a point against, so it drops out.
+ """
+ if not filters:
+ return ast.Constant(value=True)
+ return parse_expr(
+ """
+ series_fingerprint IN (
+ SELECT series_fingerprint
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ AND {filters}
+ )
+ """,
+ placeholders={"metric_name": ast.Constant(value=metric_name), "filters": filters_expr(filters)},
+ )
+
+
+def series_labels_query(metric_name: str) -> ast.SelectQuery:
+ """One row per series of `metric_name` with its labels, for joining onto a
+ per-series reduction.
+
+ Grouped rather than read with FINAL: ReplacingMergeTree duplicates share
+ the fingerprint and carry the same labels, since the labels are the
+ fingerprint's input, so `any()` cannot pick a stale value and the join
+ never multiplies a series.
+ """
+ query = parse_select(
+ """
+ SELECT
+ series_fingerprint,
+ any(service_name) AS service_name,
+ any(attributes) AS attributes,
+ any(resource_attributes) AS resource_attributes
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ GROUP BY series_fingerprint
+ """,
+ placeholders={"metric_name": ast.Constant(value=metric_name)},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
class MetricQueryRunner:
def __init__(
self,
@@ -512,32 +578,42 @@ class MetricQueryRunner:
"use a coarser interval, a narrower range, or a lower-cardinality group_by"
)
- def _splice_group_columns(self, query: ast.SelectQuery, *, resolve_in: ast.SelectQuery | None = None) -> None:
+ def _splice_group_columns(self, query: ast.SelectQuery) -> None:
"""Insert the group_by label columns between `time` and `value` —
parse_select placeholders can't express a variable column count.
- `attribute_field` resolves against the scope of the query it lands in,
- so that query must expose `service_name`, `attributes` and
- `resource_attributes` under those names — read straight off
- `posthog.metrics`, or re-exported from a subquery. Pass `resolve_in`
- when the labels have to be built a level down instead; `query` then
- only forwards them up by name.
+ `query` reads a per-series subquery aliased `s` that exports
+ `series_fingerprint`. The labels are not on that side, so a LEFT JOIN
+ to the metric's series (`series_labels_query`, aliased `ser`) is added
+ on the fingerprint, and each label resolves against `ser`. The join is
+ only attached when there is a group_by, so an ungrouped chart never
+ pays for it. A series whose row has not landed yet keeps its points
+ and groups under an empty label.
"""
+ if not self.group_by:
+ return
assert query.group_by is not None
+ assert query.select_from is not None and query.select_from.alias == "s"
+ query.select_from.next_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=series_labels_query(self.metric_name),
+ alias="ser",
+ constraint=ast.JoinConstraint(
+ expr=parse_expr("s.series_fingerprint = ser.series_fingerprint"), constraint_type="ON"
+ ),
+ )
for index, group in enumerate(self.group_by):
alias = f"group_{index}"
label_expr: ast.Expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])
- if resolve_in is not None:
- assert resolve_in.group_by is not None
- resolve_in.select.append(ast.Alias(alias=alias, expr=label_expr))
- resolve_in.group_by.append(ast.Field(chain=[alias]))
- label_expr = ast.Field(chain=[alias])
query.select.insert(1 + index, ast.Alias(alias=alias, expr=label_expr))
query.group_by.append(ast.Field(chain=[alias]))
def _type_filter_expr(self) -> ast.Expr:
return type_filter_expr(self.metric_type)
+ def _series_scope_expr(self) -> ast.Expr:
+ return series_scope_expr(self.metric_name, self.filters)
+
def _build_simple_query(self) -> ast.SelectQuery:
"""sum/avg/count/p95: collapse each series to one value per bucket,
then aggregate across series — PromQL instant-vector semantics.
@@ -552,9 +628,8 @@ class MetricQueryRunner:
make `argMax` pick between them arbitrarily; they are the same
reading, so either answer is right.
- Group-by labels are built in the inner query, where the attribute maps
- are still in scope. A label is constant within a series, so the outer
- query just carries it up.
+ Group-by labels join onto the reduced series by fingerprint. A label is
+ constant within a series, so the outer query groups on it directly.
"""
# `metrics` is only registered under the `posthog.` HogQL namespace
# (see posthog/hogql/database/database.py).
@@ -566,15 +641,15 @@ class MetricQueryRunner:
FROM (
SELECT
toStartOfInterval(timestamp, {interval}) AS time,
+ series_fingerprint AS series_fingerprint,
argMax(value, timestamp) AS series_value
FROM posthog.metrics
WHERE metric_name = {metric_name}
- AND timestamp >= {date_from}
- AND timestamp < {date_to}
- AND {filters}
+ AND {time_range}
+ AND {series_scope}
AND {type_filter}
- GROUP BY time
- )
+ GROUP BY time, {series_key}
+ ) AS s
GROUP BY time
ORDER BY time ASC
LIMIT {row_limit}
@@ -583,29 +658,22 @@ class MetricQueryRunner:
"interval": _interval_expr(self.interval),
"aggregation": _aggregation_expr(self.aggregation, ast.Field(chain=["series_value"])),
"metric_name": ast.Constant(value=self.metric_name),
- "date_from": ast.Constant(value=self.date_from),
- "date_to": ast.Constant(value=self.date_to),
- "filters": filters_expr(self.filters),
+ "time_range": time_range_expr(self.date_from, self.date_to),
+ "series_scope": self._series_scope_expr(),
+ "series_key": _series_key_expr(),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
assert isinstance(query, ast.SelectQuery)
- # Appended rather than written into the template so the key stays
- # defined in exactly one place; a placeholder can only carry one
- # expression.
- inner = query.select_from.table if query.select_from else None
- assert isinstance(inner, ast.SelectQuery) and inner.group_by is not None
- inner.group_by.extend(_series_key_exprs())
- self._splice_group_columns(query, resolve_in=inner)
+ self._splice_group_columns(query)
return query
def _build_counter_query(self) -> ast.SelectQuery:
"""rate/increase: per-underlying-series deltas, then aggregate.
- Each physical series (service_name, resource_fingerprint, datapoint
- attributes) gets its samples diffed in timestamp order via a window
- function, Prometheus-style:
+ Each physical series (`series_fingerprint`) gets its samples diffed in
+ timestamp order via a window function, Prometheus-style:
- cumulative temporality: contribution = value - prev, clamped for
counter resets (value < prev means the counter restarted, so the
@@ -634,9 +702,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp AS sample_timestamp,
- service_name AS service_name,
- attributes AS attributes,
- resource_attributes AS resource_attributes,
+ series_fingerprint AS series_fingerprint,
multiIf(
aggregation_temporality = 'delta', value,
isNull(prev_value), NULL,
@@ -646,11 +712,9 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp,
- service_name,
+ series_fingerprint,
value,
aggregation_temporality,
- attributes,
- resource_attributes,
lagInFrame(toNullable(value)) OVER (
PARTITION BY {series_key}
ORDER BY timestamp ASC
@@ -658,12 +722,11 @@ class MetricQueryRunner:
) AS prev_value
FROM posthog.metrics
WHERE metric_name = {metric_name}
- AND timestamp >= {scan_from}
- AND timestamp < {date_to}
- AND {filters}
+ AND {scan_range}
+ AND {series_scope}
AND {type_filter}
)
- )
+ ) AS s
WHERE sample_timestamp >= {date_from}
GROUP BY time
HAVING isNotNull(value)
@@ -673,12 +736,11 @@ class MetricQueryRunner:
placeholders={
"interval": _interval_expr(self.interval),
"divisor": ast.Constant(value=divisor),
- "series_key": ast.Tuple(exprs=_series_key_exprs()),
+ "series_key": _series_key_expr(),
"metric_name": ast.Constant(value=self.metric_name),
- "scan_from": ast.Constant(value=self.date_from - counter_lookback(self.interval)),
+ "scan_range": time_range_expr(self.date_from - counter_lookback(self.interval), self.date_to),
"date_from": ast.Constant(value=self.date_from),
- "date_to": ast.Constant(value=self.date_to),
- "filters": filters_expr(self.filters),
+ "series_scope": self._series_scope_expr(),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
@@ -702,9 +764,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp AS sample_timestamp,
- service_name AS service_name,
- attributes AS attributes,
- resource_attributes AS resource_attributes,
+ series_fingerprint AS series_fingerprint,
histogram_bounds AS histogram_bounds,
multiIf(
aggregation_temporality = 'delta', counts_f,
@@ -716,10 +776,8 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp,
- service_name,
+ series_fingerprint,
aggregation_temporality,
- attributes,
- resource_attributes,
histogram_bounds,
arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,
lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (
@@ -729,13 +787,12 @@ class MetricQueryRunner:
) AS prev_counts
FROM posthog.metrics
WHERE metric_name = {metric_name}
- AND timestamp >= {scan_from}
- AND timestamp < {date_to}
+ AND {scan_range}
AND notEmpty(histogram_counts)
- AND {filters}
+ AND {series_scope}
AND {type_filter}
)
- )
+ ) AS s
WHERE sample_timestamp >= {date_from}
GROUP BY time
ORDER BY time ASC
@@ -743,12 +800,11 @@ class MetricQueryRunner:
""",
placeholders={
"interval": _interval_expr(self.interval),
- "series_key": ast.Tuple(exprs=_series_key_exprs()),
+ "series_key": _series_key_expr(),
"metric_name": ast.Constant(value=self.metric_name),
- "scan_from": ast.Constant(value=self.date_from - counter_lookback(self.interval)),
+ "scan_range": time_range_expr(self.date_from - counter_lookback(self.interval), self.date_to),
"date_from": ast.Constant(value=self.date_from),
- "date_to": ast.Constant(value=self.date_to),
- "filters": filters_expr(self.filters),
+ "series_scope": self._series_scope_expr(),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.py
index 8baa91310f4b..4e5c76a0948e 100644
--- a/products/metrics/backend/tests/_seeder.py
+++ b/products/metrics/backend/tests/_seeder.py
@@ -1,11 +1,15 @@
-"""Test-only metric row seeder for `metrics1`.
+"""Test-only metric row seeder for the metrics2 chain.
-Inserts rows directly via `sync_execute` rather than driving the OTLP pipe,
-so tests don't depend on capture-logs + metrics-ingestion-consumer running.
+Inserts rows into `metrics2_input` via `sync_execute` rather than driving the
+OTLP pipe, so tests don't depend on capture-logs + metrics-ingestion-consumer
+running. `metrics2_input` is the Null-engine table the Kafka MV writes to, so one
+insert fans out through the same MVs production uses: `metrics2` (data points),
+`metric_series2` (labels, one row per series) and `metric_attributes2` (the
+attribute rollups).
The shape mirrors what `rust/capture-logs/src/metric_record.rs` emits — every
-later query-runner PR (filters, group-by, rate, histogram_quantile) leans on
-this to plant deterministic fixtures with specific labels and timestamps.
+query-runner test (filters, group-by, rate, histogram_quantile) leans on this
+to plant deterministic fixtures with specific labels and timestamps.
"""
from __future__ import annotations
@@ -19,69 +23,48 @@ from typing import Any
from posthog.clickhouse.client import sync_execute
+# `metrics2` and `metric_series2` hardcode `TTL original_expiry_timestamp`
+# instead of going through `ttl_period()`, so the seeder has to keep its rows
+# alive itself. A far-future expiry pins that independent of the wall clock.
+_EXPIRY = dt.datetime(2200, 1, 1, tzinfo=dt.UTC)
-def _series_fingerprint(
- metric_name: str, service_name: str, resource_attributes: Mapping[str, str], attributes: Mapping[str, str]
-) -> int:
- """A deterministic UInt64 fingerprint for the (metric, label-set) tuple.
- The seeder owns both the series and its samples, so this only has to be
- stable per label-set (distinct sets -> distinct fingerprints) — it does NOT
- have to equal ClickHouse's `cityHash64`, which the real ingest MV computes.
- """
- key = repr((metric_name, service_name, sorted(resource_attributes.items()), sorted(attributes.items())))
+def _fingerprint(*parts: Any) -> int:
+ key = repr(parts)
return int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8).digest(), "big")
-def _attribute_map_str_with_type_tags(labels: Mapping[str, str]) -> dict[str, str]:
- """`attributes_map_str` stores keys with a trailing 5-char type tag (e.g.
- `container__str`), matching the Kafka MV's `concat(k, '__str')`. The
- ClickHouse table exposes a stripped ALIAS column `attributes` via
- `left(k, -5)`. The seeder accepts user-friendly names (`container`) and
- appends the `__str` tag so lookups via the ALIAS work as expected.
+def _series_fingerprint(
+ metric_name: str,
+ metric_type: str,
+ service_name: str,
+ resource_attributes: Mapping[str, str],
+ attributes: Mapping[str, str],
+) -> int:
+ """A deterministic UInt64 fingerprint for the (metric, type, label-set) tuple.
+
+ Same inputs as `compute_series_fingerprint` in capture-logs, so two seeded
+ series collide exactly when the real ingest would merge them. Ingest
+ fingerprints before it stamps the synthetic `$originalTimestamp` attribute
+ on a skewed point, so that key is left out here too. It does NOT have to
+ equal the Rust hash: the seeder owns both the series and its samples, so it
+ only has to be stable per label-set.
"""
- return {f"{key}__str": value for key, value in labels.items()}
+ identity_attributes = sorted((k, v) for k, v in attributes.items() if k != "$originalTimestamp")
+ return _fingerprint(
+ metric_name, metric_type, service_name, sorted(resource_attributes.items()), identity_attributes
+ )
def truncate_metrics_tables() -> None:
- """Clear every table the seeders write, so leftovers can't leak between tests."""
- for table in ("metrics1", "metric_series1", "metric_samples1"):
+ """Clear every table the seeder's inserts fan out into, so leftovers can't
+ leak between tests."""
+ for table in ("metrics2", "metric_series2", "metric_attributes2"):
sync_execute(f"TRUNCATE TABLE IF EXISTS {table}")
-def _insert_series_row(
- *,
- team_id: int,
- metric_name: str,
- fingerprint: int,
- metric_type: str,
- unit: str,
- aggregation_temporality: str,
- is_monotonic: bool,
- service_name: str,
- resource_attributes: Mapping[str, str],
- attributes: Mapping[str, str],
- last_seen: dt.datetime,
-) -> None:
- """Insert the `metric_series1` row for one (metric, label-set).
-
- `attributes` goes in untagged — the `__str` suffixes are a `metrics1`
- storage detail, and the ingest MV writes the series map without them.
- """
- series_row = {
- "team_id": team_id,
- "metric_name": metric_name,
- "series_fingerprint": fingerprint,
- "metric_type": metric_type,
- "unit": unit,
- "aggregation_temporality": aggregation_temporality,
- "is_monotonic": is_monotonic,
- "service_name": service_name,
- "resource_attributes": dict(resource_attributes),
- "attributes": dict(attributes),
- "last_seen": last_seen.strftime("%Y-%m-%d %H:%M:%S.%f"),
- }
- sync_execute("INSERT INTO metric_series1 FORMAT JSONEachRow " + json.dumps(series_row))
+def _format_timestamp(timestamp: dt.datetime) -> str:
+ return timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")
def seed_metric(
@@ -98,13 +81,13 @@ def seed_metric(
histogram_bounds: list[float] | None = None,
histogram_counts: list[int] | None = None,
unit: str = "",
+ trace_id: str = "",
+ span_id: str = "",
+ count: int = 1,
) -> None:
- """Insert one row per `(timestamp, value)` point into `metrics1`, plus the
- matching `metric_series1` row.
-
- Production fans one Kafka row into both tables, so the seeder does too —
- anything reading `metric_series` (the name picker) sees what the raw table
- sees.
+ """Insert one `metrics2_input` row per `(timestamp, value)` point; the
+ ingest MVs write the `metrics2` rows, the `metric_series2` row and the
+ `metric_attributes2` rollups from it.
Every point in one call is a sample of the *same* series, since the series
identity (`service_name`, `metric_type`, both attribute maps) is fixed per
@@ -112,17 +95,20 @@ def seed_metric(
points in one bucket collapse to the last one. Seed distinct series with
separate calls.
- `labels` populates the per-data-point `attributes_map_str` map (with the
- `__str` type-tag suffix the schema expects). `resource_labels` populates
- `resource_attributes` directly — those are tag-free.
+ `labels` populates the per-data-point `attributes` map and `resource_labels`
+ populates `resource_attributes`.
Histogram inputs (`histogram_bounds`, `histogram_counts`) are passed
through verbatim; only relevant when `metric_type='histogram'`.
"""
- labels = dict(labels or {})
- attributes_map_str = _attribute_map_str_with_type_tags(labels)
+ attributes = dict(labels or {})
resource_attributes = dict(resource_labels or {})
points = list(points)
+ if not points:
+ return
+
+ fingerprint = _series_fingerprint(metric_name, metric_type, service_name, resource_attributes, attributes)
+ resource_fingerprint = _fingerprint(sorted(resource_attributes.items()))
rows: list[dict[str, Any]] = []
for timestamp, value in points:
@@ -130,47 +116,33 @@ def seed_metric(
{
"uuid": str(uuid.uuid4()),
"team_id": team_id,
- "trace_id": "",
- "span_id": "",
- "trace_flags": 0,
- "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
- "observed_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
- "service_name": service_name,
"metric_name": metric_name,
+ "series_fingerprint": fingerprint,
+ "resource_fingerprint": resource_fingerprint,
+ "timestamp": _format_timestamp(timestamp),
+ "observed_timestamp": _format_timestamp(timestamp),
+ "original_expiry_timestamp": _format_timestamp(_EXPIRY),
+ "service_name": service_name,
"metric_type": metric_type,
"value": value,
- "count": 1,
+ "count": count,
"histogram_bounds": histogram_bounds or [],
"histogram_counts": histogram_counts or [],
+ "trace_id": trace_id,
+ "span_id": span_id,
+ "trace_flags": 0,
+ "has_labels": True,
"unit": unit,
"aggregation_temporality": aggregation_temporality,
"is_monotonic": is_monotonic,
- "resource_attributes": resource_attributes,
"instrumentation_scope": "",
- "attributes_map_str": attributes_map_str,
- "attributes_map_float": {},
+ "resource_attributes": resource_attributes,
+ "attributes": attributes,
}
)
- if not rows:
- return
-
payload = "\n".join(json.dumps(row) for row in rows)
- sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {payload}")
-
- _insert_series_row(
- team_id=team_id,
- metric_name=metric_name,
- fingerprint=_series_fingerprint(metric_name, service_name, resource_attributes, labels),
- metric_type=metric_type,
- unit=unit,
- aggregation_temporality=aggregation_temporality,
- is_monotonic=is_monotonic,
- service_name=service_name,
- resource_attributes=resource_attributes,
- attributes=labels,
- last_seen=max(ts for ts, _ in points),
- )
+ sync_execute(f"INSERT INTO metrics2_input FORMAT JSONEachRow {payload}")
def seed_metric_event(
@@ -191,48 +163,23 @@ def seed_metric_event(
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.
-
- All points here share one label-set, so they share one `series_fingerprint`
- and one series row that the samples reference.
- """
- attributes = dict(attributes or {})
- resource_attributes = dict(resource_attributes or {})
- points = list(points)
- if not points:
- return
-
- fingerprint = _series_fingerprint(metric_name, service_name, resource_attributes, attributes)
-
- sample_rows: list[dict[str, Any]] = [
- {
- "team_id": team_id,
- "metric_name": metric_name,
- "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,
- }
- for timestamp, value in points
- ]
- sync_execute("INSERT INTO metric_samples1 FORMAT JSONEachRow " + "\n".join(json.dumps(r) for r in sample_rows))
-
- _insert_series_row(
+ """`seed_metric` under the sample-oriented names the Samples tests use:
+ `attributes` / `resource_attributes` instead of `labels` / `resource_labels`,
+ and a `sum` default type."""
+ seed_metric(
team_id=team_id,
metric_name=metric_name,
- fingerprint=fingerprint,
+ points=points,
+ labels=attributes,
+ resource_labels=resource_attributes,
metric_type=metric_type,
- unit=unit,
+ service_name=service_name,
aggregation_temporality=aggregation_temporality,
is_monotonic=is_monotonic,
- service_name=service_name,
- resource_attributes=resource_attributes,
- attributes=attributes,
- last_seen=max(ts for ts, _ in points),
+ histogram_bounds=histogram_bounds,
+ histogram_counts=histogram_counts,
+ unit=unit,
+ trace_id=trace_id,
+ span_id=span_id,
+ count=count,
)
diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.py
index 6d4dd5288662..ef917d928465 100644
--- a/products/metrics/backend/tests/test_diagnostics.py
+++ b/products/metrics/backend/tests/test_diagnostics.py
@@ -4,12 +4,10 @@ import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
-from posthog.clickhouse.client import sync_execute
-
from products.metrics.backend import diagnostics
from products.metrics.backend.diagnostics import decompose_bucket
from products.metrics.backend.fundamentals import SpatialReducer, TemporalReducer
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
BUCKET = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)
@@ -21,7 +19,7 @@ class TestBucketDecomposition(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def _seed_gauge_pair(self) -> None:
# Two pods reporting the same gauge, three scrapes each inside one bucket.
@@ -206,7 +204,7 @@ class TestBucketDecomposition(ClickhouseTestMixin, APIBaseTest):
class TestExplainEndpoint(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def test_explain_returns_the_series_behind_a_point(self) -> None:
seed_metric(
@@ -258,7 +256,7 @@ class TestExplainEndpoint(ClickhouseTestMixin, APIBaseTest):
class TestCounterBoundary(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
# The predecessor sample sits in the previous bucket; the chart's window
# function diffs across that edge, so the check has to as well.
seed_metric(
@@ -336,7 +334,7 @@ class TestCounterBoundary(ClickhouseTestMixin, APIBaseTest):
class TestTruncatedBucket(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def test_truncated_read_reports_not_comparable_instead_of_a_verdict(self) -> None:
seed_metric(
diff --git a/products/metrics/backend/tests/test_has_metrics_query_runner.py b/products/metrics/backend/tests/test_has_metrics_query_runner.py
index 708711f62c4a..c9010a21d140 100644
--- a/products/metrics/backend/tests/test_has_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_has_metrics_query_runner.py
@@ -1,4 +1,4 @@
-import json
+import datetime as dt
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -7,42 +7,16 @@ from django.core.cache import cache
from rest_framework import status
-from posthog.clickhouse.client import sync_execute
-
from products.metrics.backend.has_metrics_query_runner import HasMetricsQueryRunner
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
def _insert_metric_row(*, team_id: int) -> None:
- """Insert a minimal row into the local `metrics1` storage table.
-
- `metrics` is a Distributed proxy over `metrics1`; INSERTs forward
- through Distributed but TRUNCATEs must hit the local table directly
- (Distributed doesn't support TRUNCATE).
- """
- row = {
- "uuid": "019e6bc4-4897-77d0-ab21-56ba3e2fe535",
- "team_id": team_id,
- "trace_id": "",
- "span_id": "",
- "trace_flags": 0,
- "timestamp": "2026-05-27 00:00:00.000000",
- "observed_timestamp": "2026-05-27 00:00:00.000000",
- "service_name": "test-service",
- "metric_name": "test.metric",
- "metric_type": "gauge",
- "value": 1.0,
- "count": 1,
- "histogram_bounds": [],
- "histogram_counts": [],
- "unit": "",
- "aggregation_temporality": "cumulative",
- "is_monotonic": False,
- "resource_attributes": {},
- "instrumentation_scope": "",
- "attributes_map_str": {},
- "attributes_map_float": {},
- }
- sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {json.dumps(row)}")
+ seed_metric(
+ team_id=team_id,
+ metric_name="test.metric",
+ points=[(dt.datetime(2026, 5, 27, tzinfo=dt.UTC), 1.0)],
+ )
class TestHasMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
@@ -53,14 +27,14 @@ class TestHasMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
cache.delete(f"team:{self.team.id}:has_metrics")
def test_has_metrics_returns_false_when_no_metrics(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
cache.delete(f"team:{self.team.id}:has_metrics")
runner = HasMetricsQueryRunner(self.team)
self.assertFalse(runner.run())
def test_has_metrics_returns_true_when_metrics_exist(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
cache.delete(f"team:{self.team.id}:has_metrics")
_insert_metric_row(team_id=self.team.id)
@@ -68,7 +42,7 @@ class TestHasMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(runner.run())
def test_has_metrics_respects_team_isolation(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
cache.delete(f"team:{self.team.id}:has_metrics")
# Row belongs to a different team — the HogQL team_id auto-filter
# should make our team's runner return False.
@@ -86,7 +60,7 @@ class TestHasMetricsAPI(ClickhouseTestMixin, APIBaseTest):
cache.delete(f"team:{self.team.id}:has_metrics")
def test_has_metrics_api_returns_false_when_no_metrics(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
cache.delete(f"team:{self.team.id}:has_metrics")
response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics")
diff --git a/products/metrics/backend/tests/test_investigation.py b/products/metrics/backend/tests/test_investigation.py
index 974572a00a16..72a9cf9aba4d 100644
--- a/products/metrics/backend/tests/test_investigation.py
+++ b/products/metrics/backend/tests/test_investigation.py
@@ -6,11 +6,9 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from django.utils import timezone
-from posthog.clickhouse.client import sync_execute
-
from products.metrics.backend.facade.api import investigate, investigate_incident
from products.metrics.backend.facade.contracts import CompanionMetric, CompanionVerdict, IncidentContext
-from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event
+from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event, truncate_metrics_tables
def _trace_hex(i: int) -> str:
@@ -26,9 +24,7 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
- sync_execute("TRUNCATE TABLE IF EXISTS metric_samples1")
- sync_execute("TRUNCATE TABLE IF EXISTS metric_series1")
+ truncate_metrics_tables()
# 20-minute window: minutes 0-9 baseline, 10-19 anomaly (spike from 12).
self.start = (timezone.now() - dt.timedelta(hours=1)).replace(second=0, microsecond=0)
self.anomaly_from = self.start + dt.timedelta(minutes=10)
@@ -88,7 +84,7 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(self._verdict(result, "throughput").moved_with_symptom)
self.assertTrue(self._verdict(result, "error_rate").moved_with_symptom)
- # No metric_samples rows exist -> the pivot stays empty rather than erroring.
+ # No metrics rows exist -> the pivot stays empty rather than erroring.
self.assertEqual(result.evidence.trace_exemplars, ())
self.assertEqual(result.confidence, "high")
diff --git a/products/metrics/backend/tests/test_metric_attributes.py b/products/metrics/backend/tests/test_metric_attributes.py
index ab88c3cf7390..5ffba4ac9d32 100644
--- a/products/metrics/backend/tests/test_metric_attributes.py
+++ b/products/metrics/backend/tests/test_metric_attributes.py
@@ -7,9 +7,7 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.clickhouse.client import sync_execute
-
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):
@@ -19,10 +17,7 @@ class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- # metric_attributes is fed by MVs on metrics1, so truncating metrics1
- # alone (as sibling test classes do) leaves attribute rows behind.
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
- sync_execute("TRUNCATE TABLE IF EXISTS metric_attributes")
+ truncate_metrics_tables()
cls.now = timezone.now().replace(second=0, microsecond=0)
recent = [(cls.now - dt.timedelta(minutes=m), 1.0) for m in (2, 3, 4)]
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 12dc2007cc94..4016d41c7043 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
@@ -15,7 +15,7 @@ from products.metrics.backend.facade.api import list_metric_event_samples
from products.metrics.backend.facade.contracts import MetricFilter
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricType
from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
-from products.metrics.backend.tests._seeder import seed_metric_event
+from products.metrics.backend.tests._seeder import seed_metric_event, truncate_metrics_tables
# Trace context is stored base64-encoded (as capture-logs writes it) but crosses the
# API boundary as hex, matching the tracing product's contract. hex() in ClickHouse
@@ -28,13 +28,26 @@ SPAN_A_HEX = "f068a584a45a5eda".upper()
SPAN_A_B64 = base64.b64encode(bytes.fromhex(SPAN_A_HEX)).decode()
+def _insert_orphan_sample(*, team_id: int, metric_name: str, timestamp: dt.datetime, value: float) -> None:
+ # Straight into `metrics2`, bypassing the ingest MVs, so no series row exists.
+ sync_execute(
+ "INSERT INTO metrics2 (team_id, metric_name, series_fingerprint, timestamp, original_expiry_timestamp, value) "
+ "VALUES (%(team_id)s, %(metric_name)s, 42, %(ts)s, '2200-01-01 00:00:00', %(value)s)",
+ {
+ "team_id": team_id,
+ "metric_name": metric_name,
+ "ts": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "value": value,
+ },
+ )
+
+
class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metric_samples1")
- sync_execute("TRUNCATE TABLE IF EXISTS metric_series1")
+ truncate_metrics_tables()
tag_queries(product=Product.METRICS, feature=Feature.QUERY)
@parameterized.expand(
@@ -224,16 +237,12 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(samples[0].span_id, "")
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.
+ # A data point whose series row never landed (its labelled record was
+ # dropped, or arrived with `has_labels` false only) must still render
+ # under its own metric name, with the labels empty — regression guard
+ # for reading anything but the two maps 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")},
- )
+ _insert_orphan_sample(team_id=self.team.id, metric_name="orphaned.metric", timestamp=anchor, value=7.0)
samples = list_metric_event_samples(
team=self.team,
@@ -246,7 +255,8 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
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
+ self.assertEqual(samples[0].metric_type, "") # column default
+ self.assertEqual(samples[0].attributes, {})
def test_samples_api_requires_authentication(self):
self.client.logout()
@@ -322,8 +332,7 @@ class TestMetricEventSampleFilters(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metric_samples1")
- sync_execute("TRUNCATE TABLE IF EXISTS metric_series1")
+ truncate_metrics_tables()
tag_queries(product=Product.METRICS, feature=Feature.QUERY)
self.anchor = timezone.now().replace(microsecond=0)
seed_metric_event(
@@ -378,10 +387,6 @@ class TestMetricEventSampleFilters(ClickhouseTestMixin, APIBaseTest):
]
)
def test_single_filter(self, _label, filter, expected_values):
- # The chart reads labels off `metrics1`, where `attributes` is an ALIAS that
- # strips the type tag; here they come off `metric_series`, where the map is
- # real and `service_name` is its own column. Same filter expressions, two
- # storage shapes, so both need covering.
self.assertEqual(self._values((filter,)), expected_values)
def test_filter_applies_before_the_limit(self):
@@ -402,11 +407,7 @@ class TestMetricEventSampleFilters(ClickhouseTestMixin, APIBaseTest):
# match, so it drops out of a filtered result. The predicate below matches
# both real series, which pins the exclusion on the missing series rather
# than on the filter itself.
- sync_execute(
- "INSERT INTO metric_samples1 (team_id, metric_name, series_fingerprint, timestamp, value) "
- "VALUES (%(team_id)s, 'req', 42, %(ts)s, 7.0)",
- {"team_id": self.team.id, "ts": self.anchor.strftime("%Y-%m-%d %H:%M:%S.%f")},
- )
+ _insert_orphan_sample(team_id=self.team.id, metric_name="req", timestamp=self.anchor, value=7.0)
self.assertIn(7.0, self._values())
self.assertNotIn(7.0, self._values((MetricFilter(key="env", op=FilterOp.NEQ, value="absent"),)))
diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.py
index 4f834e2aaf6c..04b064b7c02c 100644
--- a/products/metrics/backend/tests/test_metric_names_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py
@@ -104,12 +104,9 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):
runner = MetricNamesQueryRunner(team=self.team, search=search)
self.assertEqual([row["name"] for row in runner.run()], expected)
- def test_reads_series_written_without_a_raw_datapoint_row(self):
- # seed_metric_event writes metric_series1 + metric_samples1 and no metrics1
- # row, so this is the one test that fails if the runner goes back to
- # aggregating posthog.metrics. Seeding twice lands two unmerged
- # ReplacingMergeTree parts for one fingerprint, which must still collapse
- # to a single picker row without FINAL.
+ def test_collapses_unmerged_series_parts_without_final(self):
+ # Seeding twice lands two unmerged ReplacingMergeTree parts for one
+ # fingerprint, which must still collapse to a single picker row.
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)
for offset in (10, 1):
seed_metric_event(
@@ -300,8 +297,7 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):
class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
"""The catalog is the picker row plus what makes a card scannable: the unit,
when the metric was last heard from, and a small sparkline of its recent
- shape. Sparkline points come from `metric_samples`, so a series written
- without a pre-aggregated `metrics` row still draws."""
+ shape. Sparkline points come from the raw `metrics` data points."""
CLASS_DATA_LEVEL_SETUP = True
@@ -332,8 +328,6 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
# A clear rise across the window: any faithful downsampling keeps the
# last value above the first.
points = [(anchor + dt.timedelta(minutes=i), float(i)) for i in range(30)]
- # Sparklines read metric_samples, so seed through the raw-sample path
- # (seed_metric writes only the pre-aggregated metrics row).
seed_metric_event(team_id=self.team.id, metric_name="queue.depth", points=points, metric_type="gauge")
runner = MetricNamesQueryRunner(team=self.team)
@@ -346,7 +340,6 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_sparkline_is_bounded(self):
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=120)
points = [(anchor + dt.timedelta(minutes=i), float(i % 7)) for i in range(120)]
- # Sparklines read metric_samples, so seed through the raw-sample path.
seed_metric_event(team_id=self.team.id, metric_name="busy.metric", points=points, metric_type="gauge")
runner = MetricNamesQueryRunner(team=self.team)
@@ -356,9 +349,7 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertGreater(len(row["sparkline"]), 1)
self.assertLessEqual(len(row["sparkline"]), 24)
- def test_sparkline_reads_samples_without_a_preaggregated_row(self):
- # seed_metric_event writes metric_series + metric_samples and no metrics
- # row, so this fails if the sparkline goes back to aggregating posthog.metrics.
+ def test_sparkline_draws_from_a_short_recent_run(self):
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)
points = [(anchor + dt.timedelta(minutes=i), float(i)) for i in range(10)]
seed_metric_event(team_id=self.team.id, metric_name="samples.only", points=points, metric_type="gauge")
@@ -388,7 +379,6 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_sparkline_scoped_to_services(self):
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)
for service, metric_name in (("web", "http.duration"), ("worker", "jobs.processed")):
- # Sparklines read metric_samples, so seed through the raw-sample path.
seed_metric_event(
team_id=self.team.id,
metric_name=metric_name,
@@ -406,7 +396,6 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):
# web and worker emit the same metric name. A card scoped to web must
# draw only web's series; an unscoped card averages both.
anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)
- # Sparklines read metric_samples, so seed through the raw-sample path.
seed_metric_event(
team_id=self.team.id,
metric_name="shared.metric",
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index ce25b731d36a..eb50fd8208b7 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -30,7 +30,7 @@ from products.metrics.backend.metric_query_runner import (
_pick_interval,
attribute_field,
)
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
class TestPickInterval:
@@ -90,7 +90,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def test_rejects_unsupported_aggregation(self):
with self.assertRaises(ValueError):
@@ -358,7 +358,7 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def test_query_requires_authentication(self):
self.client.logout()
@@ -442,20 +442,20 @@ class TestAttributeField(ClickhouseTestMixin, APIBaseTest):
"""End-to-end tests for the `attribute_field` helper.
The helper builds an AST node; correctness depends on what ClickHouse
- actually returns, so we execute a real query against `posthog.metrics`
- for each scope and assert the resolved value.
+ actually returns, so we execute a real query against `posthog.metric_series`
+ (where the label maps live) for each scope and assert the resolved value.
"""
CLASS_DATA_LEVEL_SETUP = True
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def _select_attribute(self, expr: ast.Expr, metric_name: str) -> str | None:
query = parse_select(
"""
- SELECT {expr} AS value FROM posthog.metrics
+ SELECT {expr} AS value FROM posthog.metric_series
WHERE metric_name = {metric_name} LIMIT 1
""",
placeholders={"expr": expr, "metric_name": ast.Constant(value=metric_name)},
@@ -557,7 +557,7 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
def _request(self, **overrides):
anchor = timezone.now().replace(microsecond=0)
@@ -632,7 +632,7 @@ class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = timezone.now().replace(microsecond=0)
seed_metric(
team_id=self.team.id,
@@ -749,7 +749,7 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = timezone.now().replace(microsecond=0, second=0)
# env=prod has points in two buckets, env=dev only in the second —
# exercises the shared-grid zero-fill.
@@ -813,7 +813,7 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):
self._run(interval="fortnight")
def test_group_by_resource_scope(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
seed_metric(
team_id=self.team.id,
metric_name="req",
@@ -863,7 +863,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
# Anchor on a minute boundary so bucket membership is deterministic.
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
@@ -1119,7 +1119,7 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
def _seed_histogram(self, points_with_counts, temporality="cumulative", bounds=None, **kwargs):
@@ -1322,7 +1322,7 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
# errors: 2 then 4; requests: 10 then 20 (per-minute buckets)
seed_metric(
@@ -1368,7 +1368,7 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([p.value for p in series[0].points], [0.2, 0.2])
def test_formula_matches_grouped_series_by_label_set(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
for env, errors, requests in [("prod", 1.0, 10.0), ("dev", 3.0, 6.0)]:
seed_metric(
team_id=self.team.id,
@@ -1401,7 +1401,7 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(by_env, {"prod": [0.1], "dev": [0.5]})
def test_formula_broadcasts_ungrouped_clause(self):
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
for env, errors in [("prod", 2.0), ("dev", 6.0)]:
seed_metric(
team_id=self.team.id,
@@ -1481,7 +1481,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
# The same name recorded as a delta counter (5) and as a gauge (42).
seed_metric(
@@ -1576,7 +1576,7 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ truncate_metrics_tables()
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
def _seed_huge(self, count: int) -> None: