Skip to content

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

feat(hogql): interval and breakdown filters placeholders (#76718)

Thomas Obermüllercc4a4a223305
diff --git a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
index ab15ddde49c8..8eeb982d8862 100644
--- a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
+++ b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
@@ -270,7 +270,9 @@ class TestSQLMixins(NonAtomicBaseTest):
async def test_quality_check_output_with_unsupported_filter_placeholder(self):
mixin = self._node
- invalid_output = self._sql_output("SELECT dateTrunc({filters.interval}, timestamp) FROM events WHERE {filters}")
+ invalid_output = self._sql_output(
+ "SELECT dateTrunc({filters.granularity}, timestamp) FROM events WHERE {filters}"
+ )
with self.assertRaises(PydanticOutputParserException):
await mixin._quality_check_output(invalid_output)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index e9c1f169aa24..045e5cfae0bf 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -26967,12 +26967,20 @@
"additionalProperties": false,
"description": "Filters object that will be converted to a HogQL {filters} placeholder",
"properties": {
+ "breakdownFilter": {
+ "$ref": "#/definitions/BreakdownFilter",
+ "description": "Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown."
+ },
"dateRange": {
"$ref": "#/definitions/DateRange"
},
"filterTestAccounts": {
"type": "boolean"
},
+ "interval": {
+ "$ref": "#/definitions/IntervalType",
+ "description": "Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval."
+ },
"properties": {
"items": {
"$ref": "#/definitions/AnyPropertyFilter"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 01e892efa985..e7eb318a490f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -595,6 +595,10 @@ export interface HogQLFilters {
properties?: AnyPropertyFilter[]
dateRange?: DateRange
filterTestAccounts?: boolean
+ /** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
+ interval?: IntervalType
+ /** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
+ breakdownFilter?: BreakdownFilter
}
export interface HogQLVariable {
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index 9e8b499ccf7b..1b8a38a4f2b3 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -1,3 +1,5 @@
+import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { DashboardPlacement, DashboardTile, DashboardType, InsightModel, QueryBasedInsightModel } from '~/types'
@@ -5,6 +7,7 @@ import { DashboardPlacement, DashboardTile, DashboardType, InsightModel, QueryBa
import {
dashboardToSaveableTemplate,
getDashboardTileDisplayName,
+ getInsightWithRetry,
isWidgetTileVisibleOnPlacement,
parseURLFilters,
parseURLVariables,
@@ -132,6 +135,41 @@ describe('parseURLFilters', () => {
})
})
+describe('getInsightWithRetry', () => {
+ const insight = { id: 300, short_id: 'abc123', name: 'Test insight' } as QueryBasedInsightModel
+ const MAX_ATTEMPTS = 3
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it.each<[string, number, number | undefined]>([
+ ['a deterministic 400 (e.g. query validation error)', 1, 400],
+ ['a 429 (rate limited)', MAX_ATTEMPTS, 429],
+ ['a 500 (transient server error)', MAX_ATTEMPTS, 500],
+ ['a network failure without a status', MAX_ATTEMPTS, undefined],
+ ])('on %s, requests %i time(s) before throwing', async (_, expectedAttempts, status) => {
+ const getResponseSpy = jest.spyOn(api, 'getResponse').mockRejectedValue(new ApiError('some error', status))
+
+ await expect(
+ getInsightWithRetry(
+ 1,
+ insight,
+ 60,
+ 'query-id',
+ 'blocking',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ MAX_ATTEMPTS,
+ 1
+ )
+ ).rejects.toThrow('some error')
+ expect(getResponseSpy).toHaveBeenCalledTimes(expectedAttempts)
+ })
+})
+
describe('shouldSharedDashboardAutoForceForStaleTime', () => {
it.each<[string, dayjs.Dayjs | null, boolean]>([
['last refresh is null', null, false],
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 4fbdbbbf41fb..454dc6af9f19 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -381,6 +381,12 @@ export async function getInsightWithRetry(
throw e // Re-throw cancellation errors
}
+ // A 4xx response (e.g. a query validation error) is deterministic, so retrying
+ // would only replay the same failure — 429 excepted, which means "retry later"
+ if (e instanceof ApiError && e.status && e.status >= 400 && e.status < 500 && e.status !== 429) {
+ throw e
+ }
+
attempt++
if (attempt >= maxAttempts) {
throw e // Re-throw the error after max attempts
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.py
index 6b84cd53602e..eeb145d5ce58 100644
--- a/posthog/hogql/filters.py
+++ b/posthog/hogql/filters.py
@@ -5,7 +5,15 @@ from typing import Any, Optional, TypeVar, cast
from dateutil.parser import isoparse
-from posthog.schema import EmptyPropertyFilter, HogQLFilters, SessionPropertyFilter
+from posthog.schema import (
+ BreakdownFilter,
+ BreakdownType,
+ EmptyPropertyFilter,
+ HogQLFilters,
+ IntervalType,
+ MultipleBreakdownType,
+ SessionPropertyFilter,
+)
from posthog.hogql import ast
from posthog.hogql.database.database import Database
@@ -40,6 +48,12 @@ BOUND_FILTERS_USAGE = (
"e.g. {filters(created_at AS timestamp, account_id AS 'account_id')}. "
"Use null to skip a key, e.g. {filters(null AS timestamp)}."
)
+BOUND_BREAKDOWN_USAGE = (
+ "Each argument of {filters.breakdown(...)} must bind an expression to a breakdown key with AS, "
+ "e.g. {filters.breakdown(properties.plan AS 'plan')}. "
+ "Use null to skip a key, e.g. {filters.breakdown(null AS 'plan')}."
+)
+INTERVAL_UNITS = frozenset(interval.value for interval in IntervalType)
@dataclasses.dataclass
@@ -213,6 +227,22 @@ class ReplaceFilters(CloningVisitor):
if isinstance(node.expr, ast.Call) and node.expr.name == "filters":
return self._replace_bound_filters(node.expr)
+ # Dotted call forms: {filters.interval('week')} substitutes a granularity constant, and
+ # {filters.breakdown(expr AS key, ...)} substitutes the column bound to the selected breakdown.
+ if isinstance(node.expr, ast.ExprCall) and isinstance(node.expr.expr, ast.Field):
+ call_chain = node.expr.expr.chain
+ if call_chain == ["filters", "interval"]:
+ return self._replace_interval(node.expr.args)
+ if call_chain == ["filters", "breakdown"]:
+ return self._replace_breakdown(node.expr.args)
+ if call_chain and call_chain[0] == "filters":
+ chain_str = ".".join(str(c) for c in call_chain)
+ raise QueryError(
+ f"Unsupported filters placeholder `{{{chain_str}(...)}}`. "
+ "Supported call forms are: `{filters(expr AS key, ...)}`, `{filters.interval('day')}`, "
+ "and `{filters.breakdown(expr AS key, ...)}`."
+ )
+
no_filters = self.filters is None or not self.filters.model_fields_set
if node.chain == ["filters"]:
@@ -316,12 +346,22 @@ class ReplaceFilters(CloningVisitor):
compare_op_wrapper.skip = True
return ast.Constant(value=True)
+ if node.chain == ["filters", "interval"]:
+ return self._replace_interval([])
+
+ if node.chain == ["filters", "breakdown"]:
+ raise QueryError(
+ "{filters.breakdown} needs column bindings. "
+ "Write {filters.breakdown(expr AS 'key', ...)} to map breakdown keys onto your columns."
+ )
+
if node.chain and node.chain[0] == "filters":
chain_str = ".".join(str(c) for c in node.chain)
raise QueryError(
f"Unsupported filters placeholder `{{{chain_str}}}`. "
"Supported filters placeholders are: `{filters}`, `{filters.dateRange.from}`, `{filters.dateRange.to}`, "
- "and the column-bound form `{filters(expr AS key, ...)}`."
+ "`{filters.interval}`, and the column-bound forms `{filters(expr AS key, ...)}` and "
+ "`{filters.breakdown(expr AS key, ...)}`."
)
return super().visit_placeholder(node)
@@ -345,14 +385,21 @@ class ReplaceFilters(CloningVisitor):
return ast.And(exprs=exprs)
def _parse_bindings(self, call: ast.Call) -> dict[str, Optional[ast.Expr]]:
- if call.params is not None or call.distinct or not call.args:
+ if call.params is not None or call.distinct:
raise QueryError(BOUND_FILTERS_USAGE)
+ return self._parse_binding_args(call.args, BOUND_FILTERS_USAGE, "{filters(...)}")
+
+ def _parse_binding_args(
+ self, args: list[ast.Expr], usage: str, placeholder_label: str
+ ) -> dict[str, Optional[ast.Expr]]:
+ if not args:
+ raise QueryError(usage)
bindings: dict[str, Optional[ast.Expr]] = {}
- for arg in call.args:
+ for arg in args:
if not isinstance(arg, ast.Alias):
- raise QueryError(BOUND_FILTERS_USAGE)
+ raise QueryError(usage)
if arg.alias in bindings:
- raise QueryError(f"Filter key '{arg.alias}' is bound more than once in {{filters(...)}}.")
+ raise QueryError(f"Filter key '{arg.alias}' is bound more than once in {placeholder_label}.")
if isinstance(arg.expr, ast.Constant) and arg.expr.value is None:
# `null AS key` opts the query out of filters on that key.
bindings[arg.alias] = None
@@ -450,3 +497,84 @@ class ReplaceFilters(CloningVisitor):
if bound_expr is None:
return None
return bound_property_to_expr(property, bound_expr, self.team)
+
+ def _replace_interval(self, args: list[ast.Expr]) -> ast.Expr:
+ if len(args) > 1:
+ raise QueryError(
+ "{filters.interval(...)} takes at most one argument: the default interval, "
+ "e.g. {filters.interval('week')}."
+ )
+ default = "day"
+ if args:
+ arg = args[0]
+ if not isinstance(arg, ast.Constant) or arg.value not in INTERVAL_UNITS:
+ units = ", ".join(sorted(INTERVAL_UNITS))
+ raise QueryError(f"The default interval must be a constant string, one of: {units}.")
+ default = arg.value
+ if self.filters is not None and self.filters.interval is not None:
+ return ast.Constant(value=self.filters.interval.value)
+ return ast.Constant(value=default)
+
+ def _replace_breakdown(self, args: list[ast.Expr]) -> ast.Expr:
+ # Bindings are validated before checking whether a breakdown is set, so malformed usage
+ # surfaces in the SQL editor even while no breakdown is selected yet.
+ bindings = self._parse_binding_args(args, BOUND_BREAKDOWN_USAGE, "{filters.breakdown(...)}")
+ breakdown_filter = self.filters.breakdownFilter if self.filters is not None else None
+ key = self._resolve_breakdown_key(breakdown_filter)
+ if key is None:
+ # No breakdown selected: a constant key keeps the query valid and yields a single group.
+ return ast.Constant(value=None)
+ if key not in bindings:
+ raise QueryError(
+ f"The breakdown on '{key}' has no binding in {{filters.breakdown(...)}}. "
+ f"Bind a column like {{filters.breakdown(my_column AS '{key}')}} to apply it, "
+ f"or null AS '{key}' to skip it."
+ )
+ bound_expr = bindings[key]
+ if bound_expr is None:
+ return ast.Constant(value=None)
+ return clone_expr(bound_expr)
+
+ def _resolve_breakdown_key(self, breakdown_filter: Optional[BreakdownFilter]) -> Optional[str]:
+ if breakdown_filter is None:
+ return None
+ if breakdown_filter.breakdowns:
+ if len(breakdown_filter.breakdowns) > 1:
+ raise self._multiple_breakdowns_error()
+ single = breakdown_filter.breakdowns[0]
+ if single.type == MultipleBreakdownType.COHORT:
+ raise self._cohort_breakdown_error()
+ if single.histogram_bin_count is not None:
+ raise self._histogram_breakdown_error()
+ return str(single.property)
+ if breakdown_filter.breakdown is None:
+ return None
+ if breakdown_filter.breakdown_type == BreakdownType.COHORT:
+ raise self._cohort_breakdown_error()
+ if breakdown_filter.breakdown_histogram_bin_count is not None:
+ raise self._histogram_breakdown_error()
+ breakdown = breakdown_filter.breakdown
+ if isinstance(breakdown, list):
+ if len(breakdown) == 0:
+ return None
+ if len(breakdown) > 1:
+ raise self._multiple_breakdowns_error()
+ breakdown = breakdown[0]
+ return str(breakdown)
+
+ def _multiple_breakdowns_error(self) -> QueryError:
+ return QueryError(
+ "{filters.breakdown(...)} supports a single breakdown. "
+ "Remove the extra breakdowns from the dashboard or insight."
+ )
+
+ def _cohort_breakdown_error(self) -> QueryError:
+ return QueryError(
+ "Cohort breakdowns can't be applied through {filters.breakdown(...)}, because cohort "
+ "membership is resolved per person. Remove the cohort breakdown from the dashboard or insight."
+ )
+
+ def _histogram_breakdown_error(self) -> QueryError:
+ return QueryError(
+ "Numeric binning isn't supported by {filters.breakdown(...)}. Remove the bin count from the breakdown."
+ )
diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.py
index a044457957f8..18c3b47d39ab 100644
--- a/posthog/hogql/placeholders.py
+++ b/posthog/hogql/placeholders.py
@@ -39,6 +39,15 @@ class FindPlaceholders(TraversingVisitor):
# The column-bound form {filters(expr AS key, ...)} is resolved by replace_filters;
# classifying it as a generic expression placeholder would send it to the Hog VM instead.
self.has_filters = True
+ elif (
+ isinstance(node.expr, ast.ExprCall)
+ and isinstance(node.expr.expr, ast.Field)
+ and node.expr.expr.chain
+ and node.expr.expr.chain[0] == "filters"
+ ):
+ # Dotted call forms like {filters.interval('week')} and {filters.breakdown(...)} are
+ # resolved by replace_filters too.
+ self.has_filters = True
else:
self.placeholder_expressions.append(node.expr)
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index 6aa299d39b68..a5fc5a720745 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -6,6 +6,8 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
from posthog.schema import (
+ Breakdown,
+ BreakdownFilter,
CohortPropertyFilter,
DateRange,
ElementPropertyFilter,
@@ -14,6 +16,7 @@ from posthog.schema import (
GroupPropertyFilter,
HogQLFilters,
HogQLPropertyFilter,
+ IntervalType,
PersonPropertyFilter,
RecordingPropertyFilter,
)
@@ -506,11 +509,11 @@ class TestFilters(BaseTest):
replace_filters(select, HogQLFilters(dateRange=DateRange(date_from="2020-02-02")), self.team)
def test_raises_for_unsupported_filters_placeholder(self):
- select = self._parse_select("SELECT dateTrunc({filters.interval}, timestamp) FROM events WHERE {filters}")
+ select = self._parse_select("SELECT dateTrunc({filters.granularity}, timestamp) FROM events WHERE {filters}")
with self.assertRaisesMessage(
QueryError,
- "Unsupported filters placeholder `{filters.interval}`",
+ "Unsupported filters placeholder `{filters.granularity}`",
):
replace_filters(select, HogQLFilters(), self.team)
@@ -699,3 +702,157 @@ class TestFilters(BaseTest):
"The test account filter on 'email' has no binding in {filters(...)}",
):
replace_filters(select, HogQLFilters(filterTestAccounts=True), self.team)
+
+ @parameterized.expand(
+ [
+ ("bare_defaults_to_day", "{filters.interval}", HogQLFilters(), "day"),
+ ("bare_uses_dashboard_interval", "{filters.interval}", HogQLFilters(interval=IntervalType.WEEK), "week"),
+ ("call_argument_is_the_author_default", "{filters.interval('week')}", None, "week"),
+ (
+ "dashboard_interval_beats_author_default",
+ "{filters.interval('week')}",
+ HogQLFilters(interval=IntervalType.MONTH),
+ "month",
+ ),
+ ]
+ )
+ def test_interval_placeholder(self, _name, placeholder, filters, expected_unit):
+ select = replace_filters(
+ self._parse_select("SELECT dateTrunc(" + placeholder + ", timestamp) FROM events"),
+ filters,
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT dateTrunc('{expected_unit}', timestamp) FROM events LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ @parameterized.expand(
+ [
+ ("two_arguments", "{filters.interval('day', 'week')}", "takes at most one argument"),
+ ("non_constant_default", "{filters.interval(timestamp)}", "must be a constant string"),
+ ("unknown_unit", "{filters.interval('fortnight')}", "must be a constant string"),
+ ]
+ )
+ def test_interval_placeholder_usage_errors(self, _name, placeholder, expected_message):
+ select = self._parse_select(f"SELECT dateTrunc({placeholder}, timestamp) FROM events")
+ with self.assertRaisesMessage(QueryError, expected_message):
+ replace_filters(select, HogQLFilters(), self.team)
+
+ @parameterized.expand(
+ [
+ ("single_breakdown", BreakdownFilter(breakdown="plan", breakdown_type="event")),
+ ("single_entry_breakdowns_list", BreakdownFilter(breakdowns=[Breakdown(property="plan", type="event")])),
+ ]
+ )
+ def test_breakdown_placeholder_binds_the_selected_key(self, _name, breakdown_filter):
+ select = replace_filters(
+ self._parse_select(
+ "SELECT {filters.breakdown(properties.plan AS 'plan', properties.region AS 'region')} AS breakdown, "
+ "count() FROM persons GROUP BY breakdown"
+ ),
+ HogQLFilters(breakdownFilter=breakdown_filter),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ "SELECT properties.plan AS breakdown, count() FROM persons "
+ f"GROUP BY breakdown LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_breakdown_placeholder_without_breakdown_yields_single_group(self):
+ for filters in [None, HogQLFilters()]:
+ select = replace_filters(
+ self._parse_select(
+ "SELECT {filters.breakdown(properties.plan AS 'plan')} AS breakdown, count() "
+ "FROM persons GROUP BY breakdown"
+ ),
+ filters,
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT NULL AS breakdown, count() FROM persons GROUP BY breakdown LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_breakdown_placeholder_null_binding_opts_out(self):
+ select = replace_filters(
+ self._parse_select(
+ "SELECT {filters.breakdown(null AS 'plan')} AS breakdown, count() FROM persons GROUP BY breakdown"
+ ),
+ HogQLFilters(breakdownFilter=BreakdownFilter(breakdown="plan", breakdown_type="event")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT NULL AS breakdown, count() FROM persons GROUP BY breakdown LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_breakdown_placeholder_unbound_key_raises(self):
+ select = self._parse_select(
+ "SELECT {filters.breakdown(properties.region AS 'region')} AS breakdown, count() "
+ "FROM persons GROUP BY breakdown"
+ )
+ with self.assertRaisesMessage(
+ QueryError,
+ "The breakdown on 'plan' has no binding in {filters.breakdown(...)}",
+ ):
+ replace_filters(
+ select,
+ HogQLFilters(breakdownFilter=BreakdownFilter(breakdown="plan", breakdown_type="event")),
+ self.team,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "cohort_breakdown",
+ BreakdownFilter(breakdown=42, breakdown_type="cohort"),
+ "Cohort breakdowns can't be applied",
+ ),
+ (
+ "cohort_in_breakdowns_list",
+ BreakdownFilter(breakdowns=[Breakdown(property=42, type="cohort")]),
+ "Cohort breakdowns can't be applied",
+ ),
+ (
+ "histogram_binning",
+ BreakdownFilter(breakdown="plan", breakdown_type="event", breakdown_histogram_bin_count=10),
+ "Numeric binning isn't supported",
+ ),
+ (
+ "histogram_in_breakdowns_list",
+ BreakdownFilter(breakdowns=[Breakdown(property="plan", type="event", histogram_bin_count=10)]),
+ "Numeric binning isn't supported",
+ ),
+ (
+ "multiple_breakdowns",
+ BreakdownFilter(
+ breakdowns=[Breakdown(property="plan", type="event"), Breakdown(property="region", type="event")]
+ ),
+ "supports a single breakdown",
+ ),
+ ]
+ )
+ def test_breakdown_placeholder_unsupported_shapes_raise(self, _name, breakdown_filter, expected_message):
+ select = self._parse_select(
+ "SELECT {filters.breakdown(properties.plan AS 'plan')} AS breakdown FROM persons GROUP BY breakdown"
+ )
+ with self.assertRaisesMessage(QueryError, expected_message):
+ replace_filters(select, HogQLFilters(breakdownFilter=breakdown_filter), self.team)
+
+ @parameterized.expand(
+ [
+ ("bare_chain", "{filters.breakdown}", "needs column bindings"),
+ (
+ "positional_argument",
+ "{filters.breakdown(properties.plan)}",
+ "must bind an expression to a breakdown key",
+ ),
+ ("unsupported_call", "{filters.dateRange(day AS timestamp)}", "Unsupported filters placeholder"),
+ ]
+ )
+ def test_breakdown_placeholder_usage_errors(self, _name, placeholder, expected_message):
+ select = self._parse_select(f"SELECT {placeholder} AS breakdown FROM persons")
+ with self.assertRaisesMessage(QueryError, expected_message):
+ replace_filters(select, HogQLFilters(), self.team)
diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.py
index 027344b8af4f..7041a09e3b94 100644
--- a/posthog/hogql/test/test_placeholders.py
+++ b/posthog/hogql/test/test_placeholders.py
@@ -28,6 +28,15 @@ class TestParser(BaseTest):
self.assertEqual(finder.placeholder_fields, [["foo"]])
self.assertEqual(len(finder.placeholder_expressions), 1)
+ def test_find_placeholders_dotted_filters_calls(self):
+ # The dotted call forms must count as filters usage too; the Hog VM has no `filters` global.
+ # A dotted call on anything else stays an expression placeholder.
+ expr = parse_expr("{filters.interval('week')} and {filters.breakdown(a AS 'plan')} and {other.call(1)}")
+ finder = find_placeholders(expr)
+ self.assertTrue(finder.has_filters)
+ self.assertEqual(finder.placeholder_fields, [])
+ self.assertEqual(len(finder.placeholder_expressions), 1)
+
def test_replace_placeholders_simple(self):
expr = clear_locations(parse_expr("{foo}"))
self.assertEqual(
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index a4212e7fe36e..c05789f472b0 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -188,3 +188,13 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
if dashboard_filter.properties:
self.query.filters.properties = (self.query.filters.properties or []) + dashboard_filter.properties
+
+ if dashboard_filter.interval is not None:
+ self.query.filters.interval = dashboard_filter.interval
+
+ if dashboard_filter.breakdown_filter is not None:
+ self.query.filters.breakdownFilter = dashboard_filter.breakdown_filter
+
+ # Tri-state override: None means inherit the insight's own setting.
+ if dashboard_filter.filterTestAccounts is not None:
+ self.query.filters.filterTestAccounts = dashboard_filter.filterTestAccounts
diff --git a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py b/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
index 0513a1bbc2f0..f0e199ec16aa 100644
--- a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
+++ b/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
@@ -2,7 +2,17 @@ from typing import Optional
from posthog.test.base import BaseTest
-from posthog.schema import DashboardFilter, DateRange, EventPropertyFilter, HogQLFilters, HogQLQuery
+from parameterized import parameterized
+
+from posthog.schema import (
+ BreakdownFilter,
+ DashboardFilter,
+ DateRange,
+ EventPropertyFilter,
+ HogQLFilters,
+ HogQLQuery,
+ IntervalType,
+)
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
@@ -59,3 +69,31 @@ class TestHogQLDashboardFilters(BaseTest):
EventPropertyFilter(key="xyz", value="bar", operator="regex"),
]
)
+
+ def test_interval_is_copied_for_the_interval_placeholder(self):
+ query_runner = self._create_hogql_runner()
+ query_runner.apply_dashboard_filters(DashboardFilter(interval=IntervalType.WEEK))
+
+ assert query_runner.query.filters == HogQLFilters(interval=IntervalType.WEEK)
+
+ def test_breakdown_filter_is_copied_for_the_breakdown_placeholder(self):
+ breakdown_filter = BreakdownFilter(breakdown="plan", breakdown_type="event")
+ query_runner = self._create_hogql_runner()
+ query_runner.apply_dashboard_filters(DashboardFilter(breakdown_filter=breakdown_filter))
+
+ assert query_runner.query.filters == HogQLFilters(breakdownFilter=breakdown_filter)
+
+ @parameterized.expand(
+ [
+ ("force_on", None, True, True),
+ ("force_off_overrides_insight", True, False, False),
+ ("absent_inherits_insight", True, None, True),
+ ]
+ )
+ def test_filter_test_accounts_tri_state_override(
+ self, _name: str, insight_value: Optional[bool], override: Optional[bool], expected: Optional[bool]
+ ):
+ query_runner = self._create_hogql_runner(filters=HogQLFilters(filterTestAccounts=insight_value))
+ query_runner.apply_dashboard_filters(DashboardFilter(filterTestAccounts=override))
+
+ assert query_runner.query.filters == HogQLFilters(filterTestAccounts=expected)
diff --git a/posthog/schema.py b/posthog/schema.py
index 69b6d79f657f..ed7184794d0b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -16776,8 +16776,20 @@ class HogQLFilters(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ breakdownFilter: BreakdownFilter | None = Field(
+ default=None,
+ description=(
+ "Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown."
+ ),
+ )
dateRange: DateRange | None = None
filterTestAccounts: bool | None = None
+ interval: IntervalType | None = Field(
+ default=None,
+ description=(
+ "Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval."
+ ),
+ )
properties: list[AnyPropertyFilterDiscriminated] | None = None
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index d3775e767bea..802b4b8ca1cd 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -6042,8 +6042,12 @@ export interface PathsV2ActorsQueryApi {
}
export interface HogQLFiltersApi {
+ /** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
+ breakdownFilter?: BreakdownFilterApi | null
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
+ /** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
+ interval?: IntervalTypeApi | null
properties?:
| (
| EventPropertyFilterApi
diff --git a/products/product_analytics/backend/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.py
index 1ee56b29259e..7770f9221f53 100644
--- a/products/product_analytics/backend/models/test/test_insight_model.py
+++ b/products/product_analytics/backend/models/test/test_insight_model.py
@@ -171,6 +171,8 @@ class TestInsightModel(BaseTest):
},
"filterTestAccounts": None,
"properties": None,
+ "interval": None,
+ "breakdownFilter": None,
},
),
(
@@ -187,6 +189,8 @@ class TestInsightModel(BaseTest):
},
"filterTestAccounts": None,
"properties": None,
+ "interval": None,
+ "breakdownFilter": None,
},
),
(
@@ -203,6 +207,8 @@ class TestInsightModel(BaseTest):
},
"filterTestAccounts": None,
"properties": None,
+ "interval": None,
+ "breakdownFilter": None,
},
),
(
@@ -227,6 +233,8 @@ class TestInsightModel(BaseTest):
"dateRange": None,
"filterTestAccounts": None,
"properties": [browser_equals_chrome],
+ "interval": None,
+ "breakdownFilter": None,
},
),
(
@@ -237,6 +245,8 @@ class TestInsightModel(BaseTest):
"dateRange": None,
"filterTestAccounts": None,
"properties": [browser_equals_firefox, browser_equals_chrome],
+ "interval": None,
+ "breakdownFilter": None,
},
),
]
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 4274e6b1bdd3..b6fbe27ad4e8 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -5372,8 +5372,12 @@ export interface PathsV2ActorsQueryApi {
}
export interface HogQLFiltersApi {
+ /** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
+ breakdownFilter?: BreakdownFilterApi | null
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
+ /** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
+ interval?: IntervalTypeApi | null
properties?:
| (
| EventPropertyFilterApi
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ec4dee1881b7..697d2d355484 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4658,8 +4658,12 @@ export namespace Schemas {
}
export interface HogQLFilters {
+ /** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
+ breakdownFilter?: BreakdownFilter | null;
dateRange?: DateRange | null;
filterTestAccounts?: boolean | null;
+ /** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
+ interval?: IntervalType | null;
properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
}