: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(hogql): column-bound {filters(...)} placeholder (#76532)
Thomas Obermüllerf6e881bc6fbf
diff --git a/ee/hogai/tools/execute_sql/prompts.py b/ee/hogai/tools/execute_sql/prompts.pyindex 168f57a27549..f352457da0fb 100644--- a/ee/hogai/tools/execute_sql/prompts.py+++ b/ee/hogai/tools/execute_sql/prompts.py@@ -81,14 +81,18 @@ WHERE e.event IN (SELECT event FROM events WHERE ...)- You should not make formatting or casing changes if explicitly requested by the user.- You should not use double curly braces (`{{{{` or `}}}}`) for templating. The only templating syntax allowed is single curly braces with variables in the "variables" namespace (for example: `{{{{variables.org}}}}`).<%={{{{ }}}}=%>- SQL editor nodes can use `{filters}` placeholders. These placeholders are backed by `HogQLQuery.filters`, not by SQL text:- - If the current query contains `{filters}` and the user asks to change the date range or property filters, keep the placeholder in the SQL and pass updated `filters` to this tool.- - When keeping `{filters}` in the SQL, pass the complete desired `filters` object to this tool. Copy `current_query_node.source.filters` unchanged unless the user asked to change or remove filters.- - To remove all editor filters while preserving `{filters}`, pass an empty `filters` object (`{}`).- - Do not replace `{filters}` with explicit `timestamp` clauses when the user's request can be represented in `filters.dateRange`.- - Supported filter placeholders are `{filters}`, `{filters.dateRange.from}`, and `{filters.dateRange.to}`.- - `{filters}` can be used only in SELECT queries that select from PostHog event-like tables: `events`, `ai_events`, `sessions`, `logs`, log attributes, traces, or `groups`. It is not valid for arbitrary data warehouse/source tables.+ - If the current query contains `{filters}` or a column-bound `{filters(...)}` and the user asks to change the date range or property filters, keep the placeholder in the SQL and pass updated `filters` to this tool.+ - When keeping the placeholder in the SQL, pass the complete desired `filters` object to this tool. Copy `current_query_node.source.filters` unchanged unless the user asked to change or remove filters.+ - To remove all editor filters while preserving the placeholder, pass an empty `filters` object (`{}`).+ - Do not replace the placeholder with explicit `timestamp` clauses when the user's request can be represented in `filters.dateRange`.+ - Supported filter placeholders are `{filters}`, `{filters.dateRange.from}`, `{filters.dateRange.to}`, and the column-bound form `{filters(expr AS key, ...)}`.+ - Plain `{filters}` can be used only in SELECT queries that select from PostHog event-like tables: `events`, `ai_events`, `sessions`, `logs`, log attributes, traces, or `groups`.- Date filters map to `timestamp` for events/logs/traces, `$start_timestamp` for sessions, and `created_at` for groups.- `filters` can include `dateRange` (`date_from`, `date_to`), `filterTestAccounts`, and `properties`. Property filters apply to event scope on event/log/trace queries, group scope on `groups`, and session scope on `sessions` unless the query also includes `events`.+ - For any other table, view, or join (including data warehouse/source tables), use the column-bound form, for example `{filters(created_at AS timestamp, account_id AS 'account_id')}`:+ - The reserved key `timestamp` receives the date range. Any other key (a string alias like `'plan'` or `'$group_0'`) receives the property filters on that key, with full operator semantics.+ - `null AS key` opts the query out of filtering on that key. An active filter with no binding raises an error, so bind or explicitly opt out of every filter key in use.+ - Cohort filters and SQL-expression filters cannot be applied through bindings and raise an error if present.- If a filter is optional, ALWAYS implement via the variables namespace with guards:- ALWAYS use the "variables." prefix (e.g., variables.org, variables.browser) - never use bare variable names- Use coalesce() or IS NULL checks to handle optional valuesdiff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.pyindex 0da60a1b196c..0b1a37521c67 100644--- a/ee/hogai/tools/execute_sql/tool.py+++ b/ee/hogai/tools/execute_sql/tool.py@@ -47,10 +47,10 @@ class ExecuteSQLToolArgs(BaseModel):filters: HogQLFilters | None = Field(default=None,description=(- "Optional filters applied through `{filters}` placeholders in the query. "- "Use this when editing a SQL editor query that already uses `{filters}` and the user asks to change "+ "Optional filters applied through `{filters}` or column-bound `{filters(...)}` placeholders in the query. "+ "Use this when editing a SQL editor query that already uses such a placeholder and the user asks to change ""dateRange, property filters, or test-account filtering. Set this to an empty object to clear existing "- "SQL editor filters while preserving the `{filters}` placeholder."+ "SQL editor filters while preserving the placeholder."),)viz_title: str = Field(diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 5617bca35ad4..b32dc3561b50 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -26979,7 +26979,7 @@},"filters": {"$ref": "#/definitions/HogQLFilters",- "description": "Extra filters applied to query via {filters}"+ "description": "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"},"globals": {"description": "Extra globals for the query",@@ -27123,7 +27123,8 @@"type": "boolean"},"filters": {- "$ref": "#/definitions/HogQLFilters"+ "$ref": "#/definitions/HogQLFilters",+ "description": "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"},"kind": {"const": "HogQLQuery",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 6eae9f16df09..3c59f6a229da 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -611,6 +611,7 @@ export interface HogQLQuery extends DataNode<HogQLQueryResponse> {connectionId?: string/** Run the selected connection query directly without translating it through HogQL first */sendRawQuery?: boolean+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFilters/** Variables to be substituted into the query */variables?: Record<string, HogQLVariable>@@ -829,7 +830,7 @@ export interface HogQLMetadata extends DataNode<HogQLMetadataResponse> {sourceQuery?: AnyDataNode/** Extra globals for the query */globals?: Record<string, any>- /** Extra filters applied to query via {filters} */+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFilters/** Variables to be subsituted into the query */variables?: Record<string, HogQLVariable>diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.tsindex f7fdb413137d..d5761d5fe721 100644--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts@@ -18,6 +18,7 @@ describe('sql-utils', () => {test.each([['plain placeholder', 'SELECT * FROM events WHERE {filters}', true],['field placeholder', 'SELECT * FROM events WHERE {filters.properties}', true],+ ['column-bound placeholder', 'SELECT * FROM v WHERE {filters(day AS timestamp)}', true],['line-commented placeholder', 'SELECT * FROM events\n-- {filters}', false],['inline line-commented placeholder', 'SELECT * FROM events -- WHERE {filters}', false],['block-commented placeholder', 'SELECT * FROM events /* WHERE {filters} */', false],diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.tsindex a6f426d1bf5e..622d5cccebe8 100644--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts@@ -56,7 +56,7 @@ export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {continue}- if (query.startsWith('{filters}', i) || query.startsWith('{filters.', i)) {+ if (query.startsWith('{filters}', i) || query.startsWith('{filters.', i) || query.startsWith('{filters(', i)) {return true}diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.pyindex d5a38446bb53..6b84cd53602e 100644--- a/posthog/hogql/filters.py+++ b/posthog/hogql/filters.py@@ -1,11 +1,11 @@import reimport dataclassesfrom datetime import datetime-from typing import Optional, TypeVar, cast+from typing import Any, Optional, TypeVar, castfrom dateutil.parser import isoparse-from posthog.schema import HogQLFilters, SessionPropertyFilter+from posthog.schema import EmptyPropertyFilter, HogQLFilters, SessionPropertyFilterfrom posthog.hogql import astfrom posthog.hogql.database.database import Database@@ -19,10 +19,10 @@ from posthog.hogql.database.schema.sessions_v2 import SessionsTableV2from posthog.hogql.database.schema.sessions_v3 import SessionsTableV3from posthog.hogql.database.schema.spans import TraceSpansTablefrom posthog.hogql.errors import QueryError-from posthog.hogql.property import property_to_expr-from posthog.hogql.visitor import CloningVisitor+from posthog.hogql.property import bound_property_to_expr, property_to_expr+from posthog.hogql.visitor import CloningVisitor, clone_expr-from posthog.models import Team+from posthog.models import Property, Teamfrom posthog.utils import relative_date_parse_with_delta_mappingT = TypeVar("T", bound=ast.Expr)@@ -33,6 +33,14 @@ DATE_ONLY_REGEX = re.compile(r"^\d{4}-\d{1,2}-\d{1,2}$")# live views) where snapping to calendar boundaries would change the window's meaning.SUB_DAY_DELTA_KEYS = frozenset(["hours", "minutes", "seconds"])+# Reserved binding key in {filters(...)} that receives the date range instead of a property filter.+BOUND_TIMESTAMP_KEY = "timestamp"+BOUND_FILTERS_USAGE = (+ "Each argument of {filters(...)} must bind an expression to a filter key with AS, "+ "e.g. {filters(created_at AS timestamp, account_id AS 'account_id')}. "+ "Use null to skip a key, e.g. {filters(null AS timestamp)}."+)+@dataclasses.dataclassclass CompareOperationWrapper:@@ -146,6 +154,31 @@ class ReplaceFilters(CloningVisitor):return parsed_date, Falsereturn parsed_date.replace(hour=23, minute=59, second=59, microsecond=999999), True+ def _date_range_exprs(self, timestamp_expr: ast.Expr) -> list[ast.Expr]:+ """Comparisons pinning `timestamp_expr` inside the resolved date range. The expression is+ cloned per comparison, since bound expressions are caller-supplied AST that must not be+ shared between tree positions."""+ exprs: list[ast.Expr] = []+ date_to, date_to_inclusive = self._resolve_date_to()+ if date_to is not None:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq if date_to_inclusive else ast.CompareOperationOp.Lt,+ left=clone_expr(timestamp_expr),+ right=ast.Constant(value=date_to),+ )+ )+ date_from = self._resolve_date_from()+ if date_from is not None:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=clone_expr(timestamp_expr),+ right=ast.Constant(value=date_from),+ )+ )+ return exprs+def _resolve_table(self, chain: list) -> Optional[Table]:"""Resolve an AST field chain to the underlying database table, or None if not found."""if self.database is None:@@ -174,6 +207,12 @@ class ReplaceFilters(CloningVisitor):return nodedef visit_placeholder(self, node):+ # The column-bound form {filters(expr AS key, ...)}: the query author maps each filter key+ # onto an expression of their own query, so the table restrictions of plain {filters} don't+ # apply. A Call never has a chain, so the chain-based branches below can't match it.+ if isinstance(node.expr, ast.Call) and node.expr.name == "filters":+ return self._replace_bound_filters(node.expr)+no_filters = self.filters is None or not self.filters.model_fields_setif node.chain == ["filters"]:@@ -235,25 +274,7 @@ class ReplaceFilters(CloningVisitor):if found_groups:timestamp_field = ast.Field(chain=["created_at"])- date_to, date_to_inclusive = self._resolve_date_to()- if date_to is not None:- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.LtEq if date_to_inclusive else ast.CompareOperationOp.Lt,- left=timestamp_field,- right=ast.Constant(value=date_to),- )- )-- date_from = self._resolve_date_from()- if date_from is not None:- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=timestamp_field,- right=ast.Constant(value=date_from),- )- )+ exprs.extend(self._date_range_exprs(timestamp_field))if self.filters.filterTestAccounts:for prop in self.team.test_account_filters or []:@@ -299,7 +320,133 @@ class ReplaceFilters(CloningVisitor):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}`."+ "Supported filters placeholders are: `{filters}`, `{filters.dateRange.from}`, `{filters.dateRange.to}`, "+ "and the column-bound form `{filters(expr AS key, ...)}`.")return super().visit_placeholder(node)++ def _replace_bound_filters(self, call: ast.Call) -> ast.Expr:+ # Parse bindings before the no-filters early return, so malformed usage surfaces in the+ # SQL editor even while no filter is set yet.+ bindings = self._parse_bindings(call)++ if self.filters is None or not self.filters.model_fields_set:+ return ast.Constant(value=True)++ exprs: list[ast.Expr] = [+ *self._bound_date_range_exprs(bindings),+ *self._bound_property_exprs(bindings),+ ]+ if len(exprs) == 0:+ return ast.Constant(value=True)+ if len(exprs) == 1:+ return exprs[0]+ 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:+ raise QueryError(BOUND_FILTERS_USAGE)+ bindings: dict[str, Optional[ast.Expr]] = {}+ for arg in call.args:+ if not isinstance(arg, ast.Alias):+ raise QueryError(BOUND_FILTERS_USAGE)+ if arg.alias in bindings:+ raise QueryError(f"Filter key '{arg.alias}' is bound more than once in {{filters(...)}}.")+ 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+ else:+ bindings[arg.alias] = arg.expr+ return bindings++ def _bound_date_range_exprs(self, bindings: dict[str, Optional[ast.Expr]]) -> list[ast.Expr]:+ date_from = self._resolve_date_from()+ date_to, _date_to_inclusive = self._resolve_date_to()+ if date_from is None and date_to is None:+ return []+ if BOUND_TIMESTAMP_KEY not in bindings:+ # Silently not applying an active date filter would misrepresent the dashboard's state,+ # so the author has to either bind a time column or opt out explicitly.+ raise QueryError(+ "A date filter is set, but {filters(...)} has no timestamp binding. "+ "Bind your time column like {filters(created_at AS timestamp)}, "+ "or write null AS timestamp to exempt this query from date filtering."+ )+ timestamp_expr = bindings[BOUND_TIMESTAMP_KEY]+ if timestamp_expr is None:+ return []+ return self._date_range_exprs(timestamp_expr)++ def _bound_property_exprs(self, bindings: dict[str, Optional[ast.Expr]]) -> list[ast.Expr]:+ assert self.filters is not None+ sources: list[tuple[Any, bool]] = [(prop, False) for prop in self.filters.properties or []]+ if self.filters.filterTestAccounts:+ sources += [(prop, True) for prop in self.team.test_account_filters or []]+ exprs: list[ast.Expr] = []+ for prop, from_test_accounts in sources:+ expr = self._bound_property_expr(prop, bindings, from_test_accounts)+ if expr is not None:+ exprs.append(expr)+ return exprs++ def _bound_property_expr(+ self, prop: Any, bindings: dict[str, Optional[ast.Expr]], from_test_accounts: bool+ ) -> Optional[ast.Expr]:+ if isinstance(prop, EmptyPropertyFilter):+ return None+ try:+ if isinstance(prop, Property):+ property = prop+ elif isinstance(prop, dict):+ property = Property(**prop)+ else:+ property = Property(**prop.dict())+ except (ValueError, TypeError):+ # Incomplete saved filters apply nowhere, matching property_to_expr's behavior.+ return None++ if property.type == "flag":+ # Flag dependencies resolve at flag-matching time, never in HogQL; property_to_expr+ # treats them as neutral too.+ return None+ if property.type == "hogql":+ if from_test_accounts:+ raise QueryError(+ "The team's test account filters include a SQL expression, which can't be applied "+ "through {filters(...)} bindings. Turn off 'Filter out internal and test users' for this query."+ )+ raise QueryError(+ "SQL expression filters can't be applied through {filters(...)} bindings. "+ "Remove the SQL expression filter from the dashboard or insight."+ )+ if property.type in ("cohort", "static-cohort", "precalculated-cohort"):+ raise QueryError(+ "Cohort filters can't be applied through {filters(...)} bindings, because cohort "+ "membership is resolved per person. Remove the cohort filter from the dashboard or insight."+ )+ if property.type == "element":+ # Element filters match autocaptured DOM structure (selector regexes over elements_chain),+ # which a single bound column can't reproduce.+ raise QueryError(+ "Element filters match autocaptured elements and can't be applied through "+ "{filters(...)} bindings. Remove the element filter from the dashboard or insight."+ )+ if property.type == "recording":+ raise QueryError(+ "Session recording filters can't be applied through {filters(...)} bindings. "+ "Remove the recording filter from the dashboard or insight."+ )++ key = str(property.key)+ if key not in bindings:+ label = "test account filter" if from_test_accounts else "property filter"+ raise QueryError(+ f"The {label} on '{key}' has no binding in {{filters(...)}}. "+ f"Bind a column like {{filters(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 None+ return bound_property_to_expr(property, bound_expr, self.team)diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.pyindex f2b244453b00..a044457957f8 100644--- a/posthog/hogql/placeholders.py+++ b/posthog/hogql/placeholders.py@@ -35,6 +35,10 @@ class FindPlaceholders(TraversingVisitor):self.has_filters = Trueelse:self.placeholder_fields.append(chain)+ elif isinstance(node.expr, ast.Call) and node.expr.name == "filters":+ # 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 = Trueelse:self.placeholder_expressions.append(node.expr)diff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex 2083bce5f53e..a98d203e591e 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -1269,6 +1269,78 @@ def property_to_expr()+def bound_property_to_expr(property: Property, expr: ast.Expr, team: Team) -> ast.Expr:+ """Apply a property filter's operator and value to a caller-supplied expression, instead of+ resolving the filter's key to a table field. Backs the column-bound `{filters(...)}` placeholder,+ where the query author maps filter keys onto their own columns. Mirrors `property_to_expr`'s+ multi-value handling, without the events-table special cases that don't apply to bound columns."""+ operator = cast(Optional[PropertyOperator], property.operator) or PropertyOperator.EXACT+ value = property.value++ if property.key and GROUP_KEY_PATTERN.match(str(property.key)):+ value = _stringify_group_key_value(value)++ if isinstance(value, list) and operator not in (+ PropertyOperator.BETWEEN,+ PropertyOperator.NOT_BETWEEN,+ PropertyOperator.ICONTAINS,+ PropertyOperator.NOT_ICONTAINS,+ ):+ if len(value) == 0:+ return ast.Constant(value=1)+ if len(value) == 1:+ value = value[0]+ elif operator in (+ PropertyOperator.EXACT,+ PropertyOperator.IS_NOT,+ PropertyOperator.IN_,+ PropertyOperator.NOT_IN,+ ):+ op = (+ ast.CompareOperationOp.In+ if operator in (PropertyOperator.EXACT, PropertyOperator.IN_)+ else ast.CompareOperationOp.NotIn+ )+ return ast.CompareOperation(+ op=op,+ left=clone_expr(expr),+ right=ast.Tuple(exprs=[ast.Constant(value=v) for v in value]),+ )+ else:+ exprs = [+ bound_property_to_expr(+ Property(+ type=property.type,+ key=property.key,+ operator=property.operator,+ group_type_index=property.group_type_index,+ value=v,+ ),+ expr,+ team,+ )+ for v in value+ ]+ if (+ operator == PropertyOperator.IS_NOT+ or operator == PropertyOperator.NOT_ICONTAINS+ or operator == PropertyOperator.NOT_REGEX+ or operator == PropertyOperator.NOT_STARTS_WITH+ or operator == PropertyOperator.NOT_ENDS_WITH+ ):+ return ast.And(exprs=exprs)+ return ast.Or(exprs=exprs)++ return _expr_to_compare_op(+ expr=clone_expr(expr),+ value=value,+ operator=operator,+ property=property,+ is_json_field=False,+ team=team,+ )++def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optional[str] = None) -> ast.Expr:if len(steps) == 0:return ast.Constant(value=True)diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.pyindex 5bee69d14068..6aa299d39b68 100644--- a/posthog/hogql/test/test_filters.py+++ b/posthog/hogql/test/test_filters.py@@ -5,7 +5,18 @@ from posthog.test.base import BaseTestfrom parameterized import parameterized-from posthog.schema import DateRange, EventPropertyFilter, GroupPropertyFilter, HogQLFilters, PersonPropertyFilter+from posthog.schema import (+ CohortPropertyFilter,+ DateRange,+ ElementPropertyFilter,+ EventMetadataPropertyFilter,+ EventPropertyFilter,+ GroupPropertyFilter,+ HogQLFilters,+ HogQLPropertyFilter,+ PersonPropertyFilter,+ RecordingPropertyFilter,+)from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS@@ -502,3 +513,189 @@ class TestFilters(BaseTest):"Unsupported filters placeholder `{filters.interval}`",):replace_filters(select, HogQLFilters(), self.team)++ def test_bound_filters_date_range_and_property(self):+ # persons is a table the plain {filters} placeholder rejects, so this exercises the unlock+ with freeze_time("2020-02-15T13:37:42Z"):+ select = replace_filters(+ self._parse_select(+ "SELECT id FROM persons WHERE {filters(created_at AS timestamp, properties.plan AS 'plan')}"+ ),+ HogQLFilters(+ dateRange=DateRange(date_from="2020-02-02"),+ properties=[EventPropertyFilter(key="plan", operator="exact", value="hobby", type="event")],+ ),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ "SELECT id FROM persons WHERE "+ "and(lessOrEquals(created_at, toDateTime('2020-02-15 23:59:59.999999')), "+ "greaterOrEquals(created_at, toDateTime('2020-02-02 00:00:00.000000')), "+ f"equals(properties.plan, 'hobby')) LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_bound_filters_without_filters_resolve_to_true(self):+ for filters in [None, HogQLFilters()]:+ select = replace_filters(+ self._parse_select("SELECT id FROM persons WHERE {filters(created_at AS timestamp)}"),+ filters,+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_bound_filters_null_bindings_skip_filters(self):+ select = replace_filters(+ self._parse_select("SELECT id FROM persons WHERE {filters(null AS timestamp, null AS 'plan')}"),+ HogQLFilters(+ dateRange=DateRange(date_from="2020-02-02", date_to="2020-02-03"),+ properties=[EventPropertyFilter(key="plan", operator="exact", value="hobby", type="event")],+ ),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ @parameterized.expand(+ [+ (+ "multi_value_exact_in",+ EventPropertyFilter(key="plan", operator="exact", value=["hobby", "scale"], type="event"),+ "in(properties.plan, tuple('hobby', 'scale'))",+ ),+ (+ "multi_value_is_not",+ EventPropertyFilter(key="plan", operator="is_not", value=["hobby", "scale"], type="event"),+ "notIn(properties.plan, tuple('hobby', 'scale'))",+ ),+ (+ "person_property_binds_by_key",+ PersonPropertyFilter(key="plan", operator="icontains", value="hobby", type="person"),+ "ilike(toString(properties.plan), '%hobby%')",+ ),+ (+ "group_key_values_stringified",+ EventMetadataPropertyFilter(key="$group_0", operator="exact", value=[123, 456], type="event_metadata"),+ "in(properties.plan, tuple('123', '456'))",+ ),+ ]+ )+ def test_bound_filters_operator_semantics(self, _name, property_filter, expected_where):+ key = property_filter.key+ select = replace_filters(+ self._parse_select("SELECT id FROM persons WHERE {filters(properties.plan AS '" + key + "')}"),+ HogQLFilters(properties=[property_filter]),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE {expected_where} LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_bound_filters_unbound_property_raises(self):+ select = self._parse_select("SELECT id FROM persons WHERE {filters(null AS timestamp)}")+ with self.assertRaisesMessage(+ QueryError,+ "The property filter on 'plan' has no binding in {filters(...)}",+ ):+ replace_filters(+ select,+ HogQLFilters(+ properties=[EventPropertyFilter(key="plan", operator="exact", value="hobby", type="event")]+ ),+ self.team,+ )++ def test_bound_filters_date_range_requires_timestamp_binding(self):+ select = self._parse_select("SELECT id FROM persons WHERE {filters(properties.plan AS 'plan')}")++ with self.assertRaisesMessage(+ QueryError,+ "A date filter is set, but {filters(...)} has no timestamp binding",+ ):+ replace_filters(select, HogQLFilters(dateRange=DateRange(date_from="2020-02-02")), self.team)++ # without an active date filter the missing timestamp binding is fine+ select = replace_filters(+ self._parse_select("SELECT id FROM persons WHERE {filters(properties.plan AS 'plan')}"),+ HogQLFilters(properties=[EventPropertyFilter(key="plan", operator="exact", value="hobby", type="event")]),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE equals(properties.plan, 'hobby') LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ @parameterized.expand(+ [+ ("positional_argument", "{filters(created_at)}", "must bind an expression to a filter key with AS"),+ ("no_arguments", "{filters()}", "must bind an expression to a filter key with AS"),+ (+ "duplicate_binding",+ "{filters(created_at AS timestamp, id AS timestamp)}",+ "Filter key 'timestamp' is bound more than once",+ ),+ ]+ )+ def test_bound_filters_usage_errors(self, _name, placeholder, expected_message):+ select = self._parse_select(f"SELECT id FROM persons WHERE {placeholder}")+ with self.assertRaisesMessage(QueryError, expected_message):+ replace_filters(select, HogQLFilters(), self.team)++ @parameterized.expand(+ [+ (+ "cohort",+ CohortPropertyFilter(key="id", value=42, type="cohort"),+ "Cohort filters can't be applied through {filters(...)} bindings",+ ),+ (+ "hogql",+ HogQLPropertyFilter(key="properties.x = 1", type="hogql"),+ "SQL expression filters can't be applied through {filters(...)} bindings",+ ),+ (+ "element",+ ElementPropertyFilter(key="selector", operator="exact", value=".sign-up", type="element"),+ "Element filters match autocaptured elements and can't be applied through {filters(...)} bindings",+ ),+ (+ "recording",+ RecordingPropertyFilter(key="visited_page", operator="icontains", value="/pricing", type="recording"),+ "Session recording filters can't be applied through {filters(...)} bindings",+ ),+ ]+ )+ def test_bound_filters_unbindable_filter_types_raise(self, _name, property_filter, expected_message):+ select = self._parse_select("SELECT id FROM persons WHERE {filters(created_at AS timestamp)}")+ with self.assertRaisesMessage(QueryError, expected_message):+ replace_filters(select, HogQLFilters(properties=[property_filter]), self.team)++ def test_bound_filters_apply_test_account_filters(self):+ self.team.test_account_filters = [+ {"key": "email", "type": "person", "value": "posthog.com", "operator": "not_icontains"}+ ]+ self.team.save()++ select = replace_filters(+ self._parse_select("SELECT id FROM persons WHERE {filters(properties.email AS 'email')}"),+ HogQLFilters(filterTestAccounts=True),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ "SELECT id FROM persons WHERE "+ f"notILike(toString(properties.email), '%posthog.com%') LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ select = self._parse_select("SELECT id FROM persons WHERE {filters(null AS timestamp)}")+ with self.assertRaisesMessage(+ QueryError,+ "The test account filter on 'email' has no binding in {filters(...)}",+ ):+ replace_filters(select, HogQLFilters(filterTestAccounts=True), self.team)diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.pyindex 5786250cb9c4..027344b8af4f 100644--- a/posthog/hogql/test/test_placeholders.py+++ b/posthog/hogql/test/test_placeholders.py@@ -19,6 +19,15 @@ class TestParser(BaseTest):expr = parse_expr("{foo} and {bar.bah}")self.assertEqual(sorted(find_placeholders(expr).placeholder_fields), sorted([["foo"], ["bar", "bah"]]))+ def test_find_placeholders_bound_filters_call(self):+ # {filters(...)} must count as filters usage; classifying it as a generic expression+ # placeholder would send it to the Hog VM, which has no `filters` function+ expr = parse_expr("{filters(a AS timestamp, b AS 'plan')} and {foo} and {1 + 2}")+ finder = find_placeholders(expr)+ self.assertTrue(finder.has_filters)+ self.assertEqual(finder.placeholder_fields, [["foo"]])+ 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/schema.py b/posthog/schema.pyindex fcb4fda4769c..dedc68b85793 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -24963,7 +24963,12 @@ class HogQLQuery(BaseModel):),)explain: bool | None = None- filters: HogQLFilters | None = None+ filters: HogQLFilters | None = Field(+ default=None,+ description=(+ "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"+ ),+ )kind: Literal["HogQLQuery"] = "HogQLQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")name: str | None = Field(default=None, description="Client provided name of the query")@@ -28912,7 +28917,12 @@ class HogQLMetadata(BaseModel):default=None,description="Enable more verbose output, usually run from the /debug page",)- filters: HogQLFilters | None = Field(default=None, description="Extra filters applied to query via {filters}")+ filters: HogQLFilters | None = Field(+ default=None,+ description=(+ "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"+ ),+ )globals: dict[str, Any] | None = Field(default=None, description="Extra globals for the query")kind: Literal["HogQLMetadata"] = "HogQLMetadata"language: HogLanguage = Field(..., description="Language to validate")diff --git a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.pyindex b12ed1fcceb8..5e3dd8760bf4 100644--- a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py+++ b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py@@ -396,6 +396,9 @@ def _patched_terminalize_collaborators():patch("products.warehouse_sources.backend.facade.pipelines.BatchQueue") as batch_queue,patch("products.warehouse_sources.backend.facade.pipelines.mark_job_failed_if_not_terminal") as mark_failed,patch("products.warehouse_sources.backend.facade.pipelines.release_v3_pipeline_lock") as release_lock,+ # The real close_old_connections trips pytest-django's DB blocker when an+ # earlier test on the same xdist worker left an initialized connection.+ patch("django.db.close_old_connections"),):batch_queue.fail_batches_for_job_sync.return_value = 2yield batch_queue, mark_failed, release_lock@@ -433,7 +436,7 @@ def test_terminalize_keeps_batches_non_terminal_when_job_fail_write_errors() ->with _patched_terminalize_collaborators() as (batch_queue, mark_failed, _release_lock):mark_failed.side_effect = RuntimeError("app db unavailable")- with pytest.raises(RuntimeError):+ with pytest.raises(RuntimeError, match="app db unavailable"):_terminalize_stranded_runs(conn, "sourcebatch_20000101") # type: ignore[arg-type]batch_queue.fail_batches_for_job_sync.assert_not_called()diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex efb1a0efb995..0dbfbfb6c158 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -6130,6 +6130,7 @@ export interface HogQLQueryApi {/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */connectionId?: string | nullexplain?: boolean | null+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFiltersApi | nullkind?: 'HogQLQuery'/** Modifiers used when performing the query */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex fe0f1a9037e8..3bf8a8431560 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -5460,6 +5460,7 @@ export interface HogQLQueryApi {/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */connectionId?: string | nullexplain?: boolean | null+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFiltersApi | nullkind?: 'HogQLQuery'/** Modifiers used when performing the query */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 30e9673f7979..d919e4b8c1e4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4745,6 +4745,7 @@ export namespace Schemas {/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */connectionId?: string | null;explain?: boolean | null;+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFilters | null;kind?: 'HogQLQuery';/** Modifiers used when performing the query */@@ -38849,7 +38850,7 @@ export namespace Schemas {connectionId?: string | null;/** Enable more verbose output, usually run from the /debug page */debug?: boolean | null;- /** Extra filters applied to query via {filters} */+ /** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */filters?: HogQLFilters | null;/** Extra globals for the query */globals?: HogQLMetadataGlobals;