:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): read metrics4_samples directly after the metrics4 cut-over (#109134)
Frank Hamand73f89414efeb
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 57bd8171db81..ab14ce84a4c0 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -118,6 +118,8 @@ from posthog.hogql.database.schema.marketing_costs_precomputed import MarketingCfrom posthog.hogql.database.schema.marketing_touchpoints_preaggregated import MarketingTouchpointsPreaggregatedTablefrom posthog.hogql.database.schema.metrics import (MetricAttributesTable,+ MetricNamesTable,+ MetricSamplesTable,MetricSeriesTable,MetricsKafkaMetricsTable,MetricsTable,@@ -564,6 +566,8 @@ 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_names": TableNode(name="metric_names", table=MetricNamesTable()),"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/models.py b/posthog/hogql/database/models.pyindex 9079821ada98..aa4ca85ebbaa 100644--- a/posthog/hogql/database/models.py+++ b/posthog/hogql/database/models.py@@ -166,6 +166,26 @@ class FloatArrayDatabaseField(DatabaseField):return ""+class IntegerArrayDatabaseField(DatabaseField):+ def get_constant_type(self) -> "ConstantType":+ from posthog.hogql.ast import ArrayType, IntegerType++ return ArrayType(nullable=self.is_nullable(), item_type=IntegerType(nullable=False))++ def default_value(self) -> Any:+ return ""+++class DateTimeArrayDatabaseField(DatabaseField):+ def get_constant_type(self) -> "ConstantType":+ from posthog.hogql.ast import ArrayType, DateTimeType++ return ArrayType(nullable=self.is_nullable(), item_type=DateTimeType(nullable=False))++ def default_value(self) -> Any:+ return ""++class DateDatabaseField(DatabaseField):def get_constant_type(self) -> "ConstantType":from posthog.hogql.ast import DateTypediff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pyindex 89a2fd3dd1fd..509a1e49caf3 100644--- a/posthog/hogql/database/schema/metrics.py+++ b/posthog/hogql/database/schema/metrics.py@@ -1,14 +1,19 @@from posthog.hogql.database.models import (BooleanDatabaseField,DANGEROUS_NoTeamIdCheckTable,+ DateTimeArrayDatabaseField,DateTimeDatabaseField,FieldOrTable,+ FloatArrayDatabaseField,FloatDatabaseField,+ IntegerArrayDatabaseField,IntegerDatabaseField,MapStringDatabaseField,+ StringArrayDatabaseField,StringDatabaseField,StringJSONDatabaseField,Table,+ UnknownDatabaseField,)from posthog.clickhouse.workload import Workload@@ -106,6 +111,128 @@ class MetricsTable(Table):return "metrics"+class MetricSamplesTable(Table):+ description: str = "OpenTelemetry metric data points grouped by series and UTC hour. Each row holds the points of one series-hour in parallel arrays, so the same array index identifies one point. Use `ARRAY JOIN` to read one row per point. One series-hour can have more than one row until ClickHouse merges them. Join `metric_series` on `series_fingerprint` for labels."+ 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, description="Name of the metric."),+ "time_bucket": DateTimeDatabaseField(+ name="time_bucket", nullable=False, description="Start of the UTC hour of all points in the row."+ ),+ "series_fingerprint": IntegerDatabaseField(+ name="series_fingerprint",+ nullable=False,+ description="Hash of the series' label set, assigned at ingest; join key to `metric_series`.",+ ),+ "resource_fingerprint": IntegerDatabaseField(+ name="resource_fingerprint",+ nullable=False,+ description="Hash of the resource attributes, used to group resources.",+ ),+ "service_name": StringDatabaseField(+ name="service_name", nullable=False, description="Name of the service that emitted the metric."+ ),+ "metric_type": StringDatabaseField(+ name="metric_type",+ nullable=False,+ description="OpenTelemetry metric type, e.g. 'gauge', 'sum', 'histogram'.",+ ),+ "unit": StringDatabaseField(+ name="unit", nullable=False, description="Unit of the metric value, e.g. 'ms', 'By'."+ ),+ "aggregation_temporality": StringDatabaseField(+ name="aggregation_temporality",+ nullable=False,+ description="OpenTelemetry temporality, e.g. 'delta' or 'cumulative'.",+ ),+ "is_monotonic": BooleanDatabaseField(+ name="is_monotonic", nullable=False, description="True if the sum metric only increases."+ ),+ "has_labels": BooleanDatabaseField(+ name="has_labels",+ nullable=False,+ description="True when an ingested record of the row carried the series labels.",+ ),+ "instrumentation_scope": StringDatabaseField(+ name="instrumentation_scope",+ nullable=False,+ description="Instrumentation scope (library/module) that emitted the metric.",+ ),+ "histogram_bounds": FloatArrayDatabaseField(+ name="histogram_bounds", nullable=False, description="Histogram bucket boundaries of the series."+ ),+ "timestamp_min": DateTimeDatabaseField(+ name="timestamp_min", nullable=False, description="Earliest point timestamp in the row."+ ),+ "timestamp_max": DateTimeDatabaseField(+ name="timestamp_max", nullable=False, description="Latest point timestamp in the row."+ ),+ "timestamp_arr": DateTimeArrayDatabaseField(+ name="timestamp_arr", nullable=False, description="When each data point was recorded."+ ),+ "observed_timestamp_arr": DateTimeArrayDatabaseField(+ name="observed_timestamp_arr",+ nullable=False,+ description="When the collector observed each data point.",+ ),+ "value_arr": FloatArrayDatabaseField(+ name="value_arr", nullable=False, description="Numeric value of each data point (for gauge/sum metrics)."+ ),+ "count_arr": IntegerArrayDatabaseField(+ name="count_arr",+ nullable=False,+ description="Total count of observations of each data point (for histogram metrics).",+ ),+ "histogram_counts_arr": UnknownDatabaseField(+ name="histogram_counts_arr",+ nullable=False,+ description="Per-bucket counts of each data point, aligned with `histogram_bounds`.",+ ),+ "trace_id_arr": StringArrayDatabaseField(+ name="trace_id_arr", nullable=False, description="Trace of each metric exemplar, if any."+ ),+ "span_id_arr": StringArrayDatabaseField(+ name="span_id_arr", nullable=False, description="Span of each metric exemplar, if any."+ ),+ "trace_flags_arr": IntegerArrayDatabaseField(+ name="trace_flags_arr", nullable=False, description="Trace flags of each metric exemplar."+ ),+ }++ def to_printed_clickhouse(self, context):+ return "metrics4_samples"++ def to_printed_hogql(self):+ return "metric_samples"+++class MetricNamesTable(Table):+ description: str = "One row per metric name and UTC hour with labeled data points. Use it to find the metric names of a time range."+ 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, description="Name of the metric."),+ "time_bucket": DateTimeDatabaseField(+ name="time_bucket", nullable=False, description="UTC hour in which the metric had data points."+ ),+ "original_expiry_time_bucket": DateTimeDatabaseField(+ name="original_expiry_time_bucket", nullable=False, description="Hour in which the row leaves retention."+ ),+ "original_expiry_timestamp": DateTimeDatabaseField(+ name="original_expiry_timestamp", nullable=False, description="When the row leaves retention."+ ),+ }++ def to_printed_clickhouse(self, context):+ return "metrics4_names"++ def to_printed_hogql(self):+ return "metric_names"++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 `metrics` at query time."workload: Workload | None = Workload.LOGSdiff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.pyindex f5624181303d..5004fda738dc 100644--- a/products/metrics/backend/anomaly.py+++ b/products/metrics/backend/anomaly.py@@ -31,12 +31,9 @@ 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,- time_range_expr,-)+from products.metrics.backend.metric_query_runner import _INTERVAL_LADDER, _pick_interval, time_range_expr+from products.metrics.backend.metric_samples_query_runner import build_metric_query_runner+from products.metrics.backend.metrics4_samples import reads_metrics4_only, series_in_range_query# How many label keys to drill into and how many movers to report.MAX_CANDIDATE_KEYS = 4@@ -161,7 +158,7 @@ def characterize_anomaly(interval = _pick_combined_interval(baseline_from, anomaly_from, anomaly_to)def _run(group_by: tuple[MetricGroupBy, ...] = ()) -> list[dict[str, Any]]:- return MetricQueryRunner(+ return build_metric_query_runner(team=team,metric_name=metric_name,aggregation=aggregation,@@ -228,6 +225,25 @@ def characterize_anomaly()+def _series_in_range(metric_name: str, date_from: dt.datetime, date_to: dt.datetime) -> ast.SelectQuery:+ if reads_metrics4_only(date_from):+ return series_in_range_query(metric_name, date_from, date_to)+ query = parse_select(+ """+ SELECT DISTINCT series_fingerprint+ FROM posthog.metrics+ WHERE metric_name = {metric_name}+ AND {time_range}+ """,+ placeholders={+ "metric_name": ast.Constant(value=metric_name),+ "time_range": time_range_expr(date_from, date_to),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query++def _discover_candidate_keys(team: Team, metric_name: str, date_from: dt.datetime, date_to: dt.datetime) -> tuple[str, ...]:@@ -248,12 +264,7 @@ def _discover_candidate_keys(SELECT any(attributes) AS attributes, any(resource_attributes) AS resource_attributesFROM posthog.metric_seriesWHERE metric_name = {metric_name}- AND series_fingerprint IN (- SELECT DISTINCT series_fingerprint- FROM posthog.metrics- WHERE metric_name = {metric_name}- AND {time_range}- )+ AND series_fingerprint IN {series_in_range}GROUP BY series_fingerprint))@@ -263,7 +274,7 @@ def _discover_candidate_keys(""",placeholders={"metric_name": ast.Constant(value=metric_name),- "time_range": time_range_expr(date_from, date_to),+ "series_in_range": _series_in_range(metric_name, date_from, date_to),"limit": ast.Constant(value=MAX_CANDIDATE_KEYS),},)diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.pyindex ff3a16c44d72..0ee3419a0c49 100644--- a/products/metrics/backend/diagnostics.py+++ b/products/metrics/backend/diagnostics.py@@ -38,14 +38,15 @@ from products.metrics.backend.facade.contracts import (from products.metrics.backend.fundamentals import Sample, TemporalReducer, apply_plan, plan_reduction, reduce_temporalfrom products.metrics.backend.metric_query_runner import (_QUERY_SETTINGS,- MetricQueryRunner,_interval_step,counter_lookback,+ points_query,series_labels_query,series_scope_expr,- time_range_expr,type_filter_expr,)+from products.metrics.backend.metric_samples_query_runner import build_metric_query_runner+from products.metrics.backend.metrics4_samples import reads_metrics4_only# How much of a bucket the breakdown lists. Totals are computed over everything# in the bucket; these only bound what gets rendered, and the decomposition says@@ -71,6 +72,7 @@ def _raw_samples_query(bucket_end: dt.datetime,filters: Sequence[MetricFilter],metric_type: str | None,+ timezone: str,) -> 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@@ -94,11 +96,7 @@ def _raw_samples_query(aggregation_temporality,timestamp,value- FROM posthog.metrics- WHERE metric_name = {metric_name}- AND {time_range}- AND {series_scope}- AND {type_filter}+ FROM {points}ORDER BY timestamp ASCLIMIT {row_limit}) AS s@@ -106,10 +104,22 @@ def _raw_samples_query(ORDER BY s.timestamp ASC""",placeholders={- "metric_name": ast.Constant(value=metric_name),- "time_range": time_range_expr(date_from, bucket_end),- "series_scope": series_scope_expr(metric_name, filters),- "type_filter": type_filter_expr(metric_type),+ "points": points_query(+ from_samples=reads_metrics4_only(date_from),+ columns=(+ "series_fingerprint",+ "service_name",+ "metric_type",+ "aggregation_temporality",+ "timestamp",+ "value",+ ),+ metric_names=(metric_name,),+ date_from=date_from,+ date_to=bucket_end,+ timezone=timezone,+ row_filters=(series_scope_expr(metric_name, filters), type_filter_expr(metric_type)),+ ),"row_limit": ast.Constant(value=_MAX_ROWS_READ),"series_labels": series_labels_query(metric_name),},@@ -136,7 +146,7 @@ def _actual_value(functions' predecessor sample, so this asks for exactly the one bucket thedecomposition is explaining."""- rows = MetricQueryRunner(+ rows = build_metric_query_runner(team=team,metric_name=metric_name,aggregation=aggregation,@@ -185,6 +195,7 @@ def decompose_bucket(bucket_end=bucket_end,filters=filters,metric_type=metric_type,+ timezone=team.timezone,),team=team,workload=Workload.LOGS,diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 2f843d805037..71dee707da8b 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -47,7 +47,7 @@ from products.metrics.backend.metric_attributes_query_runner import ()from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunnerfrom products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner, cached_metric_names-from products.metrics.backend.metric_query_runner import MetricQueryRunner+from products.metrics.backend.metric_samples_query_runner import build_metric_query_runnerfrom products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunner# MetricQueryRunner still speaks the legacy aggregation strings; this shrinks@@ -243,7 +243,7 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSrows_by_clause: dict[str, list[dict[str, Any]]] = {}for clause in request.clauses:runner_aggregation = _resolve_runner_aggregation(clause)- runner = MetricQueryRunner(+ runner = build_metric_query_runner(team=team,metric_name=clause.metric_name,aggregation=runner_aggregation,diff --git a/products/metrics/backend/has_metrics_query_runner.py b/products/metrics/backend/has_metrics_query_runner.pyindex b561c6aa1e66..af1a30eb229a 100644--- a/products/metrics/backend/has_metrics_query_runner.py+++ b/products/metrics/backend/has_metrics_query_runner.py@@ -10,6 +10,8 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.errors import CHQueryErrorUnknownTablefrom posthog.models import Team+from products.metrics.backend.metrics4_samples import METRICS_RETENTION, reads_metrics4_only+HAS_METRICS_CACHE_TTL = int(dt.timedelta(days=7).total_seconds())# Negative results are cached too, but only briefly. The activation check@@ -30,7 +32,11 @@ class HasMetricsQueryRunner:# `metrics` is only registered under the `posthog.` HogQL namespace# (posthog/hogql/database/database.py), so unlike `logs` it must be# referenced fully qualified.- query = parse_select("SELECT 1 FROM posthog.metrics LIMIT 1")+ # Before the `metrics2` data leaves retention, only the `metrics` view reads all of it.+ if reads_metrics4_only(dt.datetime.now(dt.UTC) - METRICS_RETENTION):+ query = parse_select("SELECT 1 FROM posthog.metric_samples LIMIT 1")+ else:+ query = parse_select("SELECT 1 FROM posthog.metrics LIMIT 1")assert isinstance(query, ast.SelectQuery)try:diff --git a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.pyindex 1c6a2456f5a8..6ac021564b7e 100644--- a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py@@ -31,12 +31,8 @@ from posthog.shared_link_user import SharedLinkUserfrom products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlErrorfrom products.metrics.backend.facade.contracts import METRICS_FEATURE_FLAG, MetricFilterfrom products.metrics.backend.facade.enums import AttributeScope, FilterOp-from products.metrics.backend.metric_query_runner import (- _INTERVAL_LADDER,- _QUERY_SETTINGS,- MetricQueryRunner,- _interval_step,-)+from products.metrics.backend.metric_query_runner import _INTERVAL_LADDER, _QUERY_SETTINGS, _interval_step+from products.metrics.backend.metric_samples_query_runner import build_metric_query_runnerif TYPE_CHECKING:from posthog.models import User@@ -128,7 +124,7 @@ class MetricsHistogramQueryRunner(AnalyticsQueryRunner[MetricsHistogramQueryResp)try:- runner = MetricQueryRunner(+ runner = build_metric_query_runner(team=self.team,metric_name=self.query.metricName,aggregation="histogram_quantile",diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.pyindex 24e5c4de0362..bd7cbd249b4b 100644--- a/products/metrics/backend/metric_event_samples_query_runner.py+++ b/products/metrics/backend/metric_event_samples_query_runner.py@@ -13,7 +13,7 @@ from typing import Anyfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workload@@ -21,7 +21,8 @@ from posthog.models import Teamfrom products.metrics.backend.facade.contracts import MetricFilterfrom products.metrics.backend.facade.enums import MetricType-from products.metrics.backend.metric_query_runner import series_scope_expr, time_range_expr, type_filter_expr+from products.metrics.backend.metric_query_runner import points_query, series_scope_expr, type_filter_expr+from products.metrics.backend.metrics4_samples import reads_metrics4_only# This query uses the shared ClickHouse cluster. Limit reads and fail on overflow._QUERY_SETTINGS = HogQLGlobalSettings(@@ -81,8 +82,48 @@ class MetricEventSamplesQueryRunner:self.metric_type = metric_typeself.limit = limit+ def _points_query(self) -> ast.SelectQuery:+ point_filters: list[ast.Expr] = []+ samples_row_filters: list[ast.Expr] = []+ if self.trace_id:+ trace_id = ast.Constant(value=self.trace_id)+ point_filters.append(parse_expr("trace_id = {trace_id}", placeholders={"trace_id": trace_id}))+ # `has()` on the array uses the `idx_trace_id_bf` bloom filter to skip granules.+ samples_row_filters.append(parse_expr("has(trace_id_arr, {trace_id})", placeholders={"trace_id": trace_id}))+ if self.span_id:+ point_filters.append(+ parse_expr("span_id = {span_id}", placeholders={"span_id": ast.Constant(value=self.span_id)})+ )+ return points_query(+ from_samples=reads_metrics4_only(self.date_from),+ columns=(+ "team_id",+ "metric_name",+ "series_fingerprint",+ "timestamp",+ "value",+ "count",+ "trace_id",+ "span_id",+ "metric_type",+ "unit",+ "aggregation_temporality",+ "is_monotonic",+ "service_name",+ ),+ metric_names=(self.metric_name,) if self.metric_name else None,+ date_from=self.date_from,+ date_to=self.date_to,+ timezone=self.team.timezone,+ row_filters=(+ type_filter_expr(self.metric_type.value if self.metric_type else None),+ series_scope_expr(self.metric_name, self.filters, self.date_from),+ ),+ point_filters=point_filters,+ samples_row_filters=samples_row_filters,+ )+def run(self) -> list[dict[str, Any]]:- # An empty `trace_id` matches every row, so the query needs no optional clause.# Filter and limit samples in the CTE. Join labels after that selection.# Apply label filters before LIMIT. Otherwise, filtered results can look empty.# Read labels only for matched samples. Trace queries must not read every series.@@ -103,13 +144,7 @@ class MetricEventSamplesQueryRunner:aggregation_temporality,is_monotonic,service_name- FROM posthog.metrics- WHERE ({metric_name} = '' OR metric_name = {metric_name})- 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}+ FROM {points}ORDER BY timestamp DESCLIMIT {limit})@@ -146,15 +181,7 @@ class MetricEventSamplesQueryRunner:AND s.series_fingerprint = ser.series_fingerprintORDER BY s.timestamp DESC""",- placeholders={- "metric_name": ast.Constant(value=self.metric_name),- "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),- "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, self.date_from),- "limit": ast.Constant(value=self.limit),- },+ placeholders={"points": self._points_query(), "limit": ast.Constant(value=self.limit)},)assert isinstance(query, ast.SelectQuery)diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.pyindex d7b960cf0e84..8b09afe7b855 100644--- a/products/metrics/backend/metric_names_query_runner.py+++ b/products/metrics/backend/metric_names_query_runner.py@@ -36,6 +36,8 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.models import Teamfrom products.metrics.backend.facade.contracts import MAX_SPARKLINE_BATCH_SIZE+from products.metrics.backend.metric_query_runner import points_query+from products.metrics.backend.metrics4_samples import reads_metrics4_onlyfrom products.metrics.backend.search import ilike_pattern# Autocomplete tolerates partial results, so reads break at the budget instead@@ -175,6 +177,20 @@ class MetricNamesQueryRunner:])+ # `metric_names` has one row per name and hour, sorted by hour, so it finds+ # the recent names without a read of every series. It has no service column.+ if not self.services and reads_metrics4_only(dt.datetime.now(dt.UTC) - self.lookback):+ query.where = ast.And(+ exprs=[+ query.where,+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["metric_name"]),+ right=self._recent_names_subquery(),+ ),+ ]+ )+# Appended to the parsed tree rather than written into both SQL variants# above, so the scoped and unscoped pickers stay one query definition.# `service_name` is the only filterable column with its own skip index@@ -193,6 +209,20 @@ class MetricNamesQueryRunner:)return query+ def _recent_names_subquery(self) -> ast.SelectQuery:+ lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])+ subquery = parse_select(+ """+ SELECT metric_name+ FROM posthog.metric_names+ WHERE time_bucket >= toStartOfHour(now() - {lookback})+ GROUP BY metric_name+ """,+ placeholders={"lookback": lookback},+ )+ assert isinstance(subquery, ast.SelectQuery)+ return subquery+def run(self) -> list[dict[str, Any]]:response = execute_hogql_query(query_type="MetricNamesQuery",@@ -242,27 +272,34 @@ class MetricNamesQueryRunner:metric_name AS name,toDateTime(intDiv(toUnixTimestamp(timestamp) - toUnixTimestamp({window_start}), {bucket_seconds}) * {bucket_seconds} + toUnixTimestamp({window_start})) AS bucket_start,avg(value) AS bucket_value- FROM posthog.metrics- WHERE timestamp > {window_start}- AND time_bucket >= {bucket_from}- AND metric_name IN {names}- AND series_fingerprint IN {series_scope}+ FROM {points}GROUP BY name, bucket_startORDER BY name, bucket_start""",placeholders={"bucket_seconds": ast.Constant(value=bucket_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,- # two services emitting one metric name share a card and a scoped- # catalog draws a shape blended across services.- "series_scope": self._series_scope_subquery(names),+ # The point read also bounds `time_bucket` (the UTC hour), which+ # lets ClickHouse skip everything older than the window.+ "points": points_query(+ from_samples=reads_metrics4_only(window_start),+ columns=("metric_name", "timestamp", "value"),+ metric_names=names,+ date_from=window_start,+ date_to=window_start + SPARKLINE_WINDOW,+ timezone=self.team.timezone,+ # A sample carries no service column; its series_fingerprint is+ # the link back to the series row that does. Without this scope,+ # two services emitting one metric name share a card and a scoped+ # catalog draws a shape blended across services.+ row_filters=(+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["series_fingerprint"]),+ right=self._series_scope_subquery(names),+ ),+ ),+ ),},)assert isinstance(query, ast.SelectQuery)diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 108a04e157b2..4d38a04a209e 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -23,6 +23,7 @@ from posthog.models import Teamfrom products.metrics.backend.facade.contracts import MetricFilter, MetricGroupByfrom products.metrics.backend.facade.enums import FilterOp, MetricType+from products.metrics.backend.metrics4_samples import metric_name_expr, samples_points_queryAttributeScope = Literal["resource", "attribute", "auto"]@@ -117,6 +118,9 @@ _ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"})+# These aggregations also read the predecessor lookback before `date_from`.+_LOOKBACK_AGGREGATIONS: frozenset[str] = frozenset({"rate", "increase", "histogram_quantile"})+# Derive this from the contract enum to match ingestion values._ALLOWED_METRIC_TYPES: frozenset[str] = frozenset(t.value for t in MetricType)@@ -277,6 +281,46 @@ def _utc_hour(value: dt.datetime) -> dt.datetime:return value.astimezone(dt.UTC).replace(minute=0, second=0, microsecond=0)+def points_query(+ *,+ from_samples: bool,+ columns: Sequence[str],+ metric_names: Sequence[str] | None,+ date_from: dt.datetime,+ date_to: dt.datetime,+ timezone: str,+ row_filters: Sequence[ast.Expr] = (),+ point_filters: Sequence[ast.Expr] = (),+ samples_row_filters: Sequence[ast.Expr] = (),+) -> ast.SelectQuery:+ """Return one row per metric point in `[date_from, date_to)`.++ `from_samples` reads `metric_samples`. Use it only when the range starts at+ or after the metrics4 cut-over. Otherwise read the `metrics` view.+ `row_filters` can use only columns that are constant in a series-hour.+ `samples_row_filters` apply only to `metric_samples`, for example array lookups.+ """+ if from_samples:+ return samples_points_query(+ columns=columns,+ metric_names=metric_names,+ date_from=date_from,+ date_to=date_to,+ timezone=timezone,+ row_filters=[*row_filters, *samples_row_filters],+ point_filters=point_filters,+ )+ query = parse_select(+ "SELECT 1 FROM posthog.metrics WHERE {name_filter} AND {time_range}",+ placeholders={"name_filter": metric_name_expr(metric_names), "time_range": time_range_expr(date_from, date_to)},+ )+ assert isinstance(query, ast.SelectQuery) and query.where is not None+ query.select = [ast.Field(chain=[column]) for column in columns]+ if row_filters or point_filters:+ query.where = ast.And(exprs=[query.where, *row_filters, *point_filters])+ return query++def type_filter_expr(metric_type: str | None) -> ast.Expr:"""Limit rows to one metric type.@@ -383,6 +427,10 @@ def series_group_labels_query(class MetricQueryRunner:+ """Run the query on the `metrics` view, which also reads `metrics2` data before the cut-over."""++ reads_samples: bool = False+def __init__(self,team: Team,@@ -429,6 +477,13 @@ class MetricQueryRunner:self.quantile = quantileself.metric_type = metric_type+ @property+ def scan_from(self) -> dt.datetime:+ """The earliest point time that the query reads, including the predecessor lookback."""+ if self.aggregation in _LOOKBACK_AGGREGATIONS:+ return self.date_from - counter_lookback(self.interval)+ return self.date_from+def run(self) -> list[dict[str, Any]]:"""Bucketed rows: `{"time", "value", "labels", "series_fingerprints"}`.`labels` carries one entry per group_by key (always `{}` without@@ -541,6 +596,18 @@ class MetricQueryRunner:def _series_scope_expr(self) -> ast.Expr:return series_scope_expr(self.metric_name, self.filters, self.date_from)+ def _points_query(self, columns: Sequence[str], point_filters: Sequence[ast.Expr] = ()) -> ast.SelectQuery:+ return points_query(+ from_samples=self.reads_samples,+ columns=columns,+ metric_names=(self.metric_name,),+ date_from=self.scan_from,+ date_to=self.date_to,+ timezone=self.team.timezone,+ row_filters=(self._series_scope_expr(), self._type_filter_expr()),+ point_filters=point_filters,+ )+def _build_simple_query(self) -> ast.SelectQuery:"""Build sum, average, count, and p95 queries.@@ -559,11 +626,7 @@ class MetricQueryRunner: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 {time_range}- AND {series_scope}- AND {type_filter}+ FROM {points}GROUP BY time, {series_key}) AS sGROUP BY time@@ -573,11 +636,8 @@ class MetricQueryRunner:placeholders={"interval": _interval_expr(self.interval),"aggregation": _aggregation_expr(self.aggregation, ast.Field(chain=["series_value"])),- "metric_name": ast.Constant(value=self.metric_name),- "time_range": time_range_expr(self.date_from, self.date_to),- "series_scope": self._series_scope_expr(),+ "points": self._points_query(("timestamp", "series_fingerprint", "value")),"series_key": _series_key_expr(),- "type_filter": self._type_filter_expr(),"row_limit": ast.Constant(value=_ROW_LIMIT),},)@@ -621,11 +681,7 @@ class MetricQueryRunner:ORDER BY timestamp ASCROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_value- FROM posthog.metrics- WHERE metric_name = {metric_name}- AND {scan_range}- AND {series_scope}- AND {type_filter}+ FROM {points})) AS sWHERE sample_timestamp >= {date_from}@@ -638,11 +694,8 @@ class MetricQueryRunner:"interval": _interval_expr(self.interval),"divisor": ast.Constant(value=divisor),"series_key": _series_key_expr(),- "metric_name": ast.Constant(value=self.metric_name),- "scan_range": time_range_expr(self.date_from - counter_lookback(self.interval), self.date_to),+ "points": self._points_query(("timestamp", "series_fingerprint", "value", "aggregation_temporality")),"date_from": ast.Constant(value=self.date_from),- "series_scope": self._series_scope_expr(),- "type_filter": self._type_filter_expr(),"row_limit": ast.Constant(value=_ROW_LIMIT),},)@@ -684,12 +737,7 @@ class MetricQueryRunner:ORDER BY timestamp ASCROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS prev_counts- FROM posthog.metrics- WHERE metric_name = {metric_name}- AND {scan_range}- AND notEmpty(histogram_counts)- AND {series_scope}- AND {type_filter}+ FROM {points})) AS sWHERE sample_timestamp >= {date_from}@@ -700,11 +748,17 @@ class MetricQueryRunner:placeholders={"interval": _interval_expr(self.interval),"series_key": _series_key_expr(),- "metric_name": ast.Constant(value=self.metric_name),- "scan_range": time_range_expr(self.date_from - counter_lookback(self.interval), self.date_to),+ "points": self._points_query(+ (+ "timestamp",+ "series_fingerprint",+ "aggregation_temporality",+ "histogram_bounds",+ "histogram_counts",+ ),+ point_filters=(parse_expr("notEmpty(histogram_counts)"),),+ ),"date_from": ast.Constant(value=self.date_from),- "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/metric_samples_query_runner.py b/products/metrics/backend/metric_samples_query_runner.pynew file mode 100644index 000000000000..cda088ee86b4--- /dev/null+++ b/products/metrics/backend/metric_samples_query_runner.py@@ -0,0 +1,63 @@+"""Run time-series queries on `metric_samples` when the range starts after the metrics4 cut-over.++`build_metric_query_runner` selects the runner. A range that starts before the+cut-over, including the predecessor lookback, still needs the `metrics2` data of+the `metrics` view.+"""++import datetime as dt+from collections.abc import Sequence++from posthog.models import Team++from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy+from products.metrics.backend.metric_query_runner import MetricQueryRunner+from products.metrics.backend.metrics4_samples import reads_metrics4_only+++class MetricSamplesQueryRunner(MetricQueryRunner):+ """Read points from `metric_samples`, and filter series-hours before the `ARRAY JOIN`."""++ reads_samples = True+++def build_metric_query_runner(+ *,+ team: Team,+ metric_name: str,+ aggregation: str,+ date_from: dt.datetime,+ date_to: dt.datetime,+ filters: Sequence[MetricFilter] = (),+ group_by: Sequence[MetricGroupBy] = (),+ interval: str | None = None,+ quantile: float | None = None,+ metric_type: str | None = None,+) -> MetricQueryRunner:+ """Return the runner for the table that holds all points of the range."""+ runner = MetricQueryRunner(+ team=team,+ metric_name=metric_name,+ aggregation=aggregation,+ date_from=date_from,+ date_to=date_to,+ filters=filters,+ group_by=group_by,+ interval=interval,+ quantile=quantile,+ metric_type=metric_type,+ )+ if not reads_metrics4_only(runner.scan_from):+ return runner+ return MetricSamplesQueryRunner(+ team=team,+ metric_name=metric_name,+ aggregation=aggregation,+ date_from=date_from,+ date_to=date_to,+ filters=filters,+ group_by=group_by,+ interval=interval,+ quantile=quantile,+ metric_type=metric_type,+ )diff --git a/products/metrics/backend/metrics4_samples.py b/products/metrics/backend/metrics4_samples.pynew file mode 100644index 000000000000..18518ffb6ee4--- /dev/null+++ b/products/metrics/backend/metrics4_samples.py@@ -0,0 +1,191 @@+"""Read metric points from `metric_samples` (`metrics4_samples`) instead of the `metrics` view.++The `metrics` view reads `metrics2` before the cut-over hour and expands every+`metrics4_samples` array after it. A read whose range starts at or after the+cut-over needs only `metrics4_samples`. That table has one row for each+series-hour, so row filters skip complete series-hours before the `ARRAY JOIN`.+The `timestamp_min` and `timestamp_max` minmax indexes skip granules by point time.++A series-hour can have more than one row until ClickHouse merges them. Each+point is in exactly one row, so an `ARRAY JOIN` over the rows returns each point once.+"""++import datetime as dt+from collections.abc import Sequence++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select++from posthog.clickhouse.metrics.metrics2 import DEFAULT_RETENTION_DAYS+from posthog.clickhouse.metrics.metrics4 import METRICS4_VIEW_CUTOVER++METRICS4_CUTOVER = dt.datetime.fromisoformat(METRICS4_VIEW_CUTOVER).replace(tzinfo=dt.UTC)++METRICS_RETENTION = dt.timedelta(days=DEFAULT_RETENTION_DAYS)++# Each point column of `metrics` maps to one array of `metric_samples`.+_POINT_ARRAYS: dict[str, str] = {+ "timestamp": "timestamp_arr",+ "observed_timestamp": "observed_timestamp_arr",+ "value": "value_arr",+ "count": "count_arr",+ "histogram_counts": "histogram_counts_arr",+ "trace_id": "trace_id_arr",+ "span_id": "span_id_arr",+ "trace_flags": "trace_flags_arr",+}++_ROW_COLUMNS: frozenset[str] = frozenset(+ {+ "team_id",+ "metric_name",+ "time_bucket",+ "series_fingerprint",+ "resource_fingerprint",+ "service_name",+ "metric_type",+ "unit",+ "aggregation_temporality",+ "is_monotonic",+ "has_labels",+ "instrumentation_scope",+ "histogram_bounds",+ }+)+++def _as_utc(value: dt.datetime) -> dt.datetime:+ return value.replace(tzinfo=dt.UTC) if value.tzinfo is None else value.astimezone(dt.UTC)+++def reads_metrics4_only(scan_from: dt.datetime) -> bool:+ """Return true when a read that starts at `scan_from` needs no `metrics2` data."""+ return _as_utc(scan_from) >= METRICS4_CUTOVER+++def _utc_hour(value: dt.datetime) -> dt.datetime:+ return _as_utc(value).replace(minute=0, second=0, microsecond=0)+++def metric_name_expr(metric_names: Sequence[str] | None) -> ast.Expr:+ """Limit a read to `metric_names`. `None` keeps every name."""+ if metric_names is None:+ return ast.Constant(value=True)+ if len(metric_names) == 1:+ return parse_expr("metric_name = {name}", placeholders={"name": ast.Constant(value=metric_names[0])})+ return parse_expr(+ "metric_name IN {names}",+ placeholders={"names": ast.Tuple(exprs=[ast.Constant(value=name) for name in metric_names])},+ )+++def _row_range_expr(date_from: dt.datetime, date_to: dt.datetime) -> ast.Expr:+ """Keep rows that can hold a point in `[date_from, date_to)`."""+ return parse_expr(+ """+ time_bucket >= {bucket_from}+ AND time_bucket <= {bucket_to}+ AND timestamp_max >= {date_from}+ AND timestamp_min < {date_to}+ """,+ placeholders={+ "bucket_from": ast.Constant(value=_utc_hour(date_from)),+ "bucket_to": ast.Constant(value=_utc_hour(date_to)),+ "date_from": ast.Constant(value=date_from),+ "date_to": ast.Constant(value=date_to),+ },+ )+++def samples_points_query(+ *,+ columns: Sequence[str],+ metric_names: Sequence[str] | None,+ date_from: dt.datetime,+ date_to: dt.datetime,+ timezone: str,+ row_filters: Sequence[ast.Expr] = (),+ point_filters: Sequence[ast.Expr] = (),+) -> ast.SelectQuery:+ """Return one row per point in `[date_from, date_to)`, with the column names of `metrics`.++ HogQL converts only `DateTime` fields to the project time zone, not array+ elements. So `timestamp` is converted to `timezone` here, to bucket as `metrics` does.++ `row_filters` can use only row columns. They apply before the `ARRAY JOIN`.+ `point_filters` can use the selected columns. They apply after it.+ `metric_names=None` reads every metric name.+ """+ unknown = [column for column in columns if column not in _POINT_ARRAYS and column not in _ROW_COLUMNS]+ if unknown:+ raise ValueError(f"Unknown metric_samples columns: {unknown!r}")++ # The time filter always needs the timestamp array.+ point_columns = ["timestamp", *(column for column in columns if column in _POINT_ARRAYS and column != "timestamp")]+ row_columns = [column for column in columns if column in _ROW_COLUMNS]++ rows = parse_select(+ "SELECT 1 FROM posthog.metric_samples WHERE {metric_name} AND {row_range}",+ placeholders={"metric_name": metric_name_expr(metric_names), "row_range": _row_range_expr(date_from, date_to)},+ )+ assert isinstance(rows, ast.SelectQuery)+ rows.select = [+ *(ast.Field(chain=[column]) for column in row_columns),+ *(ast.Field(chain=[_POINT_ARRAYS[column]]) for column in point_columns),+ ]+ if row_filters:+ assert rows.where is not None+ rows.where = ast.And(exprs=[rows.where, *row_filters])++ point_range = parse_expr(+ "point_timestamp >= {date_from} AND point_timestamp < {date_to}",+ placeholders={"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},+ )++ select: list[ast.Expr] = [+ ast.Alias(+ alias="timestamp",+ expr=ast.Call(name="toTimeZone", args=[ast.Field(chain=["point_timestamp"]), ast.Constant(value=timezone)]),+ )+ if column == "timestamp"+ else ast.Field(chain=[column])+ for column in columns+ ]+ return ast.SelectQuery(+ select=select,+ select_from=ast.JoinExpr(table=rows),+ array_join_op="ARRAY JOIN",+ array_join_list=[+ ast.Alias(+ alias="point_timestamp" if column == "timestamp" else column,+ expr=ast.Field(chain=[_POINT_ARRAYS[column]]),+ )+ for column in point_columns+ ],+ where=ast.And(exprs=[point_range, *point_filters]),+ )+++def series_in_range_query(metric_name: str, date_from: dt.datetime, date_to: dt.datetime) -> ast.SelectQuery:+ """Return the fingerprints of the series with a point in `[date_from, date_to)`.++ This read needs no `ARRAY JOIN`. It checks the timestamp array of each row.+ """+ query = parse_select(+ """+ SELECT series_fingerprint+ FROM posthog.metric_samples+ WHERE metric_name = {metric_name}+ AND {row_range}+ AND arrayExists(t -> t >= {date_from} AND t < {date_to}, timestamp_arr)+ GROUP BY series_fingerprint+ """,+ placeholders={+ "metric_name": ast.Constant(value=metric_name),+ "row_range": _row_range_expr(date_from, date_to),+ "date_from": ast.Constant(value=date_from),+ "date_to": ast.Constant(value=date_to),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return querydiff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex c9bd4dbc3c06..59eab4933ee1 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -31,6 +31,8 @@ from products.metrics.backend.metric_query_runner import (_pick_interval,attribute_field,)+from products.metrics.backend.metric_samples_query_runner import MetricSamplesQueryRunner, build_metric_query_runner+from products.metrics.backend.metrics4_samples import METRICS4_CUTOVERfrom products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables@@ -91,6 +93,8 @@ class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+CLASS_DATA_LEVEL_SETUP = Truedef setUp(self):@@ -99,7 +103,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_rejects_unsupported_aggregation(self):with self.assertRaises(ValueError):- MetricQueryRunner(+ self.runner_class(team=self.team,metric_name="x",aggregation="median",@@ -110,7 +114,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_rejects_inverted_date_range(self):now = timezone.now()with self.assertRaises(ValueError):- MetricQueryRunner(+ self.runner_class(team=self.team,metric_name="x",aggregation="sum",@@ -121,7 +125,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_rejects_too_wide_date_range(self):now = timezone.now()with self.assertRaises(ValueError):- MetricQueryRunner(+ self.runner_class(team=self.team,metric_name="x",aggregation="sum",@@ -132,7 +136,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_rejects_interval_exceeding_row_budget(self):now = timezone.now()with self.assertRaises(ValueError):- MetricQueryRunner(+ self.runner_class(team=self.team,metric_name="x",aggregation="sum",@@ -143,7 +147,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_rejects_invalid_regex_filter(self):now = timezone.now()- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="x",aggregation="sum",@@ -161,7 +165,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):metric_name="m_trunc",points=[(anchor + dt.timedelta(minutes=m), 1.0) for m in range(6)],)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="m_trunc",aggregation="sum",@@ -174,7 +178,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):runner.run()def test_returns_empty_for_no_data(self):- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="http.server.duration",aggregation="sum",@@ -207,7 +211,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):points=[(anchor - dt.timedelta(minutes=5), 99.0)],)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="m1",aggregation="sum",@@ -243,7 +247,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):labels={"pod": pod},)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="m_multi",aggregation=aggregation,@@ -269,7 +273,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):labels={"pod": "b"},)- rows = MetricQueryRunner(+ rows = self.runner_class(team=self.team,metric_name="m1",aggregation="sum",@@ -294,7 +298,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):points=[(bucket_start + dt.timedelta(minutes=15), 3.0)],)- rows = MetricQueryRunner(+ rows = self.runner_class(team=self.team,metric_name="m1",aggregation="sum",@@ -320,7 +324,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):labels={"pod": "a", "$originalTimestamp": f"2020-01-0{index + 1}T00:00:00+00:00"},)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="m_skewed",aggregation="sum",@@ -338,7 +342,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):points=[(anchor - dt.timedelta(minutes=5), 5.0)],)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="m1",aggregation="sum",@@ -781,6 +785,8 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+CLASS_DATA_LEVEL_SETUP = Truedef setUp(self):@@ -803,7 +809,7 @@ class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):)def _total(self, filters: tuple[MetricFilter, ...]) -> float:- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="req",aggregation="sum",@@ -874,7 +880,7 @@ class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):],labels={"env": "staging", "path": "/api"},)- runner = MetricQueryRunner(+ runner = self.runner_class(team=self.team,metric_name="req",aggregation="sum",@@ -1052,6 +1058,8 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+CLASS_DATA_LEVEL_SETUP = Truedef setUp(self):@@ -1070,7 +1078,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):"interval": "minute",}defaults.update(runner_overrides)- return MetricQueryRunner(**defaults).run()+ return self.runner_class(**defaults).run()def _seed_counter(self, points, **kwargs):seed_metric(@@ -1297,6 +1305,8 @@ class TestHistogramQuantileInterpolation:class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+CLASS_DATA_LEVEL_SETUP = TrueBOUNDS = [0.1, 0.5, 1.0]@@ -1330,7 +1340,7 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):"interval": "minute",}defaults.update(overrides)- return MetricQueryRunner(**defaults).run()+ return self.runner_class(**defaults).run()def test_requires_quantile(self):with self.assertRaises(ValueError):@@ -1652,6 +1662,8 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+"""Test type isolation for metrics with the same name."""CLASS_DATA_LEVEL_SETUP = True@@ -1677,7 +1689,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):)def _run(self, aggregation: str, metric_type: str | None, **kwargs: Any) -> list[dict[str, Any]]:- return MetricQueryRunner(+ return self.runner_class(team=self.team,metric_name="m_collide",aggregation=aggregation,@@ -1744,6 +1756,8 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):+ runner_class: type[MetricQueryRunner] = MetricQueryRunner+"""Test null gaps for non-finite aggregates."""CLASS_DATA_LEVEL_SETUP = True@@ -1764,7 +1778,7 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):)def _run(self, aggregation: str) -> list[dict[str, Any]]:- return MetricQueryRunner(+ return self.runner_class(team=self.team,metric_name="m_huge",aggregation=aggregation,@@ -1837,3 +1851,61 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)values = [p["value"] for p in response.json()["results"][0]["points"]]assert values == [None]+++class TestHistogramQuantileRunnerOnSamples(TestHistogramQuantileRunner):+ runner_class = MetricSamplesQueryRunner+++class TestMetricFiltersOnSamples(TestMetricFilters):+ runner_class = MetricSamplesQueryRunner+++class TestMetricQueryRunnerOnSamples(TestMetricQueryRunner):+ runner_class = MetricSamplesQueryRunner+++class TestMetricTypeIsolationOnSamples(TestMetricTypeIsolation):+ runner_class = MetricSamplesQueryRunner+++class TestNonFiniteAggregatesOnSamples(TestNonFiniteAggregates):+ runner_class = MetricSamplesQueryRunner+++class TestRateIncreaseOnSamples(TestRateIncrease):+ runner_class = MetricSamplesQueryRunner+++class TestBuildMetricQueryRunner(APIBaseTest):+ @parameterized.expand(+ [+ ("before_cutover", "sum", None, METRICS4_CUTOVER - dt.timedelta(hours=1), MetricQueryRunner),+ ("at_cutover", "sum", None, METRICS4_CUTOVER, MetricSamplesQueryRunner),+ ("lookback_crosses_cutover", "rate", "minute", METRICS4_CUTOVER, MetricQueryRunner),+ (+ "lookback_after_cutover",+ "rate",+ "minute",+ METRICS4_CUTOVER + dt.timedelta(hours=1),+ MetricSamplesQueryRunner,+ ),+ ]+ )+ def test_selects_runner_by_scan_start(+ self,+ _name: str,+ aggregation: str,+ interval: str | None,+ date_from: dt.datetime,+ expected: type[MetricQueryRunner],+ ) -> None:+ runner = build_metric_query_runner(+ team=self.team,+ metric_name="m",+ aggregation=aggregation,+ date_from=date_from,+ date_to=date_from + dt.timedelta(hours=2),+ interval=interval,+ )+ self.assertIs(type(runner), expected)