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): label filters with explicit resource/attribute/auto scope (P3) (#63125)

Daniel Viscacc359ceab1d0
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 747dca874bf3..f43fd6f7467e 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -46,8 +46,6 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
raise ValueError("explicit intervals are not supported yet")
clause = request.clauses[0]
- if clause.filters:
- raise ValueError("filters are not supported yet")
if clause.group_by:
raise ValueError("group_by is not supported yet")
@@ -64,6 +62,7 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
aggregation=runner_aggregation,
date_from=request.date_from,
date_to=request.date_to,
+ filters=clause.filters,
)
points = tuple(MetricPoint(time=row["time"], value=row["value"]) for row in runner.run())
return [MetricSeries(labels={}, points=points, metric_name=clause.metric_name, clause=clause.name)]
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 0636cc99aab6..a0b70f1176d4 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -9,6 +9,7 @@ pipeline yet.
"""
import datetime as dt
+from collections.abc import Sequence
from typing import Any, Literal
from posthog.hogql import ast
@@ -18,6 +19,9 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
+from products.metrics.backend.facade.contracts import MetricFilter
+from products.metrics.backend.facade.enums import FilterOp
+
AttributeScope = Literal["resource", "attribute", "auto"]
_ALLOWED_ATTRIBUTE_SCOPES: frozenset[str] = frozenset({"resource", "attribute", "auto"})
@@ -120,6 +124,35 @@ def _interval_expr(name: str) -> ast.Call:
raise ValueError(f"Unknown interval: {name!r}")
+def _filter_condition(filter: MetricFilter) -> ast.Expr:
+ """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.
+ """
+ field = attribute_field(filter.key, scope=filter.scope.value)
+ placeholders: dict[str, ast.Expr] = {"field": field, "value": ast.Constant(value=filter.value)}
+ if filter.op == FilterOp.EQ:
+ return parse_expr("{field} = {value}", placeholders=placeholders)
+ if filter.op == FilterOp.NEQ:
+ return parse_expr("{field} != {value}", placeholders=placeholders)
+ if filter.op == FilterOp.REGEX:
+ return parse_expr("match({field}, {value})", placeholders=placeholders)
+ if filter.op == FilterOp.NOT_REGEX:
+ return parse_expr("not match({field}, {value})", placeholders=placeholders)
+ raise ValueError(f"Unsupported filter op: {filter.op!r}")
+
+
+def _filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr:
+ """AND of all filter conditions; TRUE when there are none."""
+ if not filters:
+ return ast.Constant(value=True)
+ conditions = [_filter_condition(f) for f in filters]
+ if len(conditions) == 1:
+ return conditions[0]
+ return ast.And(exprs=conditions)
+
+
class MetricQueryRunner:
def __init__(
self,
@@ -128,6 +161,7 @@ class MetricQueryRunner:
aggregation: str,
date_from: dt.datetime,
date_to: dt.datetime,
+ filters: Sequence[MetricFilter] = (),
) -> None:
if aggregation not in _ALLOWED_AGGREGATIONS:
raise ValueError(f"Unsupported aggregation: {aggregation!r}")
@@ -139,6 +173,7 @@ class MetricQueryRunner:
self.aggregation = aggregation
self.date_from = date_from
self.date_to = date_to
+ self.filters = tuple(filters)
self.interval = _pick_interval(date_from, date_to)
def run(self) -> list[dict[str, Any]]:
@@ -153,6 +188,7 @@ class MetricQueryRunner:
WHERE metric_name = {metric_name}
AND timestamp >= {date_from}
AND timestamp < {date_to}
+ AND {filters}
GROUP BY time
ORDER BY time ASC
LIMIT 10000
@@ -163,6 +199,7 @@ class MetricQueryRunner:
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
+ "filters": _filters_expr(self.filters),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index f17179828d0f..fe88e5099918 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -23,12 +23,33 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import report_user_action
from products.metrics.backend.facade.api import list_metric_names, run_metric_query, team_has_metrics
-from products.metrics.backend.facade.contracts import MetricQueryClause, MetricQueryRequest
-from products.metrics.backend.facade.enums import MetricAggregation
+from products.metrics.backend.facade.contracts import MetricFilter, MetricQueryClause, MetricQueryRequest
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
__all__ = ["MetricsViewSet"]
+class _MetricFilterSerializer(serializers.Serializer):
+ key = serializers.CharField(
+ max_length=255,
+ help_text="Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env').",
+ )
+ op = serializers.ChoiceField(
+ choices=["eq", "neq", "regex", "not_regex"],
+ default="eq",
+ help_text="Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.",
+ )
+ value = serializers.CharField(
+ allow_blank=True,
+ help_text="Value to compare against. For regex operators this is the pattern.",
+ )
+ scope = serializers.ChoiceField(
+ choices=["resource", "attribute", "auto"],
+ default="auto",
+ help_text="Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.",
+ )
+
+
class _MetricQueryBodySerializer(serializers.Serializer):
metricName = serializers.CharField(
max_length=255,
@@ -39,6 +60,12 @@ class _MetricQueryBodySerializer(serializers.Serializer):
default="sum",
help_text="Aggregation applied per time bucket.",
)
+ filters = _MetricFilterSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Label predicates ANDed together. Rows must satisfy every filter.",
+ )
dateFrom = serializers.DateTimeField(
help_text="Lower bound (inclusive) for the query range. ISO 8601.",
)
@@ -167,6 +194,16 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
else:
aggregation, quantile = MetricAggregation(aggregation_raw), None
+ filters = tuple(
+ MetricFilter(
+ key=f["key"],
+ op=FilterOp(f["op"]),
+ value=f["value"],
+ scope=AttributeScope(f["scope"]),
+ )
+ for f in query_data.get("filters") or []
+ )
+
date_to: dt.datetime = query_data.get("dateTo") or timezone.now()
try:
metric_request = MetricQueryRequest(
@@ -176,6 +213,7 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
metric_name=query_data["metricName"],
aggregation=aggregation,
quantile=quantile,
+ filters=filters,
),
),
date_from=query_data["dateFrom"],
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 64a845d2c28c..f5caeb2d6864 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -17,7 +17,7 @@ from posthog.clickhouse.client.connection import Workload
from products.metrics.backend.facade.api import run_metric_query
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
-from products.metrics.backend.facade.enums import FilterOp, MetricAggregation
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval, attribute_field
from products.metrics.backend.tests._seeder import seed_metric
@@ -346,19 +346,6 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
),
("formula", {"formula": "a / b"}),
("interval", {"interval": "minute"}),
- (
- "filters",
- {
- "clauses": (
- MetricQueryClause(
- name="a",
- metric_name="m1",
- aggregation=MetricAggregation.SUM,
- filters=(MetricFilter(key="env", op=FilterOp.EQ, value="prod"),),
- ),
- )
- },
- ),
(
"group_by",
{
@@ -381,3 +368,120 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
def test_not_yet_supported_features_raise_value_error(self, _name, overrides):
with self.assertRaises(ValueError):
run_metric_query(team=self.team, request=self._request(**overrides))
+
+
+class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ self.anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=5), 1.0)],
+ labels={"env": "prod", "path": "/api"},
+ resource_labels={"k8s.pod.name": "web-1"},
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=5), 10.0)],
+ labels={"env": "dev", "path": "/web"},
+ resource_labels={"k8s.pod.name": "web-2"},
+ )
+
+ def _total(self, filters: tuple[MetricFilter, ...]) -> float:
+ runner = MetricQueryRunner(
+ team=self.team,
+ metric_name="req",
+ aggregation="sum",
+ date_from=self.anchor - dt.timedelta(hours=1),
+ date_to=self.anchor,
+ filters=filters,
+ )
+ return sum(row["value"] for row in runner.run())
+
+ @parameterized.expand(
+ [
+ ("eq_attribute", MetricFilter(key="env", op=FilterOp.EQ, value="prod"), 1.0),
+ ("neq_attribute", MetricFilter(key="env", op=FilterOp.NEQ, value="prod"), 10.0),
+ ("regex", MetricFilter(key="path", op=FilterOp.REGEX, value="^/a"), 1.0),
+ ("not_regex", MetricFilter(key="path", op=FilterOp.NOT_REGEX, value="^/a"), 10.0),
+ (
+ "eq_resource_scope",
+ MetricFilter(key="k8s.pod.name", op=FilterOp.EQ, value="web-2", scope=AttributeScope.RESOURCE),
+ 10.0,
+ ),
+ (
+ "auto_scope_falls_back_to_attribute",
+ MetricFilter(key="env", op=FilterOp.EQ, value="dev", scope=AttributeScope.AUTO),
+ 10.0,
+ ),
+ ("eq_no_match", MetricFilter(key="env", op=FilterOp.EQ, value="staging"), 0.0),
+ (
+ "neq_matches_rows_lacking_key",
+ MetricFilter(key="nonexistent", op=FilterOp.NEQ, value="x"),
+ 11.0,
+ ),
+ ]
+ )
+ def test_single_filter(self, _name, filter, expected_total):
+ self.assertEqual(self._total((filter,)), expected_total)
+
+ def test_filters_are_anded(self):
+ self.assertEqual(
+ self._total(
+ (
+ MetricFilter(key="env", op=FilterOp.EQ, value="prod"),
+ MetricFilter(key="path", op=FilterOp.EQ, value="/api"),
+ )
+ ),
+ 1.0,
+ )
+ self.assertEqual(
+ self._total(
+ (
+ MetricFilter(key="env", op=FilterOp.EQ, value="prod"),
+ MetricFilter(key="path", op=FilterOp.EQ, value="/web"),
+ )
+ ),
+ 0.0,
+ )
+
+ def test_filters_via_api(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/query",
+ data={
+ "query": {
+ "metricName": "req",
+ "aggregation": "sum",
+ "filters": [{"key": "env", "op": "eq", "value": "prod"}],
+ "dateFrom": (self.anchor - dt.timedelta(hours=1)).isoformat(),
+ "dateTo": self.anchor.isoformat(),
+ }
+ },
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ series = response.json()["results"][0]
+ self.assertEqual(sum(p["value"] for p in series["points"]), 1.0)
+
+ def test_filters_via_facade(self):
+ series = run_metric_query(
+ team=self.team,
+ request=MetricQueryRequest(
+ clauses=(
+ MetricQueryClause(
+ name="a",
+ metric_name="req",
+ aggregation=MetricAggregation.SUM,
+ filters=(MetricFilter(key="env", op=FilterOp.EQ, value="dev"),),
+ ),
+ ),
+ date_from=self.anchor - dt.timedelta(hours=1),
+ date_to=self.anchor,
+ ),
+ )
+ self.assertEqual(sum(p.value for p in series[0].points), 10.0)
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index a7eb8fbf7c3c..0ac6ebc2cfb0 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -38,6 +38,57 @@ export const AggregationEnumApi = {
P95: 'p95',
} as const
+/**
+ * * `eq` - eq
+ * * `neq` - neq
+ * * `regex` - regex
+ * * `not_regex` - not_regex
+ */
+export type OpEnumApi = (typeof OpEnumApi)[keyof typeof OpEnumApi]
+
+export const OpEnumApi = {
+ Eq: 'eq',
+ Neq: 'neq',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+} as const
+
+/**
+ * * `resource` - resource
+ * * `attribute` - attribute
+ * * `auto` - auto
+ */
+export type _MetricFilterScopeEnumApi = (typeof _MetricFilterScopeEnumApi)[keyof typeof _MetricFilterScopeEnumApi]
+
+export const _MetricFilterScopeEnumApi = {
+ Resource: 'resource',
+ Attribute: 'attribute',
+ Auto: 'auto',
+} as const
+
+export interface _MetricFilterApi {
+ /**
+ * Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env').
+ * @maxLength 255
+ */
+ key: string
+ /** Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.
+ *
+ * * `eq` - eq
+ * * `neq` - neq
+ * * `regex` - regex
+ * * `not_regex` - not_regex */
+ op?: OpEnumApi
+ /** Value to compare against. For regex operators this is the pattern. */
+ value: string
+ /** Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.
+ *
+ * * `resource` - resource
+ * * `attribute` - attribute
+ * * `auto` - auto */
+ scope?: _MetricFilterScopeEnumApi
+}
+
export interface _MetricQueryBodyApi {
/**
* Exact metric name to query (e.g. 'http.server.duration').
@@ -51,6 +102,8 @@ export interface _MetricQueryBodyApi {
* * `count` - count
* * `p95` - p95 */
aggregation?: AggregationEnumApi
+ /** Label predicates ANDed together. Rows must satisfy every filter. */
+ filters?: _MetricFilterApi[]
/** Lower bound (inclusive) for the query range. ISO 8601. */
dateFrom: string
/** Upper bound (exclusive) for the query range. Defaults to now if omitted. */
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 160a1422e751..7ba2ae36b135 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -12,6 +12,10 @@ import * as zod from 'zod'
export const metricsQueryCreateBodyQueryOneMetricNameMax = 255
export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`
+export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -27,6 +31,36 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Aggregation applied per time bucket.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95'
),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsQueryCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex')
+ .default(metricsQueryCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'\/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto')
+ .default(metricsQueryCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates ANDed together. Rows must satisfy every filter.'),
dateFrom: zod.iso
.datetime({ offset: true })
.describe('Lower bound (inclusive) for the query range. ISO 8601.'),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f68d21f302c1..cd7901adf512 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25608,6 +25608,22 @@ export namespace Schemas {
Other: 'other',
} as const;
+ /**
+ * * `eq` - eq
+ * * `neq` - neq
+ * * `regex` - regex
+ * * `not_regex` - not_regex
+ */
+ export type OpEnum = typeof OpEnum[keyof typeof OpEnum];
+
+
+ export const OpEnum = {
+ Eq: 'eq',
+ Neq: 'neq',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+ } as const;
+
/**
* * `latest` - latest
* * `earliest` - earliest
@@ -45504,6 +45520,43 @@ export namespace Schemas {
refreshing: boolean;
}
+ /**
+ * * `resource` - resource
+ * * `attribute` - attribute
+ * * `auto` - auto
+ */
+ export type _MetricFilterScopeEnum = typeof _MetricFilterScopeEnum[keyof typeof _MetricFilterScopeEnum];
+
+
+ export const _MetricFilterScopeEnum = {
+ Resource: 'resource',
+ Attribute: 'attribute',
+ Auto: 'auto',
+ } as const;
+
+ export interface _MetricFilter {
+ /**
+ * Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env').
+ * @maxLength 255
+ */
+ key: string;
+ /** Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.
+ *
+ * * `eq` - eq
+ * * `neq` - neq
+ * * `regex` - regex
+ * * `not_regex` - not_regex */
+ op?: OpEnum;
+ /** Value to compare against. For regex operators this is the pattern. */
+ value: string;
+ /** Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.
+ *
+ * * `resource` - resource
+ * * `attribute` - attribute
+ * * `auto` - auto */
+ scope?: _MetricFilterScopeEnum;
+ }
+
export interface _MetricName {
/** Metric name as it appears in the team's data. */
name: string;
@@ -45529,6 +45582,8 @@ export namespace Schemas {
* * `count` - count
* * `p95` - p95 */
aggregation?: AggregationEnum;
+ /** Label predicates ANDed together. Rows must satisfy every filter. */
+ filters?: _MetricFilter[];
/** Lower bound (inclusive) for the query range. ISO 8601. */
dateFrom: string;
/** Upper bound (exclusive) for the query range. Defaults to now if omitted. */