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.

fix(metrics): bound query cost and turn user errors into 400s (#63358)

Daniel Viscaee4bd279a1c7
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f51b2000336b..195575fccbb1 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -603,6 +603,8 @@ SPECTACULAR_SETTINGS = {
"FileFormatEnum": ["Parquet", "JSONLines"],
"MetricAttributeScopeEnum": ["resource", "attribute", "auto"],
"MetricQueryIntervalEnum": ["second", "minute", "minute_5", "minute_15", "hour", "hour_6", "day", "week"],
+ "MetricAnomalyDirectionEnum": ["up", "down", "flat"],
+ "WoWChangeDirectionEnum": ["Up", "Down"],
"BatchExportIntervalEnum": ["hour", "day", "week", "every 5 minutes", "every 15 minutes"],
"ErrorTrackingIssueOrderByEnum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],
"ErrorTrackingIssueStatusEnum": ["archived", "active", "resolved", "pending_release", "suppressed", "all"],
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index b9fc0eebbd0a..6a33ea4c3be3 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -57,17 +57,20 @@ def _assemble_series(
key = tuple(sorted(row["labels"].items()))
by_labels.setdefault(key, {})[row["time"]] = row["value"]
- series = [
+ # Rank and truncate on the sparse values BEFORE zero-filling, so a
+ # high-cardinality group-by never materializes label_sets x grid points
+ # only to throw most of them away. Zero-filled points contribute nothing
+ # to the magnitude, so the ranking is identical either way.
+ ranked = sorted(by_labels.items(), key=lambda item: (-sum(abs(v) for v in item[1].values()), item[0]))
+ return [
MetricSeries(
labels=dict(key),
points=tuple(MetricPoint(time=time, value=values.get(time, 0.0)) for time in grid),
metric_name=metric_name,
clause=clause_name,
)
- for key, values in by_labels.items()
+ for key, values in ranked[:MAX_SERIES_PER_CLAUSE]
]
- series.sort(key=lambda s: (-sum(abs(p.value) for p in s.points), tuple(sorted(s.labels.items()))))
- return series[:MAX_SERIES_PER_CLAUSE]
def _resolve_runner_aggregation(clause: MetricQueryClause) -> str:
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 27732dd29d48..0ad915b63e80 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -24,6 +24,10 @@ from dataclasses import dataclass
from .enums import AttributeScope, FilterOp, MetricAggregation
+# Each clause runs its own ClickHouse query on the shared logs cluster, so
+# the clause count per request is hard-capped.
+MAX_CLAUSES_PER_QUERY = 10
+
@dataclass(frozen=True, slots=True)
class MetricFilter:
@@ -87,6 +91,8 @@ class MetricQueryRequest:
def __post_init__(self) -> None:
if not self.clauses:
raise ValueError("at least one clause is required")
+ if len(self.clauses) > MAX_CLAUSES_PER_QUERY:
+ raise ValueError(f"at most {MAX_CLAUSES_PER_QUERY} clauses are allowed per query")
if self.date_to <= self.date_from:
raise ValueError("date_to must be after date_from")
names = [c.name for c in self.clauses]
diff --git a/products/metrics/backend/formula.py b/products/metrics/backend/formula.py
index 6acd87b327b9..ab3e71915733 100644
--- a/products/metrics/backend/formula.py
+++ b/products/metrics/backend/formula.py
@@ -37,6 +37,11 @@ def _tokenize(formula: str) -> list[_Token]:
return tokens
+# Parsing (and later evaluation) recurse once per nesting level; cap it so
+# a pathological formula raises ValueError -> 400 instead of RecursionError.
+_MAX_NESTING_DEPTH = 32
+
+
class _Parser:
"""expr := term (('+'|'-') term)* ; term := factor (('*'|'/') factor)* ;
factor := NUMBER | IDENT | '(' expr ')' | '-' factor"""
@@ -45,6 +50,7 @@ class _Parser:
self.tokens = tokens
self.position = 0
self.known_names = known_names
+ self.depth = 0
def parse(self) -> _Node:
node = self._expr()
@@ -77,24 +83,30 @@ class _Parser:
return node
def _factor(self) -> _Node:
- token = self._take()
- if token == ("op", "-"):
- return ("neg", self._factor())
- if token == ("op", "("):
- node = self._expr()
- closing = self._take()
- if closing != ("op", ")"):
- raise ValueError("Unbalanced parentheses in formula")
- return node
- if token[0] == "number":
- return ("number", float(token[1]))
- if token[0] == "ident":
- if token[1] not in self.known_names:
- raise ValueError(
- f"Unknown clause {token[1]!r} in formula; available clauses: {sorted(self.known_names)}"
- )
- return ("ident", token[1])
- raise ValueError(f"Unexpected token in formula: {token[1]!r}")
+ if self.depth >= _MAX_NESTING_DEPTH:
+ raise ValueError(f"Formula nesting is too deep (maximum {_MAX_NESTING_DEPTH} levels)")
+ self.depth += 1
+ try:
+ token = self._take()
+ if token == ("op", "-"):
+ return ("neg", self._factor())
+ if token == ("op", "("):
+ node = self._expr()
+ closing = self._take()
+ if closing != ("op", ")"):
+ raise ValueError("Unbalanced parentheses in formula")
+ return node
+ if token[0] == "number":
+ return ("number", float(token[1]))
+ if token[0] == "ident":
+ if token[1] not in self.known_names:
+ raise ValueError(
+ f"Unknown clause {token[1]!r} in formula; available clauses: {sorted(self.known_names)}"
+ )
+ return ("ident", token[1])
+ raise ValueError(f"Unexpected token in formula: {token[1]!r}")
+ finally:
+ self.depth -= 1
# AST nodes are plain tuples: ("number", float) | ("ident", str) |
diff --git a/products/metrics/backend/has_metrics_query_runner.py b/products/metrics/backend/has_metrics_query_runner.py
index b54e82667759..9d07fadfb16f 100644
--- a/products/metrics/backend/has_metrics_query_runner.py
+++ b/products/metrics/backend/has_metrics_query_runner.py
@@ -7,6 +7,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
+from posthog.errors import CHQueryErrorUnknownTable
from posthog.models import Team
HAS_METRICS_CACHE_TTL = int(dt.timedelta(days=7).total_seconds())
@@ -23,12 +24,17 @@ class HasMetricsQueryRunner:
query = parse_select("SELECT 1 FROM posthog.metrics LIMIT 1")
assert isinstance(query, ast.SelectQuery)
- response = execute_hogql_query(
- query_type="HasMetricsQuery",
- query=query,
- team=self.team,
- workload=Workload.LOGS,
- )
+ try:
+ response = execute_hogql_query(
+ query_type="HasMetricsQuery",
+ query=query,
+ team=self.team,
+ workload=Workload.LOGS,
+ )
+ except CHQueryErrorUnknownTable:
+ # The metrics tables are provisioned out-of-band per environment;
+ # an environment without them simply has no metrics yet.
+ return False
return len(response.results) > 0
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 2db45c041857..9575d98895e7 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -8,11 +8,14 @@ isn't going through HogQL `DataNode` caching, schema-gen or the data-viz
pipeline yet.
"""
+import re
import datetime as dt
from collections.abc import Sequence
from typing import Any, Literal
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -26,6 +29,27 @@ 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).
+_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.
+MAX_QUERY_SPAN = dt.timedelta(days=31)
+
+# These run on the shared logs cluster; cap how much one query may read.
+_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 `metrics1` column (extracted at
+# ingest from the `service.name` resource attribute); both spellings resolve
+# to it so filters/group-bys match real ingested rows.
+_SERVICE_NAME_KEYS: frozenset[str] = frozenset({"service_name", "service.name"})
+
def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
"""Build the HogQL AST node that accesses a metric attribute by name.
@@ -46,13 +70,21 @@ def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
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 behaviour, not a bug: it means
+ 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.
"""
if scope not in _ALLOWED_ATTRIBUTE_SCOPES:
raise ValueError(f"Unknown attribute scope: {scope!r}")
+ if name in _SERVICE_NAME_KEYS:
+ return ast.Field(chain=["service_name"])
+
name_constant = ast.Constant(value=name)
# arrayElement, not subscript: HogQL prints `field[...]` on a
@@ -160,6 +192,14 @@ def _filter_condition(filter: MetricFilter) -> ast.Expr:
that lack the key entirely — same as Prometheus negative matchers.
"""
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.
+ try:
+ re.compile(filter.value)
+ except re.error as exc:
+ raise ValueError(f"Invalid regular expression for filter {filter.key!r}: {exc}")
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)
@@ -199,8 +239,17 @@ class MetricQueryRunner:
raise ValueError(f"Unsupported aggregation: {aggregation!r}")
if date_to <= date_from:
raise ValueError("date_to must be after date_from")
+ if date_to - date_from > MAX_QUERY_SPAN:
+ raise ValueError(f"date range too wide; the maximum span is {MAX_QUERY_SPAN.days} days")
if interval is not None and interval not in {name for name, _, _ in _INTERVAL_LADDER}:
raise ValueError(f"Unknown interval: {interval!r}")
+ if interval is not None:
+ step = next(step for name, step, _ in _INTERVAL_LADDER if name == interval)
+ if (date_to - date_from) / step > _ROW_LIMIT:
+ raise ValueError(
+ f"interval {interval!r} produces more than {_ROW_LIMIT} buckets over this range; "
+ "use a coarser interval or a narrower range"
+ )
if aggregation == "histogram_quantile":
if quantile is None or not 0.0 < quantile < 1.0:
raise ValueError("histogram_quantile requires a quantile in (0, 1)")
@@ -230,7 +279,9 @@ class MetricQueryRunner:
query=query,
team=self.team,
workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ settings=_QUERY_SETTINGS,
)
+ self._raise_on_truncation(response.results)
group_count = len(self.group_by)
rows: list[dict[str, Any]] = []
@@ -255,7 +306,9 @@ class MetricQueryRunner:
query=query,
team=self.team,
workload=Workload.LOGS,
+ settings=_QUERY_SETTINGS,
)
+ self._raise_on_truncation(response.results)
group_count = len(self.group_by)
distinct_bounds = {tuple(variant) for row in response.results for variant in row[2 + group_count] if variant}
@@ -278,6 +331,16 @@ class MetricQueryRunner:
)
return rows
+ def _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."""
+ if len(results) >= _ROW_LIMIT:
+ raise ValueError(
+ "query produced too many (time bucket, group) rows; "
+ "use a coarser interval, a narrower range, or a lower-cardinality group_by"
+ )
+
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."""
@@ -302,7 +365,7 @@ class MetricQueryRunner:
AND {filters}
GROUP BY time
ORDER BY time ASC
- LIMIT 10000
+ LIMIT {row_limit}
""",
placeholders={
"interval": _interval_expr(self.interval),
@@ -311,6 +374,7 @@ class MetricQueryRunner:
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
"filters": _filters_expr(self.filters),
+ "row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -344,6 +408,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp AS sample_timestamp,
+ service_name AS service_name,
attributes AS attributes,
resource_attributes AS resource_attributes,
multiIf(
@@ -355,6 +420,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp,
+ service_name,
value,
aggregation_temporality,
attributes,
@@ -373,7 +439,7 @@ class MetricQueryRunner:
)
GROUP BY time
ORDER BY time ASC
- LIMIT 10000
+ LIMIT {row_limit}
""",
placeholders={
"interval": _interval_expr(self.interval),
@@ -382,6 +448,7 @@ class MetricQueryRunner:
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
"filters": _filters_expr(self.filters),
+ "row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -402,6 +469,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp AS sample_timestamp,
+ service_name AS service_name,
attributes AS attributes,
resource_attributes AS resource_attributes,
histogram_bounds AS histogram_bounds,
@@ -415,6 +483,7 @@ class MetricQueryRunner:
FROM (
SELECT
timestamp,
+ service_name,
aggregation_temporality,
attributes,
resource_attributes,
@@ -435,7 +504,7 @@ class MetricQueryRunner:
)
GROUP BY time
ORDER BY time ASC
- LIMIT 10000
+ LIMIT {row_limit}
""",
placeholders={
"interval": _interval_expr(self.interval),
@@ -443,6 +512,7 @@ class MetricQueryRunner:
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
"filters": _filters_expr(self.filters),
+ "row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index ca4b4076368c..a74177e12880 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -1,7 +1,7 @@
"""DRF views for the alpha metrics product.
Mirrors the shape of `products/logs/backend/api.py` so the two surfaces stay
-recognisable.
+recognizable.
"""
import datetime as dt
@@ -21,6 +21,7 @@ from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import report_user_action
+from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from products.metrics.backend.facade.api import (
characterize_metric_anomaly,
@@ -28,7 +29,13 @@ from products.metrics.backend.facade.api import (
run_metric_query,
team_has_metrics,
)
-from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
+from products.metrics.backend.facade.contracts import (
+ MAX_CLAUSES_PER_QUERY,
+ MetricFilter,
+ MetricGroupBy,
+ MetricQueryClause,
+ MetricQueryRequest,
+)
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
__all__ = ["MetricsViewSet"]
@@ -46,6 +53,7 @@ class _MetricFilterSerializer(serializers.Serializer):
)
value = serializers.CharField(
allow_blank=True,
+ max_length=1024,
help_text="Value to compare against. For regex operators this is the pattern.",
)
scope = serializers.ChoiceField(
@@ -138,10 +146,12 @@ class _MetricQueryBodySerializer(serializers.Serializer):
allow_null=True,
help_text="Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).",
)
- clauses = _MetricClauseSerializer(
+ # mypy can't see DRF's many_init routing max_length to the ListSerializer
+ clauses = _MetricClauseSerializer( # type: ignore[call-arg]
many=True,
required=False,
- help_text="Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'.",
+ max_length=MAX_CLAUSES_PER_QUERY,
+ help_text=f"Full multi-clause form: each clause is an independent metric selection sharing the request's time grid (maximum {MAX_CLAUSES_PER_QUERY}). Mutually exclusive with 'metricName'.",
)
formula = serializers.CharField(
required=False,
@@ -366,12 +376,17 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"limit",
OpenApiTypes.INT,
OpenApiParameter.QUERY,
- description="Max number of names to return. Defaults to 100, capped at 1000.",
+ description="Max number of names to return. Defaults to 100; maximum 1000.",
),
],
responses={200: _MetricNamesResponseSerializer},
)
- @action(detail=False, methods=["GET"], required_scopes=["metrics:read"])
+ @action(
+ detail=False,
+ methods=["GET"],
+ required_scopes=["metrics:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
def values(self, request: Request, *args, **kwargs) -> Response:
"""Distinct metric names for the team. Backs the picker UI."""
tag_queries(product=Product.METRICS, feature=Feature.QUERY)
@@ -391,7 +406,12 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return Response({"results": results}, status=status.HTTP_200_OK)
@extend_schema(request=_MetricQueryRequestSerializer, responses={200: _MetricQueryResponseSerializer})
- @action(detail=False, methods=["POST"], required_scopes=["metrics:read"])
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["metrics:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
def query(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=Product.METRICS, feature=Feature.QUERY)
@@ -433,7 +453,12 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return Response({"results": [asdict(s) for s in series]}, status=status.HTTP_200_OK)
@extend_schema(request=_MetricAnomalyRequestSerializer, responses={200: _MetricAnomalyReportSerializer})
- @action(detail=False, methods=["POST"], required_scopes=["metrics:read"])
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["metrics:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
def characterize(self, request: Request, *args, **kwargs) -> Response:
"""Characterize a metric anomaly: compare an anomaly window against a
baseline, find the onset, and rank which label values moved."""
diff --git a/products/metrics/backend/tests/test_contracts.py b/products/metrics/backend/tests/test_contracts.py
index 301fd2d4e7f8..26b487b34493 100644
--- a/products/metrics/backend/tests/test_contracts.py
+++ b/products/metrics/backend/tests/test_contracts.py
@@ -3,6 +3,7 @@ import datetime as dt
import pytest
from products.metrics.backend.facade.contracts import (
+ MAX_CLAUSES_PER_QUERY,
MetricFilter,
MetricGroupBy,
MetricPoint,
@@ -71,6 +72,11 @@ class TestMetricQueryRequest:
with pytest.raises(ValueError):
self._req(clauses=(_clause(name="a"), _clause(name="a", metric_name="other")))
+ def test_rejects_too_many_clauses(self):
+ clauses = tuple(_clause(name=f"c{i}") for i in range(MAX_CLAUSES_PER_QUERY + 1))
+ with pytest.raises(ValueError):
+ self._req(clauses=clauses)
+
def test_allows_distinct_clause_names_for_formula(self):
req = self._req(
clauses=(_clause(name="a"), _clause(name="b", metric_name="other")),
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 5001525ab7c5..31dd7fbb4526 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -74,6 +74,61 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
date_to=now - dt.timedelta(hours=1),
)
+ def test_rejects_too_wide_date_range(self):
+ now = timezone.now()
+ with self.assertRaises(ValueError):
+ MetricQueryRunner(
+ team=self.team,
+ metric_name="x",
+ aggregation="sum",
+ date_from=now - dt.timedelta(days=32),
+ date_to=now,
+ )
+
+ def test_rejects_interval_exceeding_row_budget(self):
+ now = timezone.now()
+ with self.assertRaises(ValueError):
+ MetricQueryRunner(
+ team=self.team,
+ metric_name="x",
+ aggregation="sum",
+ date_from=now - dt.timedelta(days=2),
+ date_to=now,
+ interval="second",
+ )
+
+ def test_rejects_invalid_regex_filter(self):
+ now = timezone.now()
+ runner = MetricQueryRunner(
+ team=self.team,
+ metric_name="x",
+ aggregation="sum",
+ date_from=now - dt.timedelta(hours=1),
+ date_to=now,
+ filters=(MetricFilter(key="container", op=FilterOp.REGEX, value="(["),),
+ )
+ with self.assertRaises(ValueError):
+ runner.run()
+
+ def test_raises_when_row_limit_truncates(self):
+ anchor = timezone.now().replace(second=0, microsecond=0) - dt.timedelta(minutes=10)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m_trunc",
+ points=[(anchor + dt.timedelta(minutes=m), 1.0) for m in range(6)],
+ )
+ runner = MetricQueryRunner(
+ team=self.team,
+ metric_name="m_trunc",
+ aggregation="sum",
+ date_from=anchor - dt.timedelta(minutes=1),
+ date_to=anchor + dt.timedelta(minutes=10),
+ interval="minute",
+ )
+ with patch("products.metrics.backend.metric_query_runner._ROW_LIMIT", 5):
+ with self.assertRaises(ValueError):
+ runner.run()
+
def test_returns_empty_for_no_data(self):
runner = MetricQueryRunner(
team=self.team,
@@ -242,9 +297,30 @@ class TestAttributeField(ClickhouseTestMixin, APIBaseTest):
team_id=self.team.id,
metric_name="m_resource",
points=[(anchor, 1.0)],
- resource_labels={"service_name": "logs-ingestion"},
+ resource_labels={"service_version": "1.2.3"},
)
- value = self._select_attribute(attribute_field("service_name", scope="resource"), "m_resource")
+ value = self._select_attribute(attribute_field("service_version", scope="resource"), "m_resource")
+ self.assertEqual(value, "1.2.3")
+
+ @parameterized.expand(
+ [
+ (f"{key}_{scope}", key, scope)
+ for key in ("service_name", "service.name")
+ for scope in ("auto", "resource", "attribute")
+ ]
+ )
+ 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.
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m_service",
+ points=[(anchor, 1.0)],
+ service_name="logs-ingestion",
+ )
+ value = self._select_attribute(attribute_field(key, scope=scope), "m_service") # type: ignore[arg-type]
self.assertEqual(value, "logs-ingestion")
def test_attribute_scope_reads_attributes_via_alias(self):
@@ -810,6 +886,14 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):
with self.assertRaises(ValueError):
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.
+ 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"),))
+ self.assertEqual(sorted(row["labels"]["service_name"] for row in rows), ["svc-a", "svc-b"])
+
def test_delta_histogram_p50(self):
self._seed_histogram(
[
@@ -909,6 +993,8 @@ class TestFormulaParser:
("trailing_garbage", "a + b )", frozenset({"a", "b"})),
("empty", " ", frozenset({"a"})),
("bad_char", "a ^ b", frozenset({"a", "b"})),
+ ("nesting_too_deep_parens", "(" * 40 + "a" + ")" * 40, frozenset({"a"})),
+ ("nesting_too_deep_unary", "-" * 40 + "a", frozenset({"a"})),
]
)
def test_rejects(self, _name, formula, names):
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 7e7f2d0db40b..4e8bc562a231 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -85,7 +85,10 @@ export interface _MetricFilterApi {
* * `regex` - regex
* * `not_regex` - not_regex */
op?: OpEnumApi
- /** Value to compare against. For regex operators this is the pattern. */
+ /**
+ * Value to compare against. For regex operators this is the pattern.
+ * @maxLength 1024
+ */
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.
*
@@ -145,10 +148,10 @@ export interface _MetricAnomalyRequestApi {
* * `down` - down
* * `flat` - flat
*/
-export type _MetricAnomalyReportDirectionEnumApi =
- (typeof _MetricAnomalyReportDirectionEnumApi)[keyof typeof _MetricAnomalyReportDirectionEnumApi]
+export type MetricAnomalyDirectionEnumApi =
+ (typeof MetricAnomalyDirectionEnumApi)[keyof typeof MetricAnomalyDirectionEnumApi]
-export const _MetricAnomalyReportDirectionEnumApi = {
+export const MetricAnomalyDirectionEnumApi = {
Up: 'up',
Down: 'down',
Flat: 'flat',
@@ -226,7 +229,7 @@ export interface _MetricAnomalyReportApi {
* * `up` - up
* * `down` - down
* * `flat` - flat */
- direction: _MetricAnomalyReportDirectionEnumApi
+ direction: MetricAnomalyDirectionEnumApi
/**
* First bucket clearly outside the baseline range (3 stddevs or 50% relative change), or null if no clear onset.
* @nullable
@@ -347,7 +350,7 @@ export interface _MetricQueryBodyApi {
* * `day` - day
* * `week` - week */
interval?: MetricQueryIntervalEnumApi | null
- /** Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'. */
+ /** Full multi-clause form: each clause is an independent metric selection sharing the request's time grid (maximum 10). Mutually exclusive with 'metricName'. */
clauses?: _MetricClauseApi[]
/**
* Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) / a'. Supports + - * / and parentheses; division by zero yields 0. When set, only the formula result series are returned.
@@ -387,7 +390,7 @@ export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown }
export type MetricsValuesRetrieveParams = {
/**
- * Max number of names to return. Defaults to 100, capped at 1000.
+ * Max number of names to return. Defaults to 100; maximum 1000.
*/
limit?: number
/**
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 6269dfe6844b..146d81fb717f 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -21,6 +21,8 @@ export const metricsCharacterizeCreateBodyQueryOneQuantileMax = 1
export const metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax = 255
export const metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemValueMax = 1024
+
export const metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax = 255
@@ -89,6 +91,7 @@ export const MetricsCharacterizeCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsCharacterizeCreateBodyQueryOneFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -120,6 +123,8 @@ export const metricsQueryCreateBodyQueryOneQuantileMax = 1
export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255
export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneFiltersItemValueMax = 1024
+
export const metricsQueryCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const metricsQueryCreateBodyQueryOneGroupByItemKeyMax = 255
@@ -135,6 +140,8 @@ export const metricsQueryCreateBodyQueryOneClausesItemQuantileMax = 1
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemKeyMax = 255
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemValueMax = 1024
+
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemScopeDefault = `auto`
export const metricsQueryCreateBodyQueryOneClausesItemGroupByItemKeyMax = 255
@@ -184,6 +191,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsQueryCreateBodyQueryOneFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -275,6 +283,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -313,7 +322,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'."
+ "Full multi-clause form: each clause is an independent metric selection sharing the request's time grid (maximum 10). Mutually exclusive with 'metricName'."
),
formula: zod
.string()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d4cd61d4121b..c6359b99846c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29059,6 +29059,20 @@ export namespace Schemas {
SetConfigOption: 'set_config_option',
} as const;
+ /**
+ * * `up` - up
+ * * `down` - down
+ * * `flat` - flat
+ */
+ export type MetricAnomalyDirectionEnum = typeof MetricAnomalyDirectionEnum[keyof typeof MetricAnomalyDirectionEnum];
+
+
+ export const MetricAnomalyDirectionEnum = {
+ Up: 'up',
+ Down: 'down',
+ Flat: 'flat',
+ } as const;
+
/**
* * `resource` - resource
* * `attribute` - attribute
@@ -52760,7 +52774,10 @@ export namespace Schemas {
* * `regex` - regex
* * `not_regex` - not_regex */
op?: OpEnum;
- /** Value to compare against. For regex operators this is the pattern. */
+ /**
+ * Value to compare against. For regex operators this is the pattern.
+ * @maxLength 1024
+ */
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.
*
@@ -52823,20 +52840,6 @@ export namespace Schemas {
change_ratio: number;
}
- /**
- * * `up` - up
- * * `down` - down
- * * `flat` - flat
- */
- export type _MetricAnomalyReportDirectionEnum = typeof _MetricAnomalyReportDirectionEnum[keyof typeof _MetricAnomalyReportDirectionEnum];
-
-
- export const _MetricAnomalyReportDirectionEnum = {
- Up: 'up',
- Down: 'down',
- Flat: 'flat',
- } as const;
-
export interface _MetricQueryPoint {
/** Bucket start as ISO 8601 timestamp. */
time: string;
@@ -52896,7 +52899,7 @@ export namespace Schemas {
* * `up` - up
* * `down` - down
* * `flat` - flat */
- direction: _MetricAnomalyReportDirectionEnum;
+ direction: MetricAnomalyDirectionEnum;
/**
* First bucket clearly outside the baseline range (3 stddevs or 50% relative change), or null if no clear onset.
* @nullable
@@ -53011,7 +53014,7 @@ export namespace Schemas {
* * `day` - day
* * `week` - week */
interval?: MetricQueryIntervalEnum | null;
- /** Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'. */
+ /** Full multi-clause form: each clause is an independent metric selection sharing the request's time grid (maximum 10). Mutually exclusive with 'metricName'. */
clauses?: _MetricClause[];
/**
* Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) / a'. Supports + - * / and parentheses; division by zero yields 0. When set, only the formula result series are returned.
@@ -56902,7 +56905,7 @@ export namespace Schemas {
export type EnvironmentsMetricsValuesRetrieveParams = {
/**
- * Max number of names to return. Defaults to 100, capped at 1000.
+ * Max number of names to return. Defaults to 100; maximum 1000.
*/
limit?: number;
/**
@@ -63370,7 +63373,7 @@ export namespace Schemas {
export type MetricsValuesRetrieveParams = {
/**
- * Max number of names to return. Defaults to 100, capped at 1000.
+ * Max number of names to return. Defaults to 100; maximum 1000.
*/
limit?: number;
/**
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index b99f58052cc7..d764631ef272 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -28,6 +28,8 @@ export const metricsCharacterizeCreateBodyQueryOneQuantileMax = 1
export const metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax = 255
export const metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemValueMax = 1024
+
export const metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax = 255
@@ -96,6 +98,7 @@ export const MetricsCharacterizeCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsCharacterizeCreateBodyQueryOneFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -135,6 +138,8 @@ export const metricsQueryCreateBodyQueryOneQuantileMax = 1
export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255
export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneFiltersItemValueMax = 1024
+
export const metricsQueryCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const metricsQueryCreateBodyQueryOneGroupByItemKeyMax = 255
@@ -150,6 +155,8 @@ export const metricsQueryCreateBodyQueryOneClausesItemQuantileMax = 1
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemKeyMax = 255
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemOpDefault = `eq`
+export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemValueMax = 1024
+
export const metricsQueryCreateBodyQueryOneClausesItemFiltersItemScopeDefault = `auto`
export const metricsQueryCreateBodyQueryOneClausesItemGroupByItemKeyMax = 255
@@ -199,6 +206,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsQueryCreateBodyQueryOneFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -290,6 +298,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
),
value: zod
.string()
+ .max(metricsQueryCreateBodyQueryOneClausesItemFiltersItemValueMax)
.describe('Value to compare against. For regex operators this is the pattern.'),
scope: zod
.enum(['resource', 'attribute', 'auto'])
@@ -324,7 +333,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- "Full multi-clause form: each clause is an independent metric selection sharing the request's time grid. Mutually exclusive with 'metricName'."
+ "Full multi-clause form: each clause is an independent metric selection sharing the request's time grid (maximum 10). Mutually exclusive with 'metricName'."
),
formula: zod
.string()
@@ -356,6 +365,6 @@ export const MetricsValuesRetrieveParams = /* @__PURE__ */ zod.object({
})
export const MetricsValuesRetrieveQueryParams = /* @__PURE__ */ zod.object({
- limit: zod.number().optional().describe('Max number of names to return. Defaults to 100, capped at 1000.'),
+ limit: zod.number().optional().describe('Max number of names to return. Defaults to 100; maximum 1000.'),
value: zod.string().optional().describe('Substring filter (case-insensitive) applied to metric names.'),
})