: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
perf(metrics): shrink the label reads behind charts and the overview (#99316)
Frank Hamandb1ae69b07087
diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.pyindex 5f9ffb77060f..24e5c4de0362 100644--- a/products/metrics/backend/metric_event_samples_query_runner.py+++ b/products/metrics/backend/metric_event_samples_query_runner.py@@ -1,20 +1,8 @@-"""Raw metric emissions for a metric, from the metrics/metric_series split.--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.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. 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-sample's trace_id can be passed straight to the trace endpoint / trace URL.+"""Return raw metric samples for the Samples and metric-to-trace views.++Join samples to deduplicated series labels by `series_fingerprint`.+The sample row supplies name and type if its series row is missing.+The API uses hex trace IDs. Storage uses base64 trace IDs."""import base64@@ -35,10 +23,7 @@ from products.metrics.backend.facade.contracts import MetricFilterfrom products.metrics.backend.facade.enums import MetricTypefrom 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-# queries get, and the same throw-on-overflow: a truncated sample list would-# read as "these are the emissions" while silently hiding most of them.+# This query uses the shared ClickHouse cluster. Limit reads and fail on overflow._QUERY_SETTINGS = HogQLGlobalSettings(max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,read_overflow_mode="throw",@@ -46,10 +31,9 @@ _QUERY_SETTINGS = HogQLGlobalSettings(def _normalise_to_base64(value: str) -> str:- """Hex trace/span ids (the API form) become the base64 the storage holds.+ """Convert API hex trace or span IDs to storage base64.- No-op for values that aren't valid hex, mirroring the tracing product's- filter normalisation so both pivot directions accept the same id string.+ Return invalid hex values unchanged to match tracing filters."""try:int(value, 16)@@ -72,14 +56,11 @@ class MetricEventSamplesQueryRunner:metric_type: MetricType | None = None,limit: int = 100,) -> None:- # A trace-only query (the trace->metrics pivot) spans every metric name; it stays- # bounded because trace_id carries a bloom-filter index (idx_trace_id_bf).+ # A trace query covers every metric name. `trace_id` has a bloom-filter index.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 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.+ # Label filters need one metric name. Keep trace queries unscoped.raise ValueError("filters and metric_type require metric_name")if date_to <= date_from:raise ValueError("date_to must be after date_from")@@ -87,8 +68,7 @@ class MetricEventSamplesQueryRunner:raise ValueError("limit must be in [1, 1000]")if span_id and not trace_id:- # A span id is only unique within its trace, so an unanchored span filter- # would silently mix emissions from unrelated traces.+ # A span ID is unique only within its trace.raise ValueError("span_id requires trace_id")self.team = team@@ -102,18 +82,10 @@ class MetricEventSamplesQueryRunner:self.limit = limitdef 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 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.+ # 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.query = parse_select("""WITH matched_samples AS (@@ -180,7 +152,7 @@ class MetricEventSamplesQueryRunner:"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),+ "series_scope": series_scope_expr(self.metric_name, self.filters, self.date_from),"limit": ast.Constant(value=self.limit),},)diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 045a5e2dd3c3..47dc7c186c2d 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -1,22 +1,8 @@-"""Single-metric time-series query runner.--Returns a list of `(time_bucket, value)` points for one metric over a date-range, with a choice of aggregation. Modelled after the logs-`SparklineQueryRunner` shape but flattened — we don't yet need the full-`AnalyticsQueryRunner[LogsQueryResponse]` infrastructure since this product-isn't going through HogQL `DataNode` caching, schema-gen or the data-viz-pipeline yet.--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`).+"""Run time-series queries for one metric.++Aggregate each physical series before combining series.+Metric points store a fingerprint. Series rows store label maps.+Filters use fingerprints, and group-by joins labels after reduction."""import re@@ -42,59 +28,33 @@ AttributeScope = Literal["resource", "attribute", "auto"]_ALLOWED_ATTRIBUTE_SCOPES: frozenset[str] = frozenset({"resource", "attribute", "auto"})-# Hard bound on bucketed rows per query; hitting it raises instead of-# silently truncating the tail of the time range (ORDER BY time ASC means-# the most recent buckets would be the ones dropped).+# Limit bucket rows. Raise an error instead of hiding recent buckets._ROW_LIMIT = 10000-# Widest queryable range. Counter/histogram queries scan raw samples within-# the range on the ClickHouse cluster shared with the live logs/traces-# products, so the span has to be bounded. The bound stays on the requested-# range: `date_from` snaps back to its bucket boundary and the counter and-# histogram scans reach a further `counter_lookback(interval)` for a-# predecessor sample, so the scan exceeds the request by under one interval-# step plus the lookback (up to two weeks of extra daily partitions at the-# `week` interval, a single one on the common sub-day charts).+# A series record updates every 30 minutes. The one-hour buffer allows late updates.+_SERIES_LAST_SEEN_BUFFER = dt.timedelta(hours=1)++# Limit the query range on the shared ClickHouse cluster.+# Counter and histogram queries read one bucket plus the predecessor lookback.MAX_QUERY_SPAN = dt.timedelta(days=31)-# These run on the shared logs cluster; cap how much one query may read.+# These queries use the shared logs cluster. Limit reads._QUERY_SETTINGS = HogQLGlobalSettings(max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,read_overflow_mode="throw",)-# 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.+# Ingestion extracts `service.name` to a column on both metrics tables.+# Map both spellings to that column for filters and group-bys._SERVICE_NAME_KEYS: frozenset[str] = frozenset({"service_name", "service.name"})def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:- """Build the HogQL AST node that accesses a metric attribute by name.-- 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. 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.-- The empty-string fallback is documented behavior, not a bug: it means- callers cannot meaningfully filter for "attribute equals empty string"- in auto scope. Use an explicit scope for that edge case.-- ``service_name`` / ``service.name`` are special-cased to the first-class- ``service_name`` column regardless of scope: ingestion extracts the- service name out of the resource attributes into its own column, so a- map lookup would match nothing on real rows.+ """Return a HogQL AST expression for a metric attribute.++ Labels are in `metric_series`. `scope` selects a resource, attribute, or+ resource-first map. Use an explicit scope to match empty strings.+ Service name always uses the extracted `service_name` column."""if scope not in _ALLOWED_ATTRIBUTE_SCOPES:raise ValueError(f"Unknown attribute scope: {scope!r}")@@ -104,10 +64,8 @@ def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:name_constant = ast.Constant(value=name)- # arrayElement, not subscript: HogQL prints `field[...]` on a- # StringJSONDatabaseField as JSONExtractRaw, which is illegal on the- # physical Map columns. arrayElement passes through and is ClickHouse's- # native Map accessor ('' for missing keys).+ # Use `arrayElement`. Subscript syntax is invalid on physical Map columns.+ # It is ClickHouse's Map accessor and returns an empty string for missing keys.if scope == "resource":return parse_expr("arrayElement(resource_attributes, {name})", placeholders={"name": name_constant})if scope == "attribute":@@ -119,34 +77,19 @@ def attribute_field(name: str, *, scope: AttributeScope = "auto") -> 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.-- `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 the key for one physical series.++ Ingestion includes name, type, service, and labels. It excludes+ `$originalTimestamp`."""return ast.Field(chain=["series_fingerprint"])def _aggregation_expr(name: str, value: ast.Expr) -> ast.Expr:- """Build the HogQL AST for the cross-series aggregations.-- `value` is the per-series value the inner query produced, never the raw- `value` column: aggregating raw rows counts each series once per sample, so- the result scales with the scrape rate. `count` takes no argument for the- same reason — one inner row per series means it counts series.+ """Return a HogQL AST for cross-series aggregation.- Kept as AST nodes (rather than string interpolation) so the- `hogql-no-fstring` semgrep rule doesn't have to special-case this- runner — the function name and percentile literal travel as a- typed expression, not as substituted text.+ The inner query returns one value per series. This prevents scrape rate+ from changing the result. `count` therefore counts series."""if name == "sum":return ast.Call(name="sum", args=[value])@@ -164,10 +107,7 @@ def _aggregation_expr(name: str, value: ast.Expr) -> ast.Expr:def _finite_or_none(value: float | None) -> float | None:- """ClickHouse float aggregates can overflow to inf/-inf (or produce NaN);- a non-finite value has no JSON representation and downstream renderers- turn it into null anyway. Make the null explicit and deterministic here —- consumers render it as a gap."""+ """Return null for non-finite values so clients render a gap."""if value is None or not math.isfinite(value):return Nonereturn value@@ -177,18 +117,14 @@ _ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"})-# Derived from the contract enum (whose values match what the ingest writes,-# rust/capture-logs `flatten_metric`) so the two can't silently diverge.+# Derive this from the contract enum to match ingestion values._ALLOWED_METRIC_TYPES: frozenset[str] = frozenset(t.value for t in MetricType)def _histogram_quantile(quantile: float, bounds: list[float], counts: list[float]) -> float:- """Prometheus-style quantile from explicit-bounds bucket counts.+ """Calculate a Prometheus-style quantile from bounded bucket counts.- `counts` has one entry per bound plus an overflow bucket. Linear- interpolation inside the bucket containing the rank; the overflow- bucket clamps to the highest finite bound; the first bucket's lower- edge is assumed 0 (negative-bound histograms get bounds[0]).+ Interpolate in the selected bucket. Clamp overflow to the highest bound."""total = sum(counts)if total <= 0 or not bounds:@@ -208,11 +144,10 @@ def _histogram_quantile(quantile: float, bounds: list[float], counts: list[floatreturn bounds[-1]-# Target ~60 buckets across the requested range — feels right for a chart.+# Target about 60 chart buckets._TARGET_BUCKET_COUNT = 60-# Order from finest to coarsest. The first interval that yields-# <= _TARGET_BUCKET_COUNT buckets wins.+# List intervals from finest to coarsest._INTERVAL_LADDER: list[tuple[str, dt.timedelta, ast.Call]] = [("second", dt.timedelta(seconds=1), ast.Call(name="toIntervalSecond", args=[ast.Constant(value=1)])),("minute", dt.timedelta(minutes=1), ast.Call(name="toIntervalMinute", args=[ast.Constant(value=1)])),@@ -249,82 +184,47 @@ def _interval_step(name: str) -> dt.timedelta:def _align_to_interval(timestamp: dt.datetime, interval: str, *, tzinfo: ZoneInfo) -> dt.datetime:- """Floor `timestamp` onto the bucket grid `toStartOfInterval` uses.-- The bucket labels come from `toStartOfInterval(sample_timestamp)`, so a- `date_from` inside a bucket would make that first bucket partial: labelled- as the whole interval but covering only the slice after `date_from`. Every- query scans and clips from this floor instead, so the first bucket holds- its full interval. Relative ranges like "-1h" resolve to now-minus-offset- with second precision, which makes the unaligned case the normal one.-- The grid lives in `tzinfo`, the project's timezone, not in UTC. HogQL- rewrites a `DateTime` column read into `toTimeZone(<column>, <project- timezone>)` (`PropertySwapper.visit_field`), so `toStartOfInterval` sees a- local-time value and counts every step from local midnight. Flooring in UTC- instead lands on the same instant for the sub-hour steps, but drifts for- `hour_6`, `day` and `week`, and for `hour` in a zone whose offset is not a- whole number of hours (Asia/Kolkata is +05:30, so its hour boundaries sit- at :30 past each UTC hour).-- Not `posthog.interval_specs.align`: that grid honors the team's- `week_start_day` and lacks the sub-hour steps, where `toStartOfInterval`- always counts weeks from Monday — the two would disagree exactly where- agreement with the SQL is the point.+ """Floor a timestamp to the ClickHouse bucket grid.++ Use the project timezone to keep the first bucket complete. Do not use+ `interval_specs.align`, which uses different week and sub-hour rules."""if timestamp.tzinfo is None:timestamp = timestamp.replace(tzinfo=dt.UTC)local = timestamp.astimezone(tzinfo)midnight = local.replace(hour=0, minute=0, second=0, microsecond=0)if interval == "week":- # ClickHouse's week interval starts on Monday, unlike its own- # `toStartOfWeek`, which defaults to Sunday.+ # ClickHouse week intervals start on Monday. `toStartOfWeek` defaults to Sunday.return (midnight - dt.timedelta(days=midnight.weekday())).astimezone(dt.UTC)if interval == "day":return midnight.astimezone(dt.UTC)- # ClickHouse counts elapsed seconds from the midnight instant, so this adds- # a real duration rather than doing wall-clock arithmetic. A day shortened- # or lengthened by a DST transition then keeps both grids on the same- # boundaries.+ # Use elapsed time from local midnight. This keeps DST boundaries aligned.step = _interval_step(interval)return midnight.astimezone(dt.UTC) + (local.astimezone(dt.UTC) - midnight.astimezone(dt.UTC)) // step * step-# 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 `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.+# Use Prometheus's default lookback. It supports scrapes slower than a bucket.+# A five-minute lookback reads the same hourly granules as a shorter one._MIN_COUNTER_LOOKBACK = dt.timedelta(minutes=5)def counter_lookback(interval: str) -> dt.timedelta:- """How far before `date_from` the counter and histogram scans reach.-- Those aggregations diff each sample against the one before it, so the last- sample *outside* the requested range is an input to the first bucket inside- it. Without it the first bucket diffs against nothing and is dropped as- uncomputable. The pre-range rows are cut again before bucketing, so the- returned grid is exactly the requested range.+ """Return the counter and histogram predecessor lookback.- `diagnostics.decompose_bucket` reads its raw samples over the same window- through this helper: a shorter reach there would find a different- predecessor and report a disagreement the chart does not have.+ The first in-range sample needs its prior sample. Queries remove pre-range+ rows before returning results. Diagnostics uses the same lookback."""return max(_interval_step(interval), _MIN_COUNTER_LOOKBACK)def _filter_condition(filter: MetricFilter) -> ast.Expr:- """One label predicate as a HogQL boolean expression.+ """Return one label predicate as a HogQL boolean expression.- Missing map keys resolve to `''`, so `neq`/`not_regex` also match rows- that lack the key entirely — same as Prometheus negative matchers.+ Negative matchers include missing map keys, as in Prometheus."""field = attribute_field(filter.key, scope=filter.scope.value)if filter.op in (FilterOp.REGEX, FilterOp.NOT_REGEX):- # Pre-validate so a bad pattern is a 400, not a ClickHouse- # CANNOT_COMPILE_REGEXP 500. Python `re` accepts a superset of RE2,- # so this catches syntax errors without rejecting valid patterns.+ # Return 400 for invalid patterns. Python accepts all valid RE2 syntax.try:re.compile(filter.value)except re.error as exc:@@ -352,16 +252,10 @@ def filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr: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.+ """Limit a `metrics` read to `[date_from, date_to)`.++ Timestamp gives the exact range. UTC `time_bucket` lets ClickHouse skip+ granules."""return parse_expr("""@@ -384,28 +278,40 @@ def _utc_hour(value: dt.datetime) -> dt.datetime: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- blend into one aggregate. TRUE when no type was requested.+ """Limit rows to one metric type.- Both `metrics` and `metric_series` name the column `metric_type`, so the- same expression works against either table."""+ The same name can have distinct counter and gauge series. Return true when+ no type was requested.+ """if metric_type is None:return ast.Constant(value=True)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.+def _active_since_expr(date_from: dt.datetime | None) -> ast.Expr:+ """Bound a `metric_series` read to series that could have later samples.- 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.+ Keep a one-hour buffer for delayed series updates. `metric_series2` indexes+ `last_seen`, so the bound skips old parts.- 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.+ TRUE when `date_from` is None, for callers (the bucket decomposition) that+ want every series regardless of when it was last seen.+ """+ if date_from is None:+ return ast.Constant(value=True)+ return parse_expr(+ "last_seen >= {date_from}",+ placeholders={"date_from": ast.Constant(value=date_from - _SERIES_LAST_SEEN_BUFFER)},+ )+++def series_scope_expr(+ metric_name: str, filters: Sequence[MetricFilter], date_from: dt.datetime | None = None+) -> ast.Expr:+ """Limit `metrics` rows to series that match label filters.++ Labels are in `metric_series`, so filters select matching fingerprints.+ Without filters, points with missing series rows still count."""if not filters:return ast.Constant(value=True)@@ -415,21 +321,23 @@ def series_scope_expr(metric_name: str, filters: Sequence[MetricFilter]) -> ast.SELECT series_fingerprintFROM posthog.metric_seriesWHERE metric_name = {metric_name}+ AND {active_since}AND {filters})""",- placeholders={"metric_name": ast.Constant(value=metric_name), "filters": filters_expr(filters)},+ placeholders={+ "metric_name": ast.Constant(value=metric_name),+ "active_since": _active_since_expr(date_from),+ "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.+def series_labels_query(metric_name: str, date_from: dt.datetime | None = None) -> ast.SelectQuery:+ """Return full label maps for each metric series.- 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.+ Group rows to avoid duplicate joins. `date_from` limits active series.+ Without it, return every series for bucket decomposition."""query = parse_select("""@@ -440,14 +348,40 @@ def series_labels_query(metric_name: str) -> ast.SelectQuery:any(resource_attributes) AS resource_attributesFROM posthog.metric_seriesWHERE metric_name = {metric_name}+ AND {active_since}GROUP BY series_fingerprint""",- placeholders={"metric_name": ast.Constant(value=metric_name)},+ placeholders={"metric_name": ast.Constant(value=metric_name), "active_since": _active_since_expr(date_from)},)assert isinstance(query, ast.SelectQuery)return query+def series_group_labels_query(+ metric_name: str, group_by: Sequence[MetricGroupBy], date_from: dt.datetime | None = None+) -> ast.SelectQuery:+ """Return group-by labels for each series as `group_0`, `group_1`, and so on.++ Read only the group labels to avoid joining full maps. `any()` is safe+ because labels are constant within a series.+ """+ query = parse_select(+ """+ SELECT series_fingerprint+ FROM posthog.metric_series+ WHERE metric_name = {metric_name}+ AND {active_since}+ GROUP BY series_fingerprint+ """,+ placeholders={"metric_name": ast.Constant(value=metric_name), "active_since": _active_since_expr(date_from)},+ )+ assert isinstance(query, ast.SelectQuery)+ for index, group in enumerate(group_by):+ label = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])+ query.select.append(ast.Alias(alias=f"group_{index}", expr=ast.Call(name="any", args=[label])))+ return query++class MetricQueryRunner:def __init__(self,@@ -487,8 +421,7 @@ class MetricQueryRunner:self.metric_name = metric_nameself.aggregation = aggregationself.interval = interval or _pick_interval(date_from, date_to)- # Validation above bounds the requested range; the scan then starts at- # the bucket boundary so the first bucket covers its whole interval.+ # Start at the bucket boundary so the first bucket is complete.self.date_from = _align_to_interval(date_from, self.interval, tzinfo=team.timezone_info)self.date_to = date_toself.filters = tuple(filters)@@ -497,8 +430,7 @@ class MetricQueryRunner:self.metric_type = metric_typedef run(self) -> list[dict[str, Any]]:- """Bucketed rows: `{"time", "value", "labels"}`. `labels` carries one- entry per group_by key (always `{}` without group_by)."""+ """Return bucketed rows with time, value, and group labels."""if self.aggregation == "histogram_quantile":return self._run_histogram_quantile()if self.aggregation in ("rate", "increase"):@@ -528,9 +460,7 @@ class MetricQueryRunner:return rowsdef _run_histogram_quantile(self) -> list[dict[str, Any]]:- """ClickHouse sums the per-le distributions (temporality-aware,- per-series deltas like rate/increase); the quantile interpolation- happens here in Python where it is exact and unit-testable."""+ """Calculate quantiles from the distributions that ClickHouse sums."""assert self.quantile is not Nonequery = self._build_histogram_query()response = execute_hogql_query(@@ -555,9 +485,7 @@ class MetricQueryRunner:bounds = list(row[1 + group_count])counts = list(row[3 + group_count])if sum(counts) <= 0:- # No computable increase in this bucket (e.g. a cumulative- # series' first sample has nothing to diff against). A gap is- # honest; a fabricated quantile of 0 reads as "p95 is 0s".+ # The bucket has no computable increase. Return a gap, not zero.continuerows.append({@@ -569,9 +497,7 @@ class MetricQueryRunner:return rowsdef _raise_on_truncation(self, results: list[Any]) -> None:- """A full page means ClickHouse hit the row LIMIT and dropped the- tail of the range (the most recent buckets) — fail loud rather than- return data that silently ends early."""+ """Raise an error when the row limit drops recent buckets."""if len(results) >= _ROW_LIMIT:raise ValueError("query produced too many (time bucket, group) rows; "@@ -579,16 +505,10 @@ class MetricQueryRunner:)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.-- `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.+ """Add group labels between `time` and `value`.++ Join series labels by fingerprint only when the query groups results.+ Missing series rows use empty labels."""if not self.group_by:return@@ -596,43 +516,32 @@ class MetricQueryRunner: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),+ table=series_group_labels_query(self.metric_name, self.group_by, self.date_from),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):+ # The joined query resolves labels as `group_i`.+ # The outer query reads `ser.group_i`, not label maps.+ for index in range(len(self.group_by)):alias = f"group_{index}"- label_expr: ast.Expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])- query.select.insert(1 + index, ast.Alias(alias=alias, expr=label_expr))+ query.select.insert(1 + index, ast.Alias(alias=alias, expr=ast.Field(chain=["ser", alias])))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)+ return series_scope_expr(self.metric_name, self.filters, self.date_from)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.-- The inner query takes each series' last sample in the bucket, so a- metric scraped ten times contributes once rather than ten times.- Aggregating raw rows instead multiplied the cross-series total by the- scrape count, and the multiplier moved with partial buckets and- dropped scrapes.+ """Build sum, average, count, and p95 queries.- Two samples of one series sharing a timestamp (a duplicate scrape)- make `argMax` pick between them arbitrarily; they are the same- reading, so either answer is right.-- 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.+ Reduce each series to its last value per bucket before aggregation.+ Group-by joins labels by fingerprint after reduction."""- # `metrics` is only registered under the `posthog.` HogQL namespace- # (see posthog/hogql/database/database.py).+ # `metrics` is registered only in the `posthog.` HogQL namespace.query = parse_select("""SELECT@@ -670,27 +579,11 @@ class MetricQueryRunner:return querydef _build_counter_query(self) -> ast.SelectQuery:- """rate/increase: per-underlying-series deltas, then aggregate.-- 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- post-reset absolute value IS the increase); a sample with no- predecessor within `counter_lookback` has an unknowable increase, so- it contributes NULL, and a bucket where nothing was computable is- dropped rather than plotted as 0 (the histogram path drops such- buckets too).- - delta temporality: each sample already is the increase, so it- contributes its own value.-- `increase` sums contributions per bucket; `rate` divides by the- bucket length in seconds.-- The scan starts a lookback before `date_from` so the first sample in- the range has a predecessor to diff against; the outer `WHERE` drops- those pre-range rows again, leaving the requested bucket grid.+ """Build rate and increase queries from per-series deltas.++ Cumulative metrics diff each sample and handle resets. Delta metrics+ use sample values. Missing predecessors produce gaps. The lookback+ provides a predecessor before the requested range."""step_seconds = _interval_step(self.interval).total_seconds()divisor = step_seconds if self.aggregation == "rate" else 1.0@@ -750,10 +643,7 @@ class MetricQueryRunner:return querydef _build_histogram_query(self) -> ast.SelectQuery:- """Per-time-bucket summed bucket-count distributions for histogram- rows, with the same per-series temporality/reset handling as- rate/increase applied element-wise to the counts array — including the- lookback that gives the first in-range sample a predecessor."""+ """Build histogram distributions with rate and increase semantics."""query = parse_select("""SELECTdiff --git a/products/metrics/backend/metrics_overview_query_runner.py b/products/metrics/backend/metrics_overview_query_runner.pyindex 4fe6593fafe6..ea70f59dc51f 100644--- a/products/metrics/backend/metrics_overview_query_runner.py+++ b/products/metrics/backend/metrics_overview_query_runner.py@@ -1,18 +1,8 @@-"""Ingestion rollup for the metrics overview page.--Reads `metric_series` only — one row per (metric, label-set) with a-materialized `last_seen`, sorted by `(team_id, metric_name,-series_fingerprint)` — so the landing page never scans the raw datapoint-table. Two queries: an unwindowed pass for freshness plus window-scoped-inventory counts, and a windowed GROUP BY service.--No FINAL, same argument as `MetricNamesQueryRunner`: ReplacingMergeTree-duplicates share the fingerprint, `max(last_seen)` picks the row FINAL would-keep, and `uniqExact(series_fingerprint)` counts duplicates once. The-freshness pass filters inside the aggregates rather than in WHERE because-`last_seen` must be the max over ALL retained series: when ingestion stops,-the window counts go to zero but the status strip still needs to say how-long ago the last datapoint arrived.+"""Build metrics overview data from `metric_series`.++`max(last_seen)` and `uniqExact` handle duplicate rows without FINAL.+Counts use a window so the index skips old parts. Freshness reads the last+data point. All three queries run concurrently."""import datetime as dt@@ -39,25 +29,26 @@ from products.metrics.backend.facade.contracts import MetricsOverview, MetricsSetracer = trace.get_tracer(__name__)-# The overview tolerates partial results, so reads break at the budget instead-# of erroring the way the chart queries do. Mirrors MetricNamesQueryRunner.+# The overview accepts partial results. Stop at the read limit._QUERY_SETTINGS = HogQLGlobalSettings(max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,read_overflow_mode="break",)-# More services than this stops being an overview; the largest win.+# Show only the largest services.MAX_SERVICES = 500DEFAULT_LOOKBACK = dt.timedelta(days=1)-def _set_query_timing_attributes(span: Span, response: HogQLQueryResponse) -> None:- """Split the HogQL root timing from the ClickHouse read.+@frozen+class _OverviewCounts:+ metric_names: int+ series: int+- `.` is the whole lifecycle (parse, resolve, print, execute), so a slow overview- trace needs `./clickhouse_execute` to tell a slow read from slow query building.- """+def _set_query_timing_attributes(span: Span, response: HogQLQueryResponse) -> None:+ """Set separate timing attributes for the query and ClickHouse read."""timings = {timing.k: timing.t for timing in response.timings or ()}if (query_seconds := timings.get(".")) is not None:span.set_attribute("query.seconds", query_seconds)@@ -65,19 +56,6 @@ def _set_query_timing_attributes(span: Span, response: HogQLQueryResponse) -> Nospan.set_attribute("clickhouse.seconds", clickhouse_seconds)-@frozen-class _OverviewTotals:- """Project-wide freshness and inventory counts, before the per-service split.-- `metric_names` and `series` are both counts of the window, so they are named- rather than positional — swapping them would misreport the project silently.- """-- last_seen: str | None- metric_names: int- series: int--class MetricsOverviewQueryRunner:def __init__(self, team: Team, *, lookback: dt.timedelta = DEFAULT_LOOKBACK) -> None:if lookback <= dt.timedelta(0):@@ -89,25 +67,43 @@ class MetricsOverviewQueryRunner:def _lookback_interval(self) -> ast.Call:return ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])- def _run_totals(self) -> _OverviewTotals:- with tracer.start_as_current_span("metrics.overview.totals") as span:+ def _run_freshness(self) -> str | None:+ with tracer.start_as_current_span("metrics.overview.freshness") as span:span.set_attribute("team_id", self.team.pk)- # `last_seen_at`, not `last_seen`: HogQL registers select aliases before- # resolving the aggregate filters and would shadow the table column.+ # Report the last data point, even after ingestion stops.+ query = parse_select("SELECT max(toNullable(last_seen)) AS last_seen_at FROM posthog.metric_series")+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricsOverviewFreshnessQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ settings=_QUERY_SETTINGS,+ )+ _set_query_timing_attributes(span, response)+ if not response.results or response.results[0][0] is None:+ return None+ return response.results[0][0].isoformat()++ def _run_counts(self) -> _OverviewCounts:+ with tracer.start_as_current_span("metrics.overview.counts") as span:+ span.set_attribute("team_id", self.team.pk)+ # Put the time window in WHERE so the index skips old parts.query = parse_select("""SELECT- max(toNullable(last_seen)) AS last_seen_at,- uniqExactIf(metric_name, last_seen > now() - {lookback}) AS metric_names,- uniqExactIf(series_fingerprint, last_seen > now() - {lookback}) AS active_series+ uniqExact(metric_name) AS metric_names,+ uniqExact(series_fingerprint) AS active_seriesFROM posthog.metric_series+ WHERE last_seen > now() - {lookback}""",placeholders={"lookback": self._lookback_interval()},)assert isinstance(query, ast.SelectQuery)response = execute_hogql_query(- query_type="MetricsOverviewTotalsQuery",+ query_type="MetricsOverviewCountsQuery",query=query,team=self.team,workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now@@ -115,13 +111,9 @@ class MetricsOverviewQueryRunner:)_set_query_timing_attributes(span, response)if not response.results:- return _OverviewTotals(last_seen=None, metric_names=0, series=0)- last_seen, metric_names, series = response.results[0]- return _OverviewTotals(- last_seen=last_seen.isoformat() if last_seen is not None else None,- metric_names=int(metric_names),- series=int(series),- )+ return _OverviewCounts(metric_names=0, series=0)+ metric_names, series = response.results[0]+ return _OverviewCounts(metric_names=int(metric_names), series=int(series))def _run_services(self) -> tuple[MetricsServiceOverview, ...]:with tracer.start_as_current_span("metrics.overview.services") as span:@@ -168,19 +160,22 @@ class MetricsOverviewQueryRunner:span.set_attribute("lookback_seconds", int(self.lookback.total_seconds()))if TEST:- totals = self._run_totals()+ last_seen = self._run_freshness()+ counts = self._run_counts()services = self._run_services()else:- with ThreadPoolExecutor(max_workers=2, thread_name_prefix="metrics_overview") as executor:- totals_future = executor.submit(contextvars.copy_context().run, self._run_totals)+ with ThreadPoolExecutor(max_workers=3, thread_name_prefix="metrics_overview") as executor:+ freshness_future = executor.submit(contextvars.copy_context().run, self._run_freshness)+ counts_future = executor.submit(contextvars.copy_context().run, self._run_counts)services_future = executor.submit(contextvars.copy_context().run, self._run_services)- totals = totals_future.result()+ last_seen = freshness_future.result()+ counts = counts_future.result()services = services_future.result()return MetricsOverview(- last_seen=totals.last_seen,- metric_names=totals.metric_names,- series=totals.series,+ last_seen=last_seen,+ metric_names=counts.metric_names,+ series=counts.series,lookback_seconds=int(self.lookback.total_seconds()),services=services,)diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex eb50fd8208b7..76aa13fb6a45 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -25,6 +25,7 @@ from products.metrics.backend.formula import evaluate, parse_formulafrom products.metrics.backend.metric_query_runner import (_INTERVAL_LADDER,MetricQueryRunner,+ _active_since_expr,_align_to_interval,_histogram_quantile,_pick_interval,@@ -36,11 +37,11 @@ from products.metrics.backend.tests._seeder import seed_metric, truncate_metricsclass TestPickInterval:@parameterized.expand([- # 60 buckets at 1 min each+ # 60 one-minute buckets.("1h_range_picks_minute", dt.timedelta(hours=1), "minute"),- # 24 buckets, comfortably under the ~60 target+ # 24 buckets are below the target.("1d_range_picks_hour", dt.timedelta(days=1), "hour"),- # 30 buckets; finer intervals all exceed the target+ # Finer intervals exceed the target.("30d_range_picks_day", dt.timedelta(days=30), "day"),])@@ -49,6 +50,17 @@ class TestPickInterval:assert _pick_interval(start, start + delta) == expected+class TestActiveSinceExpr:+ def test_keeps_series_within_the_last_seen_buffer(self) -> None:+ date_from = dt.datetime(2026, 1, 1, 12, tzinfo=dt.UTC)++ expr = _active_since_expr(date_from)++ assert isinstance(expr, ast.CompareOperation)+ assert isinstance(expr.right, ast.Constant)+ assert expr.right.value == date_from - dt.timedelta(hours=1)++class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):@parameterized.expand([@@ -58,12 +70,8 @@ class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):])def test_matches_clickhouse_bucket_boundaries(self, project_timezone: str, interval: str) -> None:- # The runner snaps date_from onto the bucket grid before querying; if- # this floor ever disagrees with toStartOfInterval, first buckets go- # partial again. The queries read `timestamp` through the project's- # timezone, because HogQL wraps a DateTime column in toTimeZone, so the- # grid that has to match is the project's. Asia/Kolkata is +05:30, which- # puts every boundary from `hour` up where a UTC floor never lands.+ # The runner floors `date_from` on the project time grid.+ # This must match `toStartOfInterval` to keep the first bucket complete.awkward = dt.datetime(2026, 3, 11, 17, 47, 33, 123456, tzinfo=dt.UTC)aligned = _align_to_interval(awkward, interval, tzinfo=ZoneInfo(project_timezone))@@ -75,10 +83,7 @@ class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):f"SELECT toString(toStartOfInterval(toTimeZone(toDateTime64(%(ts)s, 6, 'UTC'), %(tz)s), {interval_sql}))",{"ts": awkward.strftime("%Y-%m-%d %H:%M:%S.%f"), "tz": project_timezone},)- # Rendering the bucket as a string keeps the comparison free of the- # driver's datetime conversion, and covers the `week` interval, which- # ClickHouse truncates to a bare Date. Either shape names a wall-clock- # reading in the project's timezone.+ # Compare strings to avoid driver date conversion. This also covers weeks.clickhouse_aligned = dt.datetime.fromisoformat(bucket_label).replace(tzinfo=ZoneInfo(project_timezone))self.assertEqual(aligned, clickhouse_aligned)@@ -195,7 +200,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):points=[(anchor - dt.timedelta(minutes=5), 3.0)],labels={"pod": "b"},)- # Different metric — should be filtered out.+ # Exclude a different metric.seed_metric(team_id=self.team.id,metric_name="m2",@@ -216,15 +221,13 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):@parameterized.expand([- # Summing raw samples would give 66 (every sample counted), and- # scrape count is not constant across buckets, so the error moves.+ # Raw samples sum to 66 and vary with scrape count.("sum", 33.0),- # Sample-weighted would be 11.0.+ # Sample-weighted average is 11.0.("avg", 16.5),- # Counting raw samples would give 6.+ # Raw samples count as 6.("count", 2.0),- # The discriminating case for min: over raw samples this is 1.0, series a's- # stale first sample, rather than the smallest current reading across series.+ # Raw samples would select the stale value 1.0.("min", 3.0),("max", 30.0),]@@ -251,10 +254,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual([row["value"] for row in runner.run()], [expected])def test_unaligned_date_from_reads_the_whole_first_bucket(self):- # The viewer's relative presets ("-1h") resolve to now-minus-offset with- # second precision, so date_from usually lands inside a bucket. A series- # whose only report came before date_from but inside that bucket must- # still count — the bucket stands for its whole interval.+ # Relative presets can start inside a bucket. The whole bucket must count.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)seed_metric(team_id=self.team.id,@@ -284,10 +284,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(earliest, anchor)def test_first_bucket_is_whole_on_a_project_away_from_utc(self):- # A project at +05:30 has its hourly buckets at :30 past each UTC hour,- # so a date_from floored in UTC can start the scan after the bucket- # ClickHouse labels the rows with. The 07:45 sample belongs to the- # 07:30 bucket, and a UTC floor to 08:00 would drop it.+ # In a half-hour time zone, a UTC floor can drop the first bucket.self.team.timezone = "Asia/Kolkata"self.team.save()bucket_start = dt.datetime(2026, 3, 17, 7, 30, tzinfo=dt.UTC)@@ -314,9 +311,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_synthetic_original_timestamp_does_not_split_a_series(self):anchor = timezone.now().replace(second=0, microsecond=0)bucket = anchor - dt.timedelta(minutes=5)- # Ingest stamps `$originalTimestamp` on a point whose timestamp it had to- # override, with a different value per sample, and excludes it from the- # series identity it computes. Counting it here would give 6.0.+ # Ingestion excludes `$originalTimestamp` from series identity.for index, value in enumerate((1.0, 2.0, 3.0)):seed_metric(team_id=self.team.id,@@ -439,12 +434,7 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):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.metric_series`- (where the label maps live) for each scope and assert the resolved value.- """+ """Test `attribute_field` with real `metric_series` queries."""CLASS_DATA_LEVEL_SETUP = True@@ -494,9 +484,7 @@ class TestAttributeField(ClickhouseTestMixin, APIBaseTest):])def test_service_name_resolves_to_first_class_column(self, _name: str, key: str, scope: str) -> None:- # Real ingestion extracts the service name into its own column (the- # maps carry the dotted `service.name` at best), so both spellings- # must read the column in every scope.+ # Ingestion extracts service name to a column in every scope.anchor = timezone.now().replace(microsecond=0)seed_metric(team_id=self.team.id,@@ -707,6 +695,30 @@ class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):0.0,)+ def test_window_keeps_a_series_with_samples_outside_the_range(self):+ # The filter subquery bounds `metric_series` by `last_seen`, the series'+ # newest sample. Samples on either side of the chart window must not cost+ # the series its in-window points.+ seed_metric(+ team_id=self.team.id,+ metric_name="req",+ points=[+ (self.anchor - dt.timedelta(hours=6), 3.0),+ (self.anchor - dt.timedelta(hours=2, minutes=30), 4.0),+ (self.anchor - dt.timedelta(minutes=5), 5.0),+ ],+ labels={"env": "staging", "path": "/api"},+ )+ runner = MetricQueryRunner(+ team=self.team,+ metric_name="req",+ aggregation="sum",+ date_from=self.anchor - dt.timedelta(hours=3),+ date_to=self.anchor - dt.timedelta(hours=2),+ filters=(MetricFilter(key="env", op=FilterOp.EQ, value="staging"),),+ )+ self.assertEqual(sum(row["value"] for row in runner.run()), 4.0)+def test_filters_via_api(self):response = self.client.post(f"/api/projects/{self.team.id}/metrics/query",@@ -751,8 +763,7 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):super().setUp()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.+ # `env=dev` needs zero-fill in the shared grid.seed_metric(team_id=self.team.id,metric_name="req",@@ -795,7 +806,7 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):self.assertEqual(sum(p.value for p in by_env["prod"].points), 3.0)self.assertEqual(sum(p.value for p in by_env["dev"].points), 10.0)- # dev has no data in prod's first bucket: zero-filled, not missing.+ # Zero-fill `dev` in the first bucket.self.assertIn(0.0, [p.value for p in by_env["dev"].points])def test_series_ordered_largest_first(self):@@ -804,7 +815,7 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):def test_explicit_interval_respected(self):series = self._run(interval="minute_5")- # 10-minute spread at 5m buckets: both points land in distinct buckets+ # Both points land in different five-minute buckets.by_env = {s.labels["env"]: s for s in series}self.assertEqual(len(by_env["prod"].points), len(by_env["dev"].points))@@ -832,6 +843,23 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(series[0].labels, {"k8s.pod.name": "web-1"})+ def test_group_labels_survive_a_series_with_samples_outside_the_range(self):+ # The label join bounds `metric_series` by `last_seen` too. Dropping a+ # series with data in the window would regroup it under an empty label.+ seed_metric(+ team_id=self.team.id,+ metric_name="req",+ points=[+ (self.anchor - dt.timedelta(hours=6), 5.0),+ (self.anchor - dt.timedelta(hours=2, minutes=30), 6.0),+ (self.anchor - dt.timedelta(minutes=5), 7.0),+ ],+ labels={"env": "staging"},+ )+ series = self._run(date_from=self.anchor - dt.timedelta(hours=3), date_to=self.anchor - dt.timedelta(hours=2))+ self.assertEqual([s.labels["env"] for s in series], ["staging"])+ self.assertEqual(sum(p.value for p in series[0].points), 6.0)+def test_group_by_via_api(self):response = self.client.post(f"/api/projects/{self.team.id}/metrics/query",@@ -864,7 +892,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):def setUp(self):super().setUp()truncate_metrics_tables()- # Anchor on a minute boundary so bucket membership is deterministic.+ # Use a minute boundary for stable bucket membership.self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)def _run(self, aggregation: str, **runner_overrides):@@ -903,7 +931,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):rows = self._run("increase")by_time = {row["time"]: row["value"] for row in rows}values = list(by_time.values())- # bucket 1: first sample contributes 0, then 5+5+5; bucket 2: 5+5+ # The first sample contributes zero.self.assertEqual(values, [15.0, 10.0])@parameterized.expand(@@ -913,8 +941,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):])def test_first_bucket_diffs_against_the_sample_before_the_range(self, aggregation: str, expected: list[float]):- # Scraped about once per bucket, which is the normal case: without a- # predecessor from before date_from the first point is a flat 0.+ # The first point needs a predecessor before `date_from`.self._seed_counter([(self.anchor - dt.timedelta(seconds=90), 100.0),@@ -925,8 +952,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):rows = self._run(aggregation)for row, expected_value in zip(rows, expected):self.assertAlmostEqual(row["value"], expected_value)- # The pre-range sample only feeds the window function; its own bucket- # must not widen the grid the chart plots.+ # The pre-range sample must not add a chart bucket.self.assertEqual(len(rows), len(expected))earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))@@ -938,9 +964,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):])def test_unaligned_date_from_still_charts_a_complete_first_bucket(self, aggregation: str, expected: list[float]):- # date_from usually lands inside a bucket (relative presets resolve to- # now-minus-offset with second precision). The first bucket must cover- # its whole interval, not just the slice after date_from.+ # The first bucket must cover its full interval.self._seed_counter([(self.anchor + dt.timedelta(seconds=s), 100.0 + s / 3.0) for s in range(-60, 181, 15)])rows = self._run(aggregation,@@ -954,10 +978,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):self.assertEqual(earliest, self.anchor)def test_bucket_with_no_computable_increase_is_dropped_not_zero(self):- # Scraped every 10 minutes: the first in-range sample's predecessor sits- # beyond counter_lookback, so its increase is unknowable. Unknown must- # be a missing point, not a plotted 0 — the histogram path already- # drops such buckets.+ # The predecessor is outside the lookback. Return a gap, not zero.start = self.anchor - dt.timedelta(minutes=self.anchor.minute % 5)self._seed_counter([@@ -997,7 +1018,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):])rows = self._run("increase")- # 0 (first) + 10 + 5 (reset: post-reset absolute value) + 10+ # The reset contributes its post-reset value.self.assertEqual([row["value"] for row in rows], [25.0])def test_delta_temporality_sums_samples_directly(self):@@ -1013,8 +1034,7 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):self.assertEqual([row["value"] for row in rows], [12.0])def test_deltas_are_computed_per_underlying_series(self):- # Two pods with interleaved timestamps; naive global diffing would- # produce garbage from the cross-series jumps.+ # Diff each pod separately.self._seed_counter([(self.anchor + dt.timedelta(seconds=0), 1000.0),@@ -1097,12 +1117,11 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):class TestHistogramQuantileInterpolation:@parameterized.expand([- # bounds [0.1, 0.5, 1.0], counts [10, 10, 10, 0] (no overflow):- # p50 -> rank 15, second bucket [0.1, 0.5], 5/10 through -> 0.3+ # p50 is 0.3 in the second bucket.("p50_mid_bucket", 0.5, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.3),- # p25 -> rank 7.5, first bucket [0, 0.1], 7.5/10 through -> 0.075+ # p25 is 0.075 in the first bucket.("p25_first_bucket", 0.25, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.075),- # rank lands in the overflow bucket -> clamp to highest bound+ # Clamp overflow ranks to the highest bound.("overflow_clamps", 0.99, [0.1, 0.5, 1.0], [1.0, 1.0, 1.0, 10.0], 1.0),("empty_counts", 0.5, [0.1, 0.5], [0.0, 0.0, 0.0], 0.0),("no_bounds", 0.5, [], [10.0], 0.0),@@ -1155,8 +1174,7 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):self._run(quantile=1.5)def test_group_by_service_name_column(self):- # service_name resolves to the raw column, which the nested- # per-series subqueries must propagate to the outer group-by.+ # Pass `service_name` to the outer group-by.self._seed_histogram([(self.anchor, [10, 0, 0, 0])], temporality="delta", service_name="svc-a")self._seed_histogram([(self.anchor, [0, 0, 10, 0])], temporality="delta", service_name="svc-b")rows = self._run(group_by=(MetricGroupBy(key="service_name"),))@@ -1171,12 +1189,12 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):temporality="delta",)rows = self._run(0.5)- # combined counts [20, 20, 20, 0]: rank 30, mid of second bucket+ # The combined p50 is the second-bucket midpoint.self.assertEqual(len(rows), 1)self.assertAlmostEqual(rows[0]["value"], 0.3)def test_cumulative_histogram_diffs_per_series(self):- # Cumulative counts grow; first sample contributes nothing.+ # The first cumulative sample contributes nothing.self._seed_histogram([(self.anchor + dt.timedelta(seconds=0), [100, 100, 100, 0]),@@ -1185,21 +1203,18 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):temporality="cumulative",)rows = self._run(0.5)- # window contribution [10, 10, 10, 0] -> p50 = 0.3+ # The window p50 is 0.3.self.assertEqual(len(rows), 1)self.assertAlmostEqual(rows[0]["value"], 0.3)def test_cumulative_lone_sample_emits_no_point(self):- # A cumulative histogram's first (and only) sample has no predecessor- # to diff against — the window has no computable increase. That must- # be a gap, not a fabricated p95 of 0 (which reads as "p95 is 0s").+ # The histogram has no predecessor. Return a gap, not zero.self._seed_histogram([(self.anchor, [1, 1, 1, 0])], temporality="cumulative")rows = self._run(0.95)self.assertEqual(rows, [])def test_first_bucket_diffs_against_the_histogram_before_the_range(self):- # Same missing-predecessor defect as the counter functions, but here it- # drops the point entirely rather than plotting a zero.+ # A missing predecessor drops the histogram point.self._seed_histogram([(self.anchor - dt.timedelta(seconds=90), [100, 100, 100, 0]),@@ -1214,9 +1229,7 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))def test_unaligned_date_from_keeps_the_first_buckets_full_distribution(self):- # Growth recorded before date_from but inside the first bucket is part- # of that bucket's distribution; clipping at date_from skews the- # quantile toward whatever happened to grow last.+ # Include growth from the first partial bucket.self._seed_histogram([(self.anchor, [100, 100, 100, 0]),@@ -1231,7 +1244,7 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):date_to=self.anchor + dt.timedelta(minutes=1),)self.assertEqual(len(rows), 1)- # Window contribution [10, 10, 0, 0]: p50 sits in the first bucket.+ # The window p50 is in the first bucket.self.assertAlmostEqual(rows[0]["value"], 0.1)earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)self.assertEqual(earliest, self.anchor)@@ -1324,7 +1337,7 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):super().setUp()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)+ # Use per-minute error and request buckets.seed_metric(team_id=self.team.id,metric_name="errors",@@ -1474,8 +1487,7 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):- """One metric name existing as several types (e.g. a counter and a gauge)- must not blend into one aggregate — series identity includes the type."""+ """Test type isolation for metrics with the same name."""CLASS_DATA_LEVEL_SETUP = True@@ -1483,7 +1495,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):super().setUp()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).+ # Use one counter and one gauge with the same name.seed_metric(team_id=self.team.id,metric_name="m_collide",@@ -1512,7 +1524,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):@parameterized.expand([- # Without isolation these blended: avg was (5 + 42) / 2 = 23.5.+ # Metric types must not blend.("gauge_avg", "avg", "gauge", 42.0),("counter_sum", "sum", "sum", 5.0),("counter_increase", "increase", "sum", 5.0),@@ -1523,7 +1535,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):assert [row["value"] for row in rows] == [expected]def test_without_type_filter_all_rows_still_match(self):- # Back-compat: no metric_type keeps the pre-filter behavior.+ # No metric type keeps the previous behavior.rows = self._run("count", None)assert [row["value"] for row in rows] == [2]@@ -1541,10 +1553,10 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):histogram_bounds=[10.0, 50.0, 100.0],histogram_counts=[0, 10, 0, 0],)- # No explicit type needed: the histogram path must constrain itself.+ # Histogram queries constrain their metric type.rows = self._run("histogram_quantile", None, quantile=0.5)assert len(rows) == 1- # All 10 observations sit in the (10, 50] bucket; p50 interpolates to 30.+ # p50 interpolates to 30 in the `(10, 50]` bucket.assert abs(rows[0]["value"] - 30.0) < 1e-9def test_api_accepts_metric_type(self):@@ -1567,10 +1579,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):- """ClickHouse float aggregates can overflow to inf (two 1e308 series in- one bucket). A Python `inf` leaking into the response is at best invalid- JSON ("Infinity") and at worst a silent null downstream — the API contract- is an explicit null gap instead."""+ """Test null gaps for non-finite aggregates."""CLASS_DATA_LEVEL_SETUP = True@@ -1580,8 +1589,7 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)def _seed_huge(self, count: int) -> None:- # One series each: aggregation is across series, so repeated samples of- # a single series would collapse to one value and never overflow.+ # Use two series. Repeated samples collapse to one value.for index in range(count):seed_metric(team_id=self.team.id,@@ -1647,9 +1655,7 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):assert values == [None]def test_formula_propagates_clause_null_gap(self):- # Two 1e308 points sum to inf, so the CLAUSE aggregate is already a- # null gap before the formula runs — exercising the input-None guard- # in _evaluate_formula_point, not the formula-overflow branch above.+ # The clause sum overflows before formula evaluation.self._seed_huge(2)response = self.client.post(f"/api/projects/{self.team.id}/metrics/query",