Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(metrics): expose metric series labels to HogQL via a lazy join (#102390)

Daniel Viscaa98935aaa2e3
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.py
index 39eab247c305..d9c41970775e 100644
--- a/posthog/hogql/database/lazy_join_registry.py
+++ b/posthog/hogql/database/lazy_join_registry.py
@@ -10,6 +10,7 @@ from posthog.hogql.database.schema.error_tracking_issue_fingerprint_overrides im
)
from posthog.hogql.database.schema.groups import join_with_group_n_table
from posthog.hogql.database.schema.groups_revenue_analytics import join_with_groups_revenue_analytics_table
+from posthog.hogql.database.schema.metrics import join_metrics_with_metric_series_table
from posthog.hogql.database.schema.person_distinct_id_overrides import join_with_person_distinct_id_overrides_table
from posthog.hogql.database.schema.person_distinct_ids import join_with_person_distinct_ids_table
from posthog.hogql.database.schema.persons import join_with_persons_table
@@ -71,6 +72,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {
tags.PERSON_DISTINCT_ID_OVERRIDES: join_with_person_distinct_id_overrides_table,
tags.GROUP_N: join_with_group_n_table,
tags.GROUPS_REVENUE_ANALYTICS: join_with_groups_revenue_analytics_table,
+ tags.METRICS_TO_METRIC_SERIES: join_metrics_with_metric_series_table,
tags.PERSONS_REVENUE_ANALYTICS: join_with_persons_revenue_analytics_table,
tags.EVENTS_TO_SESSIONS_V1: join_events_table_to_sessions_table,
tags.EVENTS_TO_SESSIONS_V2: join_events_table_to_sessions_table_v2,
diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.py
index 4a6b6af64b5c..24f72553fbf8 100644
--- a/posthog/hogql/database/lazy_join_tags.py
+++ b/posthog/hogql/database/lazy_join_tags.py
@@ -21,6 +21,7 @@ REPLAY_TO_SESSIONS_V2 = "replay_to_sessions_v2"
REPLAY_TO_SESSIONS_V3 = "replay_to_sessions_v3"
REPLAY_TO_EVENTS = "replay_to_events"
REPLAY_TO_CONSOLE_LOGS = "replay_to_console_logs"
+METRICS_TO_METRIC_SERIES = "metrics_to_metric_series"
ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES = "error_tracking_issue_fingerprint_overrides"
ERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state"
TICKET_TAGS = "ticket_tags"
diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.py
index 924f3d3093fa..ef6699a07859 100644
--- a/posthog/hogql/database/schema/metrics.py
+++ b/posthog/hogql/database/schema/metrics.py
@@ -1,3 +1,9 @@
+import datetime as dt
+
+from posthog.hogql import ast
+from posthog.hogql.ast import JoinExpr, SelectQuery
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import METRICS_TO_METRIC_SERIES
from posthog.hogql.database.models import (
BooleanDatabaseField,
DANGEROUS_NoTeamIdCheckTable,
@@ -8,6 +14,8 @@ from posthog.hogql.database.models import (
FloatDatabaseField,
IntegerArrayDatabaseField,
IntegerDatabaseField,
+ LazyJoin,
+ LazyJoinToAdd,
MapStringDatabaseField,
StringArrayDatabaseField,
StringDatabaseField,
@@ -15,6 +23,8 @@ from posthog.hogql.database.models import (
Table,
UnknownDatabaseField,
)
+from posthog.hogql.errors import ResolutionError
+from posthog.hogql.visitor import clone_expr
from posthog.clickhouse.workload import Workload
@@ -102,6 +112,15 @@ class MetricsTable(Table):
nullable=False,
description="True when the ingested record carried the series labels; only such records write `metric_series` and `metric_attributes` rows.",
),
+ "series": LazyJoin(
+ from_field=["series_fingerprint"],
+ join_table="posthog.metric_series",
+ resolver=METRICS_TO_METRIC_SERIES,
+ description=(
+ "The metric's series (label set), joined from `metric_series` on `series_fingerprint`. "
+ "Read labels as `series.attributes['key']` and `series.resource_attributes['key']`."
+ ),
+ ),
}
def to_printed_clickhouse(self, context):
@@ -342,6 +361,192 @@ class MetricAttributesTable(Table):
return "metric_attributes"
+# `last_seen` is the ReplacingMergeTree version column, so `max` picks the row FINAL would keep.
+# `time_bucket` is the hour of `last_seen`, and `original_expiry_timestamp` is the series TTL. Both
+# also move forward between versions.
+_MAX_FIELDS = frozenset({"last_seen", "time_bucket", "original_expiry_timestamp"})
+
+# Not inputs to the series fingerprint, so a re-ingested series can change them between duplicate
+# rows; `any()` could return the stale version. `argMax(field, last_seen)` takes them from the newest.
+_ARGMAX_FIELDS = frozenset({"unit", "aggregation_temporality", "is_monotonic", "instrumentation_scope"})
+
+# Buffer subtracted from a pushed-down time lower bound, mirroring `_SERIES_LAST_SEEN_BUFFER` in
+# products.metrics.backend.metric_query_runner — the same margin the Viewer's own series reads use
+# for delayed series updates. Duplicated here rather than imported: core hogql cannot depend on the
+# product module (tach boundary).
+_SERIES_LAST_SEEN_BUFFER = dt.timedelta(hours=1)
+
+_TIME_LOWER_BOUND_OPS = frozenset({ast.CompareOperationOp.Gt, ast.CompareOperationOp.GtEq})
+
+# Alias of metric_series inside the join subquery. Each aggregate there is aliased with its source
+# field's name, and HogQL resolves SELECT aliases before columns, so every source field reference
+# must carry this qualifier or it would resolve to the aggregate.
+_SERIES_SOURCE_ALIAS = "metric_series_source"
+
+
+def _outer_metrics_column(expr: ast.Expr, from_table: str, context: HogQLContext) -> str | None:
+ """Resolve an expression to a column name on the outer (metrics) table.
+
+ Accepts an optional leading table qualifier (`metrics.timestamp` or bare `timestamp`) and
+ verifies via the resolved FieldType that the field is that column of a MetricsTable. A field on
+ another joined table, or a SELECT alias that shadows a column name, is never captured.
+ """
+ field = expr.expr if isinstance(expr, ast.Alias) else expr
+ if not isinstance(field, ast.Field):
+ return None
+ chain = list(field.chain)
+ if chain and chain[0] == from_table:
+ chain = chain[1:]
+ if len(chain) != 1 or not isinstance(chain[0], str):
+ return None
+ field_type = field.type
+ if not isinstance(field_type, ast.FieldType) or field_type.name != chain[0]:
+ return None
+ if not isinstance(field_type.table_type, ast.BaseTableType):
+ return None
+ if not isinstance(field_type.table_type.resolve_database_table(context), MetricsTable):
+ return None
+ return chain[0]
+
+
+def _is_column_free(expr: ast.Expr) -> bool:
+ """True when the expression reads no column, so its value is the same for every row."""
+ if isinstance(expr, ast.Constant):
+ return True
+ if isinstance(expr, ast.ArithmeticOperation):
+ return _is_column_free(expr.left) and _is_column_free(expr.right)
+ if isinstance(expr, ast.Call):
+ return all(_is_column_free(arg) for arg in [*expr.args, *(expr.params or [])])
+ return False
+
+
+def _series_source_field(name: str) -> ast.Field:
+ return ast.Field(chain=[_SERIES_SOURCE_ALIAS, name])
+
+
+def _series_pushdown_where(node: SelectQuery, from_table: str, context: HogQLContext) -> ast.Expr | None:
+ """Extract reductive bounds from the outer WHERE into the metric_series subquery.
+
+ Two shapes, both semantics-preserving on the join key:
+
+ - `metric_name = <constant>` / `IN (<constants>)`: metric_name is an input to the series
+ fingerprint, so every series row for a fingerprint carries the same metric_name, and it is
+ the sort-key prefix of metric_series — the bound becomes a primary-key range read.
+ - `timestamp > / >= <column-free expression>` (a constant, or a rolling window such as
+ `now() - INTERVAL 1 HOUR`): a series last seen before the window (minus the one-hour buffer
+ the Viewer's own series reads use for delayed updates) can have no points in it. Rewritten
+ to `last_seen >= bound - buffer`.
+
+ Fails open: OR terms, comparisons that read a column, aliases, and fields on other tables are
+ ignored, and the outer WHERE is left untouched (the join is LEFT, so over-selecting in the
+ subquery is always safe; under-selecting is not).
+ """
+ if node.where is None:
+ return None
+
+ def flatten_and(expr: ast.Expr) -> list[ast.Expr]:
+ # The parser produces nested ast.And; the printer may emit and(...) calls. Handle both.
+ if isinstance(expr, ast.And):
+ return [t for sub in expr.exprs for t in flatten_and(sub)]
+ if isinstance(expr, ast.Call) and expr.name == "and":
+ return [t for sub in expr.args for t in flatten_and(sub)]
+ return [expr]
+
+ pushed: list[ast.Expr] = []
+ for term in flatten_and(node.where):
+ if not isinstance(term, ast.CompareOperation):
+ continue
+ column = _outer_metrics_column(term.left, from_table, context)
+ if column == "metric_name":
+ if term.op == ast.CompareOperationOp.Eq and isinstance(term.right, ast.Constant):
+ push = True
+ elif term.op == ast.CompareOperationOp.In and isinstance(term.right, ast.Array | ast.Tuple):
+ push = all(isinstance(arg, ast.Constant) for arg in term.right.exprs)
+ else:
+ push = False
+ if push:
+ pushed.append(
+ ast.CompareOperation(
+ op=term.op,
+ left=_series_source_field("metric_name"),
+ right=clone_expr(term.right, clear_types=True, clear_locations=True),
+ )
+ )
+ elif column == "timestamp" and term.op in _TIME_LOWER_BOUND_OPS:
+ if not _is_column_free(term.right):
+ continue
+ bound = ast.Call(name="toDateTime", args=[clone_expr(term.right, clear_types=True, clear_locations=True)])
+ pushed.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=_series_source_field("last_seen"),
+ right=ast.Call(
+ name="minus",
+ args=[
+ # DateTime is unsigned, so the buffer would wrap a bound near the epoch to 2106.
+ ast.Call(name="toDateTime64", args=[bound, ast.Constant(value=6)]),
+ ast.Call(
+ name="toIntervalHour",
+ args=[ast.Constant(value=int(_SERIES_LAST_SEEN_BUFFER.total_seconds() // 3600))],
+ ),
+ ],
+ ),
+ )
+ )
+ if not pushed:
+ return None
+ return pushed[0] if len(pushed) == 1 else ast.Call(name="and", args=pushed)
+
+
+def join_metrics_with_metric_series_table(
+ join_to_add: LazyJoinToAdd,
+ context: HogQLContext,
+ node: SelectQuery,
+) -> JoinExpr:
+ if not join_to_add.fields_accessed:
+ raise ResolutionError("No fields requested from metric_series")
+
+ # Deduplicate metric_series to one row per fingerprint so the join can't fan out the metrics rows.
+ # team_id is added by HogQL's automatic team scoping on the subquery. The outer WHERE's
+ # metric_name/time bounds are pushed in so the subquery doesn't aggregate every series the
+ # team has before the outer filters apply.
+ inner_select = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="series_fingerprint", expr=_series_source_field("series_fingerprint")),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "metric_series"]), alias=_SERIES_SOURCE_ALIAS),
+ where=_series_pushdown_where(node, join_to_add.from_table, context),
+ group_by=[_series_source_field("series_fingerprint")],
+ )
+ for field_name, field_chain in join_to_add.fields_accessed.items():
+ # series_fingerprint is already selected as the join key.
+ if field_name == "series_fingerprint":
+ continue
+ # Everything else (labels, metric_type, service_name) is an input to the fingerprint, so every
+ # duplicate of one series agrees on it and `any()` cannot return a stale value.
+ field = ast.Field(chain=[_SERIES_SOURCE_ALIAS, *field_chain])
+ if field_name in _MAX_FIELDS:
+ aggregate = ast.Call(name="max", args=[field])
+ elif field_name in _ARGMAX_FIELDS:
+ aggregate = ast.Call(name="argMax", args=[field, _series_source_field("last_seen")])
+ else:
+ aggregate = ast.Call(name="any", args=[field])
+ inner_select.select.append(ast.Alias(alias=field_name, expr=aggregate))
+
+ join_expr = ast.JoinExpr(table=inner_select)
+ join_expr.join_type = "LEFT JOIN"
+ join_expr.alias = join_to_add.to_table
+ join_expr.constraint = ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=[join_to_add.from_table, "series_fingerprint"]),
+ right=ast.Field(chain=[join_to_add.to_table, "series_fingerprint"]),
+ ),
+ constraint_type="ON",
+ )
+ return join_expr
+
+
class MetricsKafkaMetricsTable(DANGEROUS_NoTeamIdCheckTable):
"""
Table stores meta information about kafka consumption _not_ scoped to teams
diff --git a/posthog/hogql/database/schema/test/test_metrics.py b/posthog/hogql/database/schema/test/test_metrics.py
new file mode 100644
index 000000000000..71086185cb56
--- /dev/null
+++ b/posthog/hogql/database/schema/test/test_metrics.py
@@ -0,0 +1,281 @@
+import datetime as dt
+from typing import Optional, cast
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.query import HogQLQueryExecutor, execute_hogql_query
+from posthog.hogql.resolver import resolve_types
+
+from products.metrics.backend.facade.testing import seed_metric, truncate_metrics_tables
+
+METRICS_TABLE = "posthog.metrics"
+
+
+class TestMetricsSeriesJoin(ClickhouseTestMixin, APIBaseTest):
+ def _select(self, query: str, placeholders: Optional[dict[str, ast.Expr]] = None) -> ast.SelectQuery:
+ return cast(ast.SelectQuery, parse_select(query, placeholders=placeholders))
+
+ def _print_clickhouse(self, query: str) -> str:
+ node = self._select(query)
+ return prepare_and_print_ast(
+ node,
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ dialect="clickhouse",
+ )[0]
+
+ def _database(self):
+ from posthog.hogql.database.database import Database
+ from posthog.hogql.modifiers import create_default_modifiers_for_team
+
+ modifiers = create_default_modifiers_for_team(self.team)
+ sources = Database._fetch_sources(team=self.team, modifiers=modifiers)
+ return Database._build_from_sources(sources)
+
+ def test_metrics_table_exposes_series_lazy_join(self):
+ metrics_table = self._database().get_table("posthog.metrics")
+ assert "series" in metrics_table.fields, "metrics table must expose a `series` field joining metric_series"
+
+ @parameterized.expand(["attributes", "resource_attributes"])
+ def test_select_series_label_map_joins_metric_series(self, label_map: str):
+ sql = self._print_clickhouse(f"SELECT series.{label_map} FROM {METRICS_TABLE} LIMIT 10")
+ assert "metrics4_series" in sql, f"expected a join against metrics4_series, got:\n{sql}"
+ assert label_map in sql
+ assert sql.replace(" ", "").count("series_fingerprint") >= 2
+
+ def test_execute_query_grouping_by_label(self):
+ # End to end: a query that groups metric data points by a label key must run.
+ executor = HogQLQueryExecutor(
+ query=f"SELECT series.attributes['service.name'] AS svc, count() FROM {METRICS_TABLE} GROUP BY svc LIMIT 10",
+ team=self.team,
+ query_type="HogQLQuery",
+ )
+ sql, _context = executor.generate_clickhouse_sql()
+ assert "metrics4_series" in sql
+ assert "attributes" in sql
+
+ def test_end_to_end_group_by_label_returns_seeded_label(self):
+ # Seed a metric whose series carries a `route` label, then group data points by it through
+ # the lazy join. This is the exact thing the SQL explorer customer could not do.
+ truncate_metrics_tables()
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="http_requests_total",
+ metric_type="sum",
+ service_name="web",
+ points=[(dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC), 1.0)],
+ labels={"route": "/checkout"},
+ )
+ response = execute_hogql_query(
+ f"SELECT series.attributes['route'] AS route, count() AS c "
+ f"FROM {METRICS_TABLE} WHERE metric_name = 'http_requests_total' GROUP BY route",
+ self.team,
+ )
+ routes = {row[0] for row in response.results}
+ assert "/checkout" in routes, f"expected the seeded route label, got: {response.results}"
+
+ def test_metric_name_filter_is_pushed_into_the_series_subquery(self):
+ # metric_name is a fingerprint input and the sort-key prefix of metric_series, so bounding the
+ # subquery by it is semantics-preserving and turns the read into a primary-key range scan.
+ sql = self._print_clickhouse(
+ f"SELECT series.attributes FROM {METRICS_TABLE} WHERE metric_name = 'cpu_seconds_total' LIMIT 10"
+ )
+ subquery = sql.split("LEFT JOIN (", 1)[1]
+ assert "metric_name" in subquery, f"expected metric_name bound inside the join subquery, got:\n{sql}"
+
+ @parameterized.expand(
+ [
+ ("constant", "'2026-09-16 00:00:00'"),
+ ("rolling_window", "now() - INTERVAL 1 HOUR"),
+ ("nested_rolling_window", "toStartOfDay(now()) - INTERVAL 7 DAY"),
+ ]
+ )
+ def test_time_lower_bound_is_pushed_into_the_series_subquery_as_last_seen(self, _name: str, bound: str):
+ # A series last seen before the window cannot have points in it. The pushed bound is
+ # last_seen >= timestamp - buffer (the Viewer's `_active_since_expr` shape).
+ sql = self._print_clickhouse(
+ f"SELECT series.attributes FROM {METRICS_TABLE} "
+ f"WHERE metric_name = 'cpu_seconds_total' AND timestamp > {bound} LIMIT 10"
+ )
+ subquery = sql.split("LEFT JOIN (", 1)[1].split("GROUP BY", 1)[0]
+ assert "greaterOrEquals(" in subquery and "timestamp" in subquery and "toIntervalHour(1)" in subquery, (
+ f"expected last_seen >= <bound - 1h> inside the subquery, got:\n{sql}"
+ )
+
+ @parameterized.expand(
+ [
+ # An OR term mixing a metric filter with something else must leave the subquery unbounded.
+ (
+ "or_term",
+ f"SELECT series.attributes FROM {METRICS_TABLE} "
+ f"WHERE metric_name = 'cpu_seconds_total' OR metric_name = 'disk_bytes' LIMIT 10",
+ ),
+ # A select alias that shadows `metric_name` filters a different column.
+ (
+ "shadowing_alias",
+ f"SELECT service_name AS metric_name, series.attributes FROM {METRICS_TABLE} "
+ f"WHERE metric_name = 'web' LIMIT 10",
+ ),
+ ]
+ )
+ def test_unsafe_filter_is_not_pushed_into_the_series_subquery(self, _name: str, query: str):
+ # Failing open: pushing these would drop series rows the outer query still needs.
+ sql = self._print_clickhouse(query)
+ subquery = sql.split("LEFT JOIN (", 1)[1].split("GROUP BY", 1)[0]
+ assert "metric_name" not in subquery, f"filter must not be pushed down, got:\n{sql}"
+
+ @parameterized.expand(
+ [
+ ("constant", "timestamp > '2026-09-16 00:00:00'"),
+ # ClickHouse DateTime is unsigned, so subtracting the buffer from the epoch must not wrap.
+ ("epoch", "timestamp >= toDateTime(0)"),
+ ("rolling_window", "timestamp >= now() - INTERVAL 1 HOUR"),
+ ]
+ )
+ def test_pushdown_preserves_results_end_to_end(self, _name: str, time_filter: str):
+ # A pushed-down bound must keep the labels of every series that has points in the window.
+ truncate_metrics_tables()
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cpu_seconds_total",
+ metric_type="sum",
+ service_name="web",
+ # Relative to the real clock: ClickHouse evaluates now() itself.
+ points=[(dt.datetime.now(tz=dt.UTC) - dt.timedelta(minutes=10), 1.0)],
+ labels={"route": "/checkout"},
+ )
+ response = execute_hogql_query(
+ f"SELECT series.attributes['route'] AS route, count() AS c FROM {METRICS_TABLE} "
+ f"WHERE metric_name = 'cpu_seconds_total' AND {time_filter} GROUP BY route",
+ self.team,
+ )
+ assert response.results == [("/checkout", 1)], f"unexpected results: {response.results}"
+
+ @parameterized.expand(["last_seen", "time_bucket", "original_expiry_timestamp"])
+ def test_version_varying_fields_use_max_not_any_across_duplicate_versions(self, field: str):
+ # These fields move forward with each new version of a series. `any()` could return a stale
+ # duplicate, so they must be `max`.
+ sql = self._print_clickhouse(f"SELECT series.{field} FROM {METRICS_TABLE} LIMIT 10")
+ assert "max(" in sql, f"expected max() for {field}, got:\n{sql}"
+ assert "any(" not in sql, f"{field} must not use any(), got:\n{sql}"
+
+ def test_label_fields_use_any_since_labels_are_constant_within_a_series(self):
+ # Labels are inputs to the fingerprint, so every duplicate of one series agrees on them; `any()`
+ # cannot return a stale label and is the codebase-sanctioned dedup for label maps.
+ sql = self._print_clickhouse(f"SELECT series.attributes FROM {METRICS_TABLE} LIMIT 10")
+ assert "any(" in sql, f"expected any() for the constant label map, got:\n{sql}"
+
+ @parameterized.expand(["unit", "aggregation_temporality", "is_monotonic", "instrumentation_scope"])
+ def test_mutable_metadata_uses_argmax_on_last_seen(self, field: str):
+ # These fields are NOT inputs to the series fingerprint, so a re-ingested series can change
+ # them. `any()` could return the stale duplicate, so they must be taken from the newest version.
+ sql = self._print_clickhouse(f"SELECT series.{field} FROM {METRICS_TABLE} LIMIT 10")
+ assert "argMax(" in sql, f"expected argMax() for mutable {field}, got:\n{sql}"
+ assert "timestamp" in sql, f"argMax must order by the sample timestamp, got:\n{sql}"
+
+ def test_end_to_end_last_seen_reflects_latest_series_version(self):
+ # Two samples of one series create two metric_series rows (version column `last_seen`). The join
+ # must surface the newest, not whichever duplicate the unmerged parts happen to return first.
+ truncate_metrics_tables()
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cpu_seconds_total",
+ metric_type="sum",
+ service_name="web",
+ points=[
+ (dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC), 1.0),
+ (dt.datetime(2026, 9, 16, 0, 0, 0, tzinfo=dt.UTC), 2.0),
+ ],
+ labels={"route": "/checkout"},
+ )
+ response = execute_hogql_query(
+ f"SELECT max(series.last_seen) AS latest FROM {METRICS_TABLE} WHERE metric_name = 'cpu_seconds_total'",
+ self.team,
+ )
+ latest = response.results[0][0]
+ assert latest.replace(tzinfo=dt.UTC) >= dt.datetime(2026, 9, 16, tzinfo=dt.UTC), (
+ f"expected the latest duplicate's last_seen, got {latest}"
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "last_seen_with_time_filter",
+ "SELECT series.last_seen FROM {table} "
+ "WHERE metric_name = 'cpu_seconds_total' AND timestamp >= '2026-09-16 00:00:00'",
+ [(dt.datetime(2026, 9, 16, 1, 0, 0, tzinfo=dt.UTC),)],
+ ),
+ (
+ "metric_name_with_metric_name_filter",
+ "SELECT series.metric_name FROM {table} WHERE metric_name = 'cpu_seconds_total'",
+ [("cpu_seconds_total",)],
+ ),
+ (
+ "last_seen_before_unit",
+ "SELECT series.last_seen, series.unit FROM {table} WHERE metric_name = 'cpu_seconds_total'",
+ [(dt.datetime(2026, 9, 16, 1, 0, 0, tzinfo=dt.UTC), "s")],
+ ),
+ ]
+ )
+ def test_end_to_end_series_fields_do_not_collide_with_aggregate_aliases(
+ self, _name: str, query: str, expected: list[tuple]
+ ):
+ # The join subquery aliases each aggregate with its source field's name. A pushed predicate or
+ # an argMax argument that resolves to one of those aliases nests an aggregate in an aggregate.
+ truncate_metrics_tables()
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cpu_seconds_total",
+ metric_type="sum",
+ service_name="web",
+ unit="s",
+ points=[(dt.datetime(2026, 9, 16, 1, 0, 0, tzinfo=dt.UTC), 1.0)],
+ labels={"route": "/checkout"},
+ )
+ response = execute_hogql_query(query.format(table=METRICS_TABLE), self.team)
+ results = [
+ tuple(v.replace(tzinfo=dt.UTC) if isinstance(v, dt.datetime) else v for v in row)
+ for row in response.results
+ ]
+ assert results == expected
+
+ def test_end_to_end_mutable_metadata_reflects_latest_series_version(self):
+ # Same labels (same fingerprint) re-ingested with a new unit produce two duplicate series rows.
+ # The join must surface the unit from the newest version, not the stale one.
+ truncate_metrics_tables()
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="disk_bytes",
+ metric_type="gauge",
+ service_name="web",
+ unit="By",
+ points=[(dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC), 1.0)],
+ labels={"host": "a"},
+ )
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="disk_bytes",
+ metric_type="gauge",
+ service_name="web",
+ unit="KiBy",
+ points=[(dt.datetime(2026, 9, 16, 0, 0, 0, tzinfo=dt.UTC), 2.0)],
+ labels={"host": "a"},
+ )
+ response = execute_hogql_query(
+ f"SELECT DISTINCT series.unit FROM {METRICS_TABLE} WHERE metric_name = 'disk_bytes'",
+ self.team,
+ )
+ units = {row[0] for row in response.results}
+ assert units == {"KiBy"}, f"expected the latest version's unit, got: {units}"
+
+ def test_resolver_resolves_series_field_type(self):
+ database = self._database()
+ node = self._select(f"SELECT series.attributes FROM {METRICS_TABLE}")
+ context = HogQLContext(database=database, team_id=self.team.pk, enable_select_queries=True)
+ resolved = resolve_types(node, context, dialect="clickhouse")
+ assert resolved is not None
diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.py
index 521b9286dee7..4f86d3012524 100644
--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py
+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py
@@ -232,6 +232,7 @@ class TestLazyJoinManifest(SimpleTestCase):
"foreign_key",
"group_n",
"groups_revenue_analytics",
+ "metrics_to_metric_series",
"person_distinct_id_overrides",
"person_distinct_ids",
"persons",
diff --git a/products/metrics/backend/facade/testing.py b/products/metrics/backend/facade/testing.py
index 742f26873eb8..f342a3a1c71f 100644
--- a/products/metrics/backend/facade/testing.py
+++ b/products/metrics/backend/facade/testing.py
@@ -5,6 +5,6 @@ they never import metrics internals; the seeder writes rows shaped like real
ingest output directly into ClickHouse.
"""
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
-__all__ = ["seed_metric"]
+__all__ = ["seed_metric", "truncate_metrics_tables"]