: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): allow dashboard variables to set query intervals (#122162)
Radu Raiceaa04d22cf954f
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 3dd9e7068c52..f30706e56d5c 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -38849,7 +38849,7 @@"type": "array"},"interval": {- "description": "Bucket size; auto-picked from the range when omitted",+ "description": "Bucket size; auto-picked from the range when omitted. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range.","type": "string"},"kind": {@@ -38881,7 +38881,7 @@"additionalProperties": {"$ref": "#/definitions/MetricsVariableValue"},- "description": "Values of the dashboard variables that the filters refer to as `$name`.",+ "description": "Values of the dashboard variables that the filters or interval refer to as `$name`.","type": "object"},"version": {@@ -39009,7 +39009,7 @@"type": "string"},"interval": {- "description": "Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Coarsened when the range would need more than 10,000 buckets.",+ "description": "Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable.","type": "string"},"kind": {@@ -39042,7 +39042,7 @@"additionalProperties": {"$ref": "#/definitions/MetricsVariableValue"},- "description": "Values of the dashboard variables that the PromQL, SQL or filters refer to as `$name`.",+ "description": "Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`.","type": "object"},"version": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 38c647f88570..0322725b54d6 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5010,11 +5010,13 @@ export interface MetricsHistogramQuery extends DataNode<MetricsHistogramQueryResfilters?: MetricsQueryFilter[]/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRange- /** Bucket size; auto-picked from the range when omitted */+ /** Bucket size; auto-picked from the range when omitted. A dashboard variable reference such as `$window`+ * pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w).+ * Variable intervals that exceed 500 buckets require a larger value or shorter date range. */interval?: string/** UCUM unit for the y-axis bounds, e.g. "s", "ms". Presentation only. */unit?: string- /** Values of the dashboard variables that the filters refer to as `$name`. */+ /** Values of the dashboard variables that the filters or interval refer to as `$name`. */variables?: Record<string, MetricsVariableValue>}@@ -5111,13 +5113,17 @@ export interface MetricsQuery extends DataNode<MetricsQueryResponse> {sql?: string/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRange- /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Coarsened when the range would need more than 10,000 buckets. */+ /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week;+ * auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets.+ * A dashboard variable reference such as `$window` pins the interval to its single duration value+ * (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require+ * a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable. */interval?: string/** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */formula?: string/** Chart presentation. A node without it renders as a line chart. */display?: MetricsDisplaySettings- /** Values of the dashboard variables that the PromQL, SQL or filters refer to as `$name`. */+ /** Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`. */variables?: Record<string, MetricsVariableValue>}diff --git a/posthog/schema.py b/posthog/schema.pyindex 6282abcc12f4..f0b4860fdd45 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -29254,7 +29254,15 @@ class MetricsHistogramQuery(BaseModel):description=("Defaults to the last 24 hours when omitted; dashboard date filters override it"),)filters: list[MetricsQueryFilter] | None = None- interval: str | None = Field(default=None, description="Bucket size; auto-picked from the range when omitted")+ interval: str | None = Field(+ default=None,+ description=(+ "Bucket size; auto-picked from the range when omitted. A dashboard variable"+ " reference such as `$window` pins the interval to its single duration"+ " value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals"+ " that exceed 500 buckets require a larger value or shorter date range."+ ),+ )kind: Literal["MetricsHistogramQuery"] = "MetricsHistogramQuery"metricName: strmetricType: MetricsOtelType | None = Field(@@ -29274,7 +29282,7 @@ class MetricsHistogramQuery(BaseModel):)variables: dict[str, MetricsVariableValue] | None = Field(default=None,- description=("Values of the dashboard variables that the filters refer to as `$name`."),+ description=("Values of the dashboard variables that the filters or interval refer to as `$name`."),)version: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -29301,7 +29309,12 @@ class MetricsQuery(BaseModel):description=("Bucket size, one of: second_15, second_30, minute, minute_5, minute_15,"" minute_30, hour, hour_6, day, week; auto-picked from the range when"- " omitted. Coarsened when the range would need more than 10,000 buckets."+ " omitted. Fixed intervals are coarsened above 500 buckets. A dashboard"+ " variable reference such as `$window` pins the interval to its single"+ " duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable"+ " intervals that exceed 500 buckets require a larger value or shorter date"+ " range, so the step stays consistent with PromQL lookbacks using that"+ " variable."),)kind: Literal["MetricsQuery"] = "MetricsQuery"@@ -29326,7 +29339,9 @@ class MetricsQuery(BaseModel):tags: QueryLogTags | None = Nonevariables: dict[str, MetricsVariableValue] | None = Field(default=None,- description=("Values of the dashboard variables that the PromQL, SQL or filters refer to as `$name`."),+ description=(+ "Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`."+ ),)version: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.pyindex f1bfcee43a5e..c749d8227cbb 100644--- a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py@@ -33,10 +33,12 @@ from products.metrics.backend.facade.contracts import METRICS_FEATURE_FLAG, Metrfrom products.metrics.backend.facade.enums import AttributeScope, FilterOpfrom products.metrics.backend.metric_query_runner import _INTERVAL_LADDER, _QUERY_SETTINGS, _interval_stepfrom products.metrics.backend.metric_samples_query_runner import build_metric_query_runner+from products.metrics.backend.query_interval import resolve_query_intervalfrom products.metrics.backend.variables import (filter_referenced_names,from_dashboard,from_query,+ referenced_names,substitute_filters,to_query,unresolved_message,@@ -130,7 +132,7 @@ class MetricsHistogramQueryRunner(AnalyticsQueryRunner[MetricsHistogramQueryRespdate_from=date_from,date_to=date_to,filters=filters,- interval=interval,+ interval=resolve_query_interval(interval, from_query(self.query.variables), date_from, date_to),quantile=0.5, # unused by the grid query; required by the constructor# One metric name can hold series of more than one OTel type; the# heatmap must grid only the distribution the viewer picked.@@ -224,6 +226,9 @@ class MetricsHistogramQueryRunner(AnalyticsQueryRunner[MetricsHistogramQueryRespif dashboard_filter.metricVariables:# The values go into the query, so each selection has its own cache entry and reaches the async worker.self.query.variables = (- to_query(from_dashboard(dashboard_filter.metricVariables), filter_referenced_names(self.query.filters))+ to_query(+ from_dashboard(dashboard_filter.metricVariables),+ [*referenced_names(self.query.interval), *filter_referenced_names(self.query.filters)],+ )or None)diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.pyindex c5a0a34871f6..fa79a35f859e 100644--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py@@ -54,6 +54,7 @@ from products.metrics.backend.facade.enums import ()from products.metrics.backend.promql import run_promql_rangefrom products.metrics.backend.query_concurrency import query_concurrency_slots+from products.metrics.backend.query_interval import resolve_query_intervalfrom products.metrics.backend.sql_mode import run_metrics_sqlfrom products.metrics.backend.variable_options import fill_all_valuesfrom products.metrics.backend.variables import (@@ -176,7 +177,9 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):clauses=clauses,date_from=date_range.date_from(),date_to=date_range.date_to(),- interval=self.query.interval,+ interval=resolve_query_interval(+ self.query.interval, from_query(self.query.variables), date_range.date_from(), date_range.date_to()+ ),formula=self.query.formula,)@@ -196,6 +199,7 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):return run_metric_query(team=self.team, request=self._to_request())date_range = metrics_query_date_range(self.team, self.query.dateRange)date_from, date_to = date_range.date_from(), date_range.date_to()+ interval = resolve_query_interval(self.query.interval, variables, date_from, date_to)if language == MetricsQueryLanguage.PROMQL:if not (self.query.promql or "").strip():raise ValueError("Write a PromQL query first.")@@ -204,13 +208,13 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):raise ValueError(unresolved_message(promql.unresolved))# A variable set to All writes `label=~".*"`, which matches every series.text = drop_match_all_matchers(promql.text) if promql.text != self.query.promql else promql.text- return run_promql_range(self.team, text, date_from, date_to, self.query.interval)+ return run_promql_range(self.team, text, date_from, date_to, interval)if not (self.query.sql or "").strip():raise ValueError("Write a SQL query first.")sql = substitute_sql(self.query.sql or "", self._load_all_options())if sql.unresolved:raise ValueError(unresolved_message(sql.unresolved))- return run_metrics_sql(self.team, sql.sql, date_from, date_to, self.query.interval, sql.placeholders)+ return run_metrics_sql(self.team, sql.sql, date_from, date_to, interval, sql.placeholders)def _call_with_rate_limits(self, *, dashboard_id: int | None) -> tuple[MetricsQueryResponse, float]:# Tiles that wait for one shared load of the All options must not hold the runner's concurrency slots.@@ -299,6 +303,7 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):)names = dict.fromkeys([+ *referenced_names(self.query.interval),*referenced_names(self.query.promql),*sql_names,*(name for clause in self.query.clauses for name in filter_referenced_names(clause.filters)),diff --git a/products/metrics/backend/query_interval.py b/products/metrics/backend/query_interval.pynew file mode 100644index 000000000000..fbed26e0075a--- /dev/null+++ b/products/metrics/backend/query_interval.py@@ -0,0 +1,48 @@+from collections.abc import Mapping+from datetime import datetime++from products.metrics.backend.metric_query_runner import _MAX_BUCKET_COUNT, _resolve_interval+from products.metrics.backend.variables import REFERENCE, Variable, reference_name, referenced_names, unresolved_message++_DURATION_INTERVALS = {+ "15s": "second_15",+ "30s": "second_30",+ "1m": "minute",+ "5m": "minute_5",+ "15m": "minute_15",+ "30m": "minute_30",+ "1h": "hour",+ "6h": "hour_6",+ "1d": "day",+ "1w": "week",+}+++def resolve_query_interval(+ interval: str | None, variables: Mapping[str, Variable], date_from: datetime, date_to: datetime+) -> str | None:+ if not referenced_names(interval):+ return interval++ match = REFERENCE.fullmatch(interval or "")+ if match is None:+ raise ValueError("The chart interval must be a single variable reference, such as $window.")+ name = reference_name(match)+ variable = variables.get(name)+ if variable is None:+ raise ValueError(unresolved_message([name]))+ if variable.is_all or len(variable.values) != 1:+ raise ValueError(f"Select one duration for ${name} to set the chart interval.")+ value = variable.values[0]+ selected = _DURATION_INTERVALS.get(value)+ if selected is None:+ raise ValueError(+ f"Invalid chart interval for ${name}: {value!r}. Choose one of: {', '.join(_DURATION_INTERVALS)}."+ )+ # Coarsening only the step would separate it from a PromQL lookback using the same variable.+ if _resolve_interval(date_from, date_to, selected) != selected:+ raise ValueError(+ f"The {value} chart interval exceeds the {_MAX_BUCKET_COUNT}-point limit for this date range. "+ f"Choose a larger duration for ${name} or a shorter date range."+ )+ return selecteddiff --git a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py b/products/metrics/backend/tests/test_metrics_histogram_query_runner.pyindex fbab7804f3b1..c4e5f3653936 100644--- a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_histogram_query_runner.py@@ -7,7 +7,14 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.schema import DashboardFilter, MetricsHistogramQuery, MetricsQueryFilter+from posthog.schema import (+ DashboardFilter,+ MetricsDashboardVariable,+ MetricsDashboardVariableSelection,+ MetricsHistogramQuery,+ MetricsQueryFilter,+ MetricsVariableValue,+)from posthog.hogql.errors import ExposedHogQLError@@ -61,14 +68,25 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):own_filter = MetricsQueryFilter(key="namespace", op="eq", value="posthog")dashboard_filter = MetricsQueryFilter(key="service.name", op="eq", value="checkout")runner = MetricsHistogramQueryRunner(- query=MetricsHistogramQuery(metricName="latency", filters=[own_filter]), team=self.team+ query=MetricsHistogramQuery(metricName="latency", filters=[own_filter], interval="$window"), team=self.team)- runner.apply_dashboard_filters(DashboardFilter(metricFilters=[dashboard_filter]))+ runner.apply_dashboard_filters(+ DashboardFilter(+ metricFilters=[dashboard_filter],+ metricVariables=[+ MetricsDashboardVariable(+ name="window", source="custom", current=MetricsDashboardVariableSelection(values=["1m"])+ )+ ],+ )+ )self.assertEqual(runner.query.filters, [own_filter, dashboard_filter])+ assert runner.query.variables is not None and runner.query.variables["window"].values == ["1m"]- def test_returns_a_time_by_bound_grid(self):+ @parameterized.expand([("fixed", "minute"), ("variable", "$window")])+ def test_returns_a_time_by_bound_grid(self, _name: str, interval: str) -> None:self._seed_histogram([(self.anchor + dt.timedelta(seconds=0), [10, 10, 10, 0]),@@ -77,7 +95,7 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):])- response = self._run()+ response = self._run(interval=interval, variables={"window": MetricsVariableValue(values=["1m"])})self.assertEqual(response.bounds, self.BOUNDS)# One column per minute bucket across the 3-minute window.diff --git a/products/metrics/backend/tests/test_metrics_query_languages.py b/products/metrics/backend/tests/test_metrics_query_languages.pyindex 75c8c52da193..5ce80bf95796 100644--- a/products/metrics/backend/tests/test_metrics_query_languages.py+++ b/products/metrics/backend/tests/test_metrics_query_languages.py@@ -345,7 +345,7 @@ class TestMetricsSqlMode(ClickhouseTestMixin, APIBaseTest):assert {point.value for series in results for point in series.points} == {50.0, None}- @parameterized.expand([("UTC", "week", "-30d"), ("Asia/Kathmandu", "minute_30", "-3h")])+ @parameterized.expand([("UTC", "week", "-30d"), ("Asia/Kathmandu", "minute_30", "-3h"), ("UTC", "$window", "-3h")])def test_interval_starts_are_zero_filled_in_any_timezone(self, timezone: str, interval: str, date_from: str) -> None:@@ -359,10 +359,23 @@ class TestMetricsSqlMode(ClickhouseTestMixin, APIBaseTest):clauses=[], language="sql", sql=sql, interval=interval, dateRange=DateRange(date_from=date_from))- results = MetricsQueryRunner(query=query, team=self.team).calculate().results+ runner = MetricsQueryRunner(query=query, team=self.team)+ runner.apply_dashboard_filters(+ DashboardFilter(+ metricVariables=[+ MetricsDashboardVariable(+ name="window", source="custom", current=MetricsDashboardVariableSelection(values=["1h"])+ )+ ]+ )+ )+ results = runner.calculate().resultsby_service = {series.labels["service"]: [point.value for point in series.points] for series in results}assert by_service == {"api": [1.0, 0.0, 0.0], "worker": [0.0, 1.0, 1.0]}+ if interval == "$window":+ first, second = [dt.datetime.fromisoformat(point.time) for point in results[0].points[:2]]+ assert second - first == dt.timedelta(hours=1)def test_caches_like_a_metrics_insight_not_a_sql_insight(self) -> None:sql = "SELECT now() AS time, 1 AS value FROM posthog.metrics"@@ -457,17 +470,33 @@ class TestMetricsPromQLMode(APIBaseTest):assert (series.clause, series.labels) == (clause, labels)- def test_dashboard_variables_reach_the_promql_text_and_the_cache_key(self) -> None:- def runner_for(job: MetricsDashboardVariableSelection) -> MetricsQueryRunner:- runner = self._runner('sum(rate(http_requests_total{job=~"$job", env="${env}"}[$__rate_interval]))')+ @parameterized.expand(+ [+ ("hourly_over_seven_days", "1h", "-7d", "$window", 3600),+ ("five_minutes_over_six_hours", "5m", "-6h", "$window", 300),+ ("variable_only_in_interval", "1h", "-7d", "$__rate_interval", 3600),+ ]+ )+ def test_dashboard_variables_reach_the_promql_text_and_the_cache_key(+ self, _name: str, window: str, date_from: str, lookback: str, step: int+ ) -> None:+ def runner_for(job: MetricsDashboardVariableSelection, selected_window: str = window) -> MetricsQueryRunner:+ runner = self._runner('sum(rate(http_requests_total{job=~"$job", env="${env}"}[' + lookback + "]))")+ runner.query.interval = "$window"runner.apply_dashboard_filters(DashboardFilter(+ date_from=date_from,metricVariables=[MetricsDashboardVariable(name="job", source="custom", includeAll=True, current=job),MetricsDashboardVariable(name="env", source="textbox", current=MetricsDashboardVariableSelection(values=["prod"])),- ]+ MetricsDashboardVariable(+ name="window",+ source="custom",+ current=MetricsDashboardVariableSelection(values=[selected_window]),+ ),+ ],))return runner@@ -479,15 +508,32 @@ class TestMetricsPromQLMode(APIBaseTest):) as request:all_jobs.calculate()+ expected_lookback = window if lookback == "$window" else lookbackassert (- request.call_args.kwargs["data"]["query"] == 'sum(rate(http_requests_total{env="prod"}[$__rate_interval]))'+ request.call_args.kwargs["data"]["query"]+ == 'sum(rate(http_requests_total{env="prod"}[' + expected_lookback + "]))")+ assert request.call_args.kwargs["data"]["step"] == str(step)assert all_jobs.get_cache_key() != runner_for(MetricsDashboardVariableSelection(values=["api"])).get_cache_key()+ assert (+ all_jobs.get_cache_key()+ != runner_for(MetricsDashboardVariableSelection(values=["api", "web"], all=True), "6h").get_cache_key()+ )- def test_unresolved_variable_is_explained_without_a_query(self) -> None:+ @parameterized.expand(+ [+ ("promql", 'up{job="$job"}', None, r"\$job"),+ ("interval", "up", "$window", r"\$window"),+ ]+ )+ def test_unresolved_variable_is_explained_without_a_query(+ self, _name: str, promql: str, interval: str | None, message: str+ ) -> None:+ runner = self._runner(promql)+ runner.query.interval = intervalwith patch("posthog.api.snuffle_proxy.internal_requests.request") as request:- with pytest.raises(ExposedHogQLError, match=r"\$job"):- self._runner('up{job="$job"}').calculate()+ with pytest.raises(ExposedHogQLError, match=message):+ runner.calculate()request.assert_not_called()def _sql_runner_with_all(self, source: str, query: str) -> MetricsQueryRunner:diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pyindex 82a60baa60aa..91df9a69b2d4 100644--- a/products/metrics/backend/tests/test_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -44,7 +44,8 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):def _runner(self, query: MetricsQuery) -> MetricsQueryRunner:return MetricsQueryRunner(query=query, team=self.team)- def test_translates_schema_node_to_facade_request(self) -> None:+ @parameterized.expand([("fixed", "minute"), ("dashboard_variable", "$window")])+ def test_translates_schema_node_to_facade_request(self, _name: str, interval: str) -> None:query = MetricsQuery(clauses=[MetricsQueryClause(@@ -58,11 +59,21 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):)],dateRange=DateRange(date_from="2026-09-19T00:00:00Z", date_to="2026-09-19T01:00:00Z"),- interval="minute",+ interval=interval,formula=None,)- request = self._runner(query)._to_request()+ runner = self._runner(query)+ runner.apply_dashboard_filters(+ DashboardFilter(+ metricVariables=[+ MetricsDashboardVariable(+ name="window", source="custom", current=MetricsDashboardVariableSelection(values=["1m"])+ )+ ]+ )+ )+ request = runner._to_request()clause = request.clauses[0]assert clause.metric_name == "http_requests_total"diff --git a/products/metrics/backend/tests/test_query_interval.py b/products/metrics/backend/tests/test_query_interval.pynew file mode 100644index 000000000000..a570c5e8503e--- /dev/null+++ b/products/metrics/backend/tests/test_query_interval.py@@ -0,0 +1,39 @@+import datetime as dt++import pytest++from products.metrics.backend.query_interval import resolve_query_interval+from products.metrics.backend.variables import Variable++START = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+++ "interval, values, is_all, hours, expected, error",+ [+ (None, (), False, 168, None, None),+ ("minute_5", (), False, 168, "minute_5", None),+ ("$window", ("1h",), False, 168, "hour", None),+ ("${window}", ("15m",), False, 6, "minute_15", None),+ ("$window", ("1m",), False, 168, None, "larger duration.*shorter date range"),+ ("$window", ("1h", "6h"), False, 168, None, "Select one duration"),+ ("$window", ("1h",), True, 168, None, "Select one duration"),+ ("$window", ("invalid",), False, 168, None, "Invalid chart interval"),+ ("prefix$window", ("1h",), False, 168, None, "single variable reference"),+ ],+)+def test_interval_variable_keeps_the_selected_spacing(+ interval: str | None,+ values: tuple[str, ...],+ is_all: bool,+ hours: int,+ expected: str | None,+ error: str | None,+) -> None:+ variables = {"window": Variable(values=values, is_all=is_all, all_value=None, options=())}+ end = START + dt.timedelta(hours=hours)+ if error:+ with pytest.raises(ValueError, match=error):+ resolve_query_interval(interval, variables, START, end)+ else:+ assert resolve_query_interval(interval, variables, START, end) == expecteddiff --git a/products/metrics/frontend/panels/metricsPartialBucket.test.ts b/products/metrics/frontend/panels/metricsPartialBucket.test.tsindex 0238819d733b..00a8eff4be12 100644--- a/products/metrics/frontend/panels/metricsPartialBucket.test.ts+++ b/products/metrics/frontend/panels/metricsPartialBucket.test.ts@@ -30,11 +30,16 @@ describe('partialBucketFraction', () => {const hourly = query([], { interval: 'hour' })it.each([- ['quarter into the last bucket', '2026-08-01T12:15:00Z', 0.25],- ['last bucket complete', '2026-08-01T13:00:00Z', null],- ['now before the last bucket', '2026-08-01T11:30:00Z', null],- ])('%s', (_, now, expected) => {- expect(partialBucketFraction(BUCKETS, hourly, 'UTC', dayjs(now))).toBe(expected)+ ['quarter into the last bucket', 'hour', '1h', '2026-08-01T12:15:00Z', 0.25],+ ['last bucket complete', 'hour', '1h', '2026-08-01T13:00:00Z', null],+ ['now before the last bucket', 'hour', '1h', '2026-08-01T11:30:00Z', null],+ ['hourly variable', '$window', '1h', '2026-08-01T12:15:00Z', 0.25],+ ['braced variable', '${window}', '15m', '2026-08-01T12:05:00Z', 1 / 3],+ ['formatted variable', '[[window:raw]]', '1m', '2026-08-01T12:00:15Z', 0.25],+ ['variable bucket complete', '$window', '1h', '2026-08-01T13:00:00Z', null],+ ])('%s', (_, interval, duration, now, expected) => {+ const q = query([], { interval, variables: { window: { values: [duration] } } })+ expect(partialBucketFraction(BUCKETS, q, 'UTC', dayjs(now))).toBe(expected)})it('uses the query interval, not the spacing of sparse buckets', () => {@@ -58,6 +63,20 @@ describe('partialBucketFraction', () => {it.each([['a fixed range end', query([], { interval: 'hour', dateRange: { date_to: '2026-08-01T12:15:00Z' } })],['buckets closer than the query interval', query([], { interval: 'day' })],+ ['missing interval variable', query([], { interval: '$window' })],+ ['empty interval selection', query([], { interval: '$window', variables: { window: { values: [] } } })],+ [+ 'multiple interval selections',+ query([], { interval: '$window', variables: { window: { values: ['1h', '6h'] } } }),+ ],+ [+ 'All interval selection',+ query([], { interval: '$window', variables: { window: { values: ['1h'], all: true } } }),+ ],+ [+ 'invalid interval duration',+ query([], { interval: '$window', variables: { window: { values: ['invalid'] } } }),+ ],['no query', undefined],])('stays solid for %s', (_, q) => {expect(partialBucketFraction(BUCKETS, q, 'UTC', dayjs('2026-08-01T12:15:00Z'))).toBeNull()diff --git a/products/metrics/frontend/panels/metricsPartialBucket.ts b/products/metrics/frontend/panels/metricsPartialBucket.tsindex 00b2344a1a5a..49f908ae02e8 100644--- a/products/metrics/frontend/panels/metricsPartialBucket.ts+++ b/products/metrics/frontend/panels/metricsPartialBucket.ts@@ -3,11 +3,12 @@ import { componentsToDayJs, dateStringToComponents, dateStringToDayJs } from 'liimport type { MetricsAggregation, MetricsQuery, MetricsQueryClause } from '~/queries/schema/schema-general'+import { ownValue, referencedNames } from '../components/dashboardVariables/metricVariables'import type { MetricsChartSeries } from '../components/metricsSeries'export type MetricsPartialBucketQuery = Pick<MetricsQuery,- 'clauses' | 'formula' | 'language' | 'dateRange' | 'interval'+ 'clauses' | 'formula' | 'language' | 'dateRange' | 'interval' | 'variables'>/** Below this share of the bucket, scaling up a few samples is mostly noise, so the real value stays. */@@ -16,17 +17,17 @@ export const MIN_EXTRAPOLATION_FRACTION = 0.1const DEFAULT_DATE_FROM = '-24h'const MINUTE_MS = 60_000/** Mirrors `_INTERVAL_LADDER`, `_TARGET_BUCKET_COUNT` and `_MAX_BUCKET_COUNT` in backend/metric_query_runner.py. */-const INTERVAL_LADDER: [string, number][] = [- ['second_15', 15_000],- ['second_30', 30_000],- ['minute', MINUTE_MS],- ['minute_5', 5 * MINUTE_MS],- ['minute_15', 15 * MINUTE_MS],- ['minute_30', 30 * MINUTE_MS],- ['hour', 60 * MINUTE_MS],- ['hour_6', 360 * MINUTE_MS],- ['day', 1440 * MINUTE_MS],- ['week', 10080 * MINUTE_MS],+const INTERVAL_LADDER: [string, number, string][] = [+ ['second_15', 15_000, '15s'],+ ['second_30', 30_000, '30s'],+ ['minute', MINUTE_MS, '1m'],+ ['minute_5', 5 * MINUTE_MS, '5m'],+ ['minute_15', 15 * MINUTE_MS, '15m'],+ ['minute_30', 30 * MINUTE_MS, '30m'],+ ['hour', 60 * MINUTE_MS, '1h'],+ ['hour_6', 360 * MINUTE_MS, '6h'],+ ['day', 1440 * MINUTE_MS, '1d'],+ ['week', 10080 * MINUTE_MS, '1w'],]const TARGET_BUCKET_COUNT = 60const MAX_BUCKET_COUNT = 500@@ -41,6 +42,14 @@ function resolveDateFrom(dateFrom: string, now: dayjs.Dayjs, timezone: string):}function resolvedIntervalMs(query: MetricsPartialBucketQuery, now: dayjs.Dayjs, timezone: string): number | null {+ const [variableName] = referencedNames(query.interval)+ if (variableName) {+ const variable = ownValue(query.variables ?? {}, variableName)+ if (!variable || variable.all || variable.values.length !== 1) {+ return null+ }+ return INTERVAL_LADDER.find(([, , duration]) => duration === variable.values[0])?.[1] ?? null+ }const from = resolveDateFrom(query.dateRange?.date_from ?? DEFAULT_DATE_FROM, now, timezone)if (!from) {return nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8e8278397658..5577d3471ac3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58979,7 +58979,7 @@ export namespace Schemas {}/**- * Values of the dashboard variables that the PromQL, SQL or filters refer to as `$name`.+ * Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`.*/export type MetricsQueryVariables = {[key: string]: MetricsVariableValue} | null;@@ -58992,7 +58992,7 @@ export namespace Schemas {display?: MetricsDisplaySettings | null;/** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */formula?: string | null;- /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Coarsened when the range would need more than 10,000 buckets. */+ /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable. */interval?: string | null;kind?: 'MetricsQuery';/** How the query is written; the builder when unset. */@@ -59005,7 +59005,7 @@ export namespace Schemas {/** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label. `{date_from}`, `{date_to}`, `{interval}` and `{interval_seconds}` are filled in from the date range and interval. */sql?: string | null;tags?: QueryLogTags | null;- /** Values of the dashboard variables that the PromQL, SQL or filters refer to as `$name`. */+ /** Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`. */variables?: MetricsQueryVariables;/** version of the node, used for schema migrations */version?: number | null;@@ -59040,7 +59040,7 @@ export namespace Schemas {}/**- * Values of the dashboard variables that the filters refer to as `$name`.+ * Values of the dashboard variables that the filters or interval refer to as `$name`.*/export type MetricsHistogramQueryVariables = {[key: string]: MetricsVariableValue} | null;@@ -59048,7 +59048,7 @@ export namespace Schemas {/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRange | null;filters?: MetricsQueryFilter[] | null;- /** Bucket size; auto-picked from the range when omitted */+ /** Bucket size; auto-picked from the range when omitted. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range. */interval?: string | null;kind?: 'MetricsHistogramQuery';metricName: string;@@ -59060,7 +59060,7 @@ export namespace Schemas {tags?: QueryLogTags | null;/** UCUM unit for the y-axis bounds, e.g. "s", "ms". Presentation only. */unit?: string | null;- /** Values of the dashboard variables that the filters refer to as `$name`. */+ /** Values of the dashboard variables that the filters or interval refer to as `$name`. */variables?: MetricsHistogramQueryVariables;/** version of the node, used for schema migrations */version?: number | null;