:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): group_by on a shared, zero-filled interval grid (P4) (#63126)
Daniel Viscac68af92e9671
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex b8b52c6f9b7b..dd9b8b23c075 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -526,6 +526,9 @@ SPECTACULAR_SETTINGS = {"AgentSessionStateEnum": ["queued", "running", "completed", "closed", "cancelled", "failed"],"ScoutOriginEnum": ["canonical", "custom"],"FileFormatEnum": ["Parquet", "JSONLines"],+ "MetricAttributeScopeEnum": ["resource", "attribute", "auto"],+ "MetricQueryIntervalEnum": ["second", "minute", "minute_5", "minute_15", "hour", "hour_6", "day", "week"],+ "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"],# Dashboard widget polymorphic OpenAPI: each per-type serializer uses a singletondiff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex b537d20504b6..e6e600488083 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -231,9 +231,9 @@ export interface BatchExportDestinationApi {* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes*/-export type IntervalEnumApi = (typeof IntervalEnumApi)[keyof typeof IntervalEnumApi]+export type BatchExportIntervalEnumApi = (typeof BatchExportIntervalEnumApi)[keyof typeof BatchExportIntervalEnumApi]-export const IntervalEnumApi = {+export const BatchExportIntervalEnumApi = {Hour: 'hour',Day: 'day',Week: 'week',@@ -381,7 +381,7 @@ export interface BatchExportApi {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval: IntervalEnumApi+ interval: BatchExportIntervalEnumApi/** Whether this BatchExport is paused or not. */paused?: boolean/** The timestamp at which this BatchExport was created. */@@ -1115,7 +1115,7 @@ export interface BatchExportRequestApi {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval: IntervalEnumApi+ interval: BatchExportIntervalEnumApi/** Whether the batch export is paused. */paused?: boolean/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */@@ -1274,7 +1274,7 @@ export interface PatchedBatchExportRequestApi {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval?: IntervalEnumApi+ interval?: BatchExportIntervalEnumApi/** Whether the batch export is paused. */paused?: boolean/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex f43fd6f7467e..1269bf8e27fc 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -29,25 +29,55 @@ def team_has_metrics(team: Team) -> bool:return _team_has_metrics(team)+# Hard cap on series returned per clause; the largest series (by summed+# absolute value) win so the most significant groups survive truncation.+MAX_SERIES_PER_CLAUSE = 100+++def _assemble_series(+ rows: list[dict[str, Any]], *, metric_name: str, clause_name: str, grid: list[str]+) -> list[MetricSeries]:+ """Split bucketed rows into one series per label-set, zero-filled onto+ the shared grid so every series (and later, every clause of a formula)+ has identical timestamps."""+ by_labels: dict[tuple[tuple[str, str], ...], dict[str, float]] = {}+ for row in rows:+ key = tuple(sorted(row["labels"].items()))+ by_labels.setdefault(key, {})[row["time"]] = row["value"]++ series = [+ 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()+ ]+ 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 run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSeries]:"""Execute a metric query and return one `MetricSeries` per(clause, label-set) pair — a single ungrouped clause yields exactly oneseries with empty labels, so consumers never branch on single-vs-multi.- Current scope: one clause; filters, group_by, interval, formula and the- rate/histogram aggregations raise `ValueError` until their PRs land.- The presentation layer surfaces `ValueError` as a 400.+ All series share one bucket grid (the union of observed buckets,+ zero-filled), which is what makes cross-series and cross-clause math+ line up. Series per clause are capped at `MAX_SERIES_PER_CLAUSE`,+ keeping the largest ones.++ Current scope: one clause; multi-clause and formula raise `ValueError`+ until their PRs land. The presentation layer surfaces `ValueError` as+ a 400."""if len(request.clauses) != 1:raise ValueError("multi-clause queries are not supported yet")if request.formula is not None:raise ValueError("formulas are not supported yet")- if request.interval is not None:- raise ValueError("explicit intervals are not supported yet")clause = request.clauses[0]- if clause.group_by:- raise ValueError("group_by is not supported yet")if clause.aggregation == MetricAggregation.QUANTILE and clause.quantile == 0.95:runner_aggregation = "p95"@@ -63,9 +93,15 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSdate_from=request.date_from,date_to=request.date_to,filters=clause.filters,+ group_by=clause.group_by,+ interval=request.interval,)- 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)]+ rows = runner.run()+ if not rows:+ return [MetricSeries(labels={}, points=(), metric_name=clause.metric_name, clause=clause.name)]++ grid = sorted({row["time"] for row in rows})+ return _assemble_series(rows, metric_name=clause.metric_name, clause_name=clause.name, grid=grid)def list_metric_names(diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex a0b70f1176d4..22dcfb089f8a 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -19,7 +19,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.models import Team-from products.metrics.backend.facade.contracts import MetricFilter+from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupByfrom products.metrics.backend.facade.enums import FilterOpAttributeScope = Literal["resource", "attribute", "auto"]@@ -162,11 +162,15 @@ class MetricQueryRunner:date_from: dt.datetime,date_to: dt.datetime,filters: Sequence[MetricFilter] = (),+ group_by: Sequence[MetricGroupBy] = (),+ interval: str | None = None,) -> None:if aggregation not in _ALLOWED_AGGREGATIONS:raise ValueError(f"Unsupported aggregation: {aggregation!r}")if date_to <= date_from:raise ValueError("date_to must be after date_from")+ if interval is not None and interval not in {name for name, _, _ in _INTERVAL_LADDER}:+ raise ValueError(f"Unknown interval: {interval!r}")self.team = teamself.metric_name = metric_name@@ -174,9 +178,12 @@ class MetricQueryRunner:self.date_from = date_fromself.date_to = date_toself.filters = tuple(filters)- self.interval = _pick_interval(date_from, date_to)+ self.group_by = tuple(group_by)+ self.interval = interval or _pick_interval(date_from, date_to)def run(self) -> list[dict[str, Any]]:+ """Bucketed rows: `{"time", "value", "labels"}`. `labels` carries one+ entry per group_by key (always `{}` without group_by)."""# `metrics` is only registered under the `posthog.` HogQL namespace# (see posthog/hogql/database/database.py).query = parse_select(@@ -203,6 +210,14 @@ class MetricQueryRunner:},)assert isinstance(query, ast.SelectQuery)+ assert query.group_by is not None++ # Splice the group_by label columns between `time` and `value` —+ # parse_select placeholders can't express a variable column count.+ for index, group in enumerate(self.group_by):+ label_expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])+ query.select.insert(1 + index, ast.Alias(alias=f"group_{index}", expr=label_expr))+ query.group_by.append(ast.Field(chain=[f"group_{index}"]))response = execute_hogql_query(query_type="MetricQuery",@@ -211,7 +226,14 @@ class MetricQueryRunner:workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now)- return [- {"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0], "value": row[1]}- for row in response.results- ]+ group_count = len(self.group_by)+ rows: list[dict[str, Any]] = []+ for row in response.results:+ rows.append(+ {+ "time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],+ "value": row[1 + group_count],+ "labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},+ }+ )+ return rowsdiff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex fe88e5099918..db5342f76e2b 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -23,7 +23,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import report_user_actionfrom products.metrics.backend.facade.api import list_metric_names, run_metric_query, team_has_metrics-from products.metrics.backend.facade.contracts import MetricFilter, MetricQueryClause, MetricQueryRequest+from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequestfrom products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation__all__ = ["MetricsViewSet"]@@ -50,6 +50,18 @@ class _MetricFilterSerializer(serializers.Serializer):)+class _MetricGroupBySerializer(serializers.Serializer):+ key = serializers.CharField(+ max_length=255,+ help_text="Attribute name to split series by (e.g. 'k8s.pod.name', 'env').",+ )+ scope = serializers.ChoiceField(+ choices=["resource", "attribute", "auto"],+ default="auto",+ help_text="Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.",+ )++class _MetricQueryBodySerializer(serializers.Serializer):metricName = serializers.CharField(max_length=255,@@ -66,6 +78,18 @@ class _MetricQueryBodySerializer(serializers.Serializer):default=list,help_text="Label predicates ANDed together. Rows must satisfy every filter.",)+ groupBy = _MetricGroupBySerializer(+ many=True,+ required=False,+ default=list,+ help_text="Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest.",+ )+ interval = serializers.ChoiceField(+ choices=["second", "minute", "minute_5", "minute_15", "hour", "hour_6", "day", "week"],+ required=False,+ allow_null=True,+ help_text="Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).",+ )dateFrom = serializers.DateTimeField(help_text="Lower bound (inclusive) for the query range. ISO 8601.",)@@ -203,6 +227,9 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)for f in query_data.get("filters") or [])+ group_by = tuple(+ MetricGroupBy(key=g["key"], scope=AttributeScope(g["scope"])) for g in query_data.get("groupBy") or []+ )date_to: dt.datetime = query_data.get("dateTo") or timezone.now()try:@@ -214,10 +241,12 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):aggregation=aggregation,quantile=quantile,filters=filters,+ group_by=group_by,),),date_from=query_data["dateFrom"],date_to=date_to,+ interval=query_data.get("interval"),)series = run_metric_query(team=self.team, request=metric_request)except ValueError as exc:diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex f5caeb2d6864..a3fd98a27ce1 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -2,6 +2,7 @@ import datetime as dtfrom typing import Anyfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom django.utils import timezone@@ -345,20 +346,6 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):},),("formula", {"formula": "a / b"}),- ("interval", {"interval": "minute"}),- (- "group_by",- {- "clauses": (- MetricQueryClause(- name="a",- metric_name="m1",- aggregation=MetricAggregation.SUM,- group_by=(MetricGroupBy(key="env"),),- ),- )- },- ),("unsupported_aggregation",{"clauses": (MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.RATE),)},@@ -485,3 +472,117 @@ class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):),)self.assertEqual(sum(p.value for p in series[0].points), 10.0)+++class TestGroupBy(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, second=0)+ # env=prod has points in two buckets, env=dev only in the second —+ # exercises the shared-grid zero-fill.+ seed_metric(+ team_id=self.team.id,+ metric_name="req",+ points=[(self.anchor - dt.timedelta(minutes=10), 1.0), (self.anchor - dt.timedelta(minutes=5), 2.0)],+ labels={"env": "prod"},+ )+ seed_metric(+ team_id=self.team.id,+ metric_name="req",+ points=[(self.anchor - dt.timedelta(minutes=5), 10.0)],+ labels={"env": "dev"},+ )++ def _run(self, **request_overrides):+ defaults: dict[str, Any] = {+ "clauses": (+ MetricQueryClause(+ name="a",+ metric_name="req",+ aggregation=MetricAggregation.SUM,+ group_by=(MetricGroupBy(key="env"),),+ ),+ ),+ "date_from": self.anchor - dt.timedelta(hours=1),+ "date_to": self.anchor,+ }+ defaults.update(request_overrides)+ return run_metric_query(team=self.team, request=MetricQueryRequest(**defaults))++ def test_one_series_per_group_with_shared_zero_filled_grid(self):+ series = self._run()++ self.assertEqual(len(series), 2)+ by_env = {s.labels["env"]: s for s in series}+ self.assertEqual(set(by_env), {"prod", "dev"})++ prod_times = [p.time for p in by_env["prod"].points]+ dev_times = [p.time for p in by_env["dev"].points]+ self.assertEqual(prod_times, dev_times)++ 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.+ self.assertIn(0.0, [p.value for p in by_env["dev"].points])++ def test_series_ordered_largest_first(self):+ series = self._run()+ self.assertEqual(series[0].labels["env"], "dev")++ def test_explicit_interval_respected(self):+ series = self._run(interval="minute_5")+ # 10-minute spread at 5m buckets: both points land in distinct buckets+ by_env = {s.labels["env"]: s for s in series}+ self.assertEqual(len(by_env["prod"].points), len(by_env["dev"].points))++ def test_unknown_interval_raises(self):+ with self.assertRaises(ValueError):+ self._run(interval="fortnight")++ def test_group_by_resource_scope(self):+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ seed_metric(+ team_id=self.team.id,+ metric_name="req",+ points=[(self.anchor - dt.timedelta(minutes=5), 7.0)],+ resource_labels={"k8s.pod.name": "web-1"},+ )+ series = self._run(+ clauses=(+ MetricQueryClause(+ name="a",+ metric_name="req",+ aggregation=MetricAggregation.SUM,+ group_by=(MetricGroupBy(key="k8s.pod.name", scope=AttributeScope.RESOURCE),),+ ),+ )+ )+ self.assertEqual(series[0].labels, {"k8s.pod.name": "web-1"})++ def test_group_by_via_api(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "req",+ "aggregation": "sum",+ "groupBy": [{"key": "env"}],+ "interval": "minute",+ "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)+ results = response.json()["results"]+ self.assertEqual({s["labels"]["env"] for s in results}, {"prod", "dev"})++ def test_series_cap_keeps_largest(self):+ with patch("products.metrics.backend.facade.api.MAX_SERIES_PER_CLAUSE", 1):+ series = self._run()+ self.assertEqual(len(series), 1)+ self.assertEqual(series[0].labels["env"], "dev")diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 0ac6ebc2cfb0..43a30e9319b5 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -58,9 +58,9 @@ export const OpEnumApi = {* * `attribute` - attribute* * `auto` - auto*/-export type _MetricFilterScopeEnumApi = (typeof _MetricFilterScopeEnumApi)[keyof typeof _MetricFilterScopeEnumApi]+export type MetricAttributeScopeEnumApi = (typeof MetricAttributeScopeEnumApi)[keyof typeof MetricAttributeScopeEnumApi]-export const _MetricFilterScopeEnumApi = {+export const MetricAttributeScopeEnumApi = {Resource: 'resource',Attribute: 'attribute',Auto: 'auto',@@ -86,9 +86,46 @@ export interface _MetricFilterApi {* * `resource` - resource* * `attribute` - attribute* * `auto` - auto */- scope?: _MetricFilterScopeEnumApi+ scope?: MetricAttributeScopeEnumApi}+export interface _MetricGroupByApi {+ /**+ * Attribute name to split series by (e.g. 'k8s.pod.name', 'env').+ * @maxLength 255+ */+ key: string+ /** Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.+ *+ * * `resource` - resource+ * * `attribute` - attribute+ * * `auto` - auto */+ scope?: MetricAttributeScopeEnumApi+}++/**+ * * `second` - second+ * * `minute` - minute+ * * `minute_5` - minute_5+ * * `minute_15` - minute_15+ * * `hour` - hour+ * * `hour_6` - hour_6+ * * `day` - day+ * * `week` - week+ */+export type MetricQueryIntervalEnumApi = (typeof MetricQueryIntervalEnumApi)[keyof typeof MetricQueryIntervalEnumApi]++export const MetricQueryIntervalEnumApi = {+ Second: 'second',+ Minute: 'minute',+ Minute5: 'minute_5',+ Minute15: 'minute_15',+ Hour: 'hour',+ Hour6: 'hour_6',+ Day: 'day',+ Week: 'week',+} as const+export interface _MetricQueryBodyApi {/*** Exact metric name to query (e.g. 'http.server.duration').@@ -104,6 +141,19 @@ export interface _MetricQueryBodyApi {aggregation?: AggregationEnumApi/** Label predicates ANDed together. Rows must satisfy every filter. */filters?: _MetricFilterApi[]+ /** Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest. */+ groupBy?: _MetricGroupByApi[]+ /** Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).+ *+ * * `second` - second+ * * `minute` - minute+ * * `minute_5` - minute_5+ * * `minute_15` - minute_15+ * * `hour` - hour+ * * `hour_6` - hour_6+ * * `day` - day+ * * `week` - week */+ interval?: MetricQueryIntervalEnumApi | null/** 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.tsindex 7ba2ae36b135..5a020c5cae00 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -16,6 +16,9 @@ export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`export const metricsQueryCreateBodyQueryOneFiltersItemScopeDefault = `auto`+export const metricsQueryCreateBodyQueryOneGroupByItemKeyMax = 255++export const metricsQueryCreateBodyQueryOneGroupByItemScopeDefault = `auto`export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -61,6 +64,39 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({).optional().describe('Label predicates ANDed together. Rows must satisfy every filter.'),+ groupBy: zod+ .array(+ zod.object({+ key: zod+ .string()+ .max(metricsQueryCreateBodyQueryOneGroupByItemKeyMax)+ .describe("Attribute name to split series by (e.g. 'k8s.pod.name', 'env')."),+ scope: zod+ .enum(['resource', 'attribute', 'auto'])+ .describe('\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto')+ .default(metricsQueryCreateBodyQueryOneGroupByItemScopeDefault)+ .describe(+ "Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.\n\n\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto"+ ),+ })+ )+ .optional()+ .describe(+ 'Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest.'+ ),+ interval: zod+ .union([+ zod+ .enum(['second', 'minute', 'minute_5', 'minute_15', 'hour', 'hour_6', 'day', 'week'])+ .describe(+ '\* `second` - second\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `hour` - hour\n\* `hour_6` - hour_6\n\* `day` - day\n\* `week` - week'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).\n\n\* `second` - second\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `hour` - hour\n\* `hour_6` - hour_6\n\* `day` - day\n\* `week` - week'+ ),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.tsindex cd7901adf512..31fbbef6d6f0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9815,10 +9815,10 @@ export namespace Schemas {* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes*/- export type IntervalEnum = typeof IntervalEnum[keyof typeof IntervalEnum];+ export type BatchExportIntervalEnum = typeof BatchExportIntervalEnum[keyof typeof BatchExportIntervalEnum];- export const IntervalEnum = {+ export const BatchExportIntervalEnum = {Hour: 'hour',Day: 'day',Week: 'week',@@ -9967,7 +9967,7 @@ export namespace Schemas {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval: IntervalEnum;+ interval: BatchExportIntervalEnum;/** Whether this BatchExport is paused or not. */paused?: boolean;/** The timestamp at which this BatchExport was created. */@@ -10763,7 +10763,7 @@ export namespace Schemas {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval: IntervalEnum;+ interval: BatchExportIntervalEnum;/** Whether the batch export is paused. */paused?: boolean;/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */@@ -25033,6 +25033,20 @@ export namespace Schemas {SetConfigOption: 'set_config_option',} as const;+ /**+ * * `resource` - resource+ * * `attribute` - attribute+ * * `auto` - auto+ */+ export type MetricAttributeScopeEnum = typeof MetricAttributeScopeEnum[keyof typeof MetricAttributeScopeEnum];+++ export const MetricAttributeScopeEnum = {+ Resource: 'resource',+ Attribute: 'attribute',+ Auto: 'auto',+ } as const;+/*** * `precise` - PRECISE* * `coarse` - COARSE@@ -25047,6 +25061,30 @@ export namespace Schemas {Partial: 'partial',} as const;+ /**+ * * `second` - second+ * * `minute` - minute+ * * `minute_5` - minute_5+ * * `minute_15` - minute_15+ * * `hour` - hour+ * * `hour_6` - hour_6+ * * `day` - day+ * * `week` - week+ */+ export type MetricQueryIntervalEnum = typeof MetricQueryIntervalEnum[keyof typeof MetricQueryIntervalEnum];+++ export const MetricQueryIntervalEnum = {+ Second: 'second',+ Minute: 'minute',+ Minute5: 'minute_5',+ Minute15: 'minute_15',+ Hour: 'hour',+ Hour6: 'hour_6',+ Day: 'day',+ Week: 'week',+ } as const;+export interface MinimalPerson {/** Numeric person ID. */readonly id: number;@@ -30932,7 +30970,7 @@ export namespace Schemas {* * `week` - week* * `every 5 minutes` - every 5 minutes* * `every 15 minutes` - every 15 minutes */- interval?: IntervalEnum;+ interval?: BatchExportIntervalEnum;/** Whether the batch export is paused. */paused?: boolean;/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */@@ -45520,20 +45558,6 @@ 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').@@ -45554,7 +45578,21 @@ export namespace Schemas {* * `resource` - resource* * `attribute` - attribute* * `auto` - auto */- scope?: _MetricFilterScopeEnum;+ scope?: MetricAttributeScopeEnum;+ }++ export interface _MetricGroupBy {+ /**+ * Attribute name to split series by (e.g. 'k8s.pod.name', 'env').+ * @maxLength 255+ */+ key: string;+ /** Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.+ *+ * * `resource` - resource+ * * `attribute` - attribute+ * * `auto` - auto */+ scope?: MetricAttributeScopeEnum;}export interface _MetricName {@@ -45584,6 +45622,19 @@ export namespace Schemas {aggregation?: AggregationEnum;/** Label predicates ANDed together. Rows must satisfy every filter. */filters?: _MetricFilter[];+ /** Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest. */+ groupBy?: _MetricGroupBy[];+ /** Bucket size for the shared time grid. Omit to auto-pick (~60 buckets across the range).+ *+ * * `second` - second+ * * `minute` - minute+ * * `minute_5` - minute_5+ * * `minute_15` - minute_15+ * * `hour` - hour+ * * `hour_6` - hour_6+ * * `day` - day+ * * `week` - week */+ interval?: MetricQueryIntervalEnum | null;/** Lower bound (inclusive) for the query range. ISO 8601. */dateFrom: string;/** Upper bound (exclusive) for the query range. Defaults to now if omitted. */