: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): support the persons table in the filters placeholder (#78705)
Thomas Obermüller68ebe9ce0e52
diff --git a/ee/hogai/tools/execute_sql/prompts.py b/ee/hogai/tools/execute_sql/prompts.pyindex 72204b03b025..9eeae1150382 100644--- a/ee/hogai/tools/execute_sql/prompts.py+++ b/ee/hogai/tools/execute_sql/prompts.py@@ -88,9 +88,9 @@ WHERE e.event IN (SELECT event FROM events WHERE ...)- 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`.+ - Plain `{filters}` can be used only in SELECT queries that select from PostHog event-like tables: `events`, `ai_events`, `sessions`, `logs`, log attributes, traces, `groups`, or `persons`.+ - Date filters map to `timestamp` for events/logs/traces, `$start_timestamp` for sessions, and `created_at` for groups and persons.+ - `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`, person scope on queries selecting only `persons`, 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.diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.pyindex eeb145d5ce58..78b6fca8a889 100644--- a/posthog/hogql/filters.py+++ b/posthog/hogql/filters.py@@ -22,6 +22,7 @@ from posthog.hogql.database.schema.ai_events import AiEventsTablefrom posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.groups import GroupsTablefrom posthog.hogql.database.schema.logs import LogAttributesTable, LogsTable+from posthog.hogql.database.schema.persons import PersonsTablefrom posthog.hogql.database.schema.sessions_v1 import SessionsTableV1from posthog.hogql.database.schema.sessions_v2 import SessionsTableV2from posthog.hogql.database.schema.sessions_v3 import SessionsTableV3@@ -253,6 +254,7 @@ class ReplaceFilters(CloningVisitor):found_logs = Falsefound_traces = Falsefound_groups = False+ found_persons = Falsewhile last_join is not None:if isinstance(last_join.table, ast.Field):resolved = self._resolve_table(last_join.table.chain)@@ -266,15 +268,24 @@ class ReplaceFilters(CloningVisitor):found_traces = Trueif isinstance(resolved, GroupsTable):found_groups = True+ if isinstance(resolved, PersonsTable):+ found_persons = Trueif found_events and found_sessions or found_groups:breaklast_join = last_join.next_join- if not any([found_events, found_sessions, found_logs, found_traces, found_groups]):+ if not any([found_events, found_sessions, found_logs, found_traces, found_groups, found_persons]):raise QueryError(- f"Cannot use 'filters' placeholder in a SELECT clause that does not select from the events, sessions, logs, traces or groups table."+ f"Cannot use 'filters' placeholder in a SELECT clause that does not select from the events, sessions, logs, traces, groups or persons table.")+ # Person semantics apply only when persons is the sole recognized table; any query that also+ # touches an event-like table keeps its existing scope, so events-joined-to-persons insights+ # are unaffected.+ persons_only = found_persons and not any(+ [found_events, found_sessions, found_logs, found_traces, found_groups]+ )+if no_filters:return ast.Constant(value=True)@@ -295,20 +306,28 @@ class ReplaceFilters(CloningVisitor):exprs.append(property_to_expr(non_session_properties, self.team, scope="event"))elif found_groups:exprs.append(property_to_expr(self.filters.properties, self.team, scope="group"))+ elif persons_only:+ exprs.append(property_to_expr(self.filters.properties, self.team, scope="person"))else:exprs.append(property_to_expr(self.filters.properties, self.team, scope="event"))timestamp_field = ast.Field(chain=["$start_timestamp"])if found_events or found_logs or found_traces:timestamp_field = ast.Field(chain=["timestamp"])- if found_groups:+ if found_groups or persons_only:timestamp_field = ast.Field(chain=["created_at"])exprs.extend(self._date_range_exprs(timestamp_field))if self.filters.filterTestAccounts:for prop in self.team.test_account_filters or []:- exprs.append(property_to_expr(prop, self.team))+ if persons_only:+ try:+ exprs.append(property_to_expr(prop, self.team, scope="person"))+ except (QueryError, NotImplementedError) as error:+ raise self._persons_test_account_filter_error(prop) from error+ else:+ exprs.append(property_to_expr(prop, self.team, scope="event"))if len(exprs) == 0:return ast.Constant(value=True)@@ -578,3 +597,15 @@ class ReplaceFilters(CloningVisitor):return QueryError("Numeric binning isn't supported by {filters.breakdown(...)}. Remove the bin count from the breakdown.")++ def _persons_test_account_filter_error(self, prop: Any) -> QueryError:+ # The filter comes from project settings rather than the query, so the bare scope error from+ # property_to_expr names something the reader never wrote and can't act on.+ prop_type = prop.get("type") if isinstance(prop, dict) else getattr(prop, "type", None)+ key = prop.get("key") if isinstance(prop, dict) else getattr(prop, "key", None)+ described = f"the {prop_type or 'unknown'} property filter" + (f" on '{key}'" if key else "")+ return QueryError(+ f"A test account filter in your project settings ({described}) can't apply to a query that "+ "selects only from persons. Change it to a person property filter in project settings, or "+ "bind it yourself with {filters(expr AS key, ...)}."+ )diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.pyindex a5fc5a720745..65db4e45a1bf 100644--- a/posthog/hogql/test/test_filters.py+++ b/posthog/hogql/test/test_filters.py@@ -30,6 +30,8 @@ from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.visitor import clear_locations+from products.cohorts.backend.models.cohort import Cohort+class TestFilters(BaseTest):maxDiff = None@@ -70,7 +72,7 @@ class TestFilters(BaseTest):)def test_raises_when_filters_empty_and_not_events_or_sessions(self):- select = self._parse_select("SELECT person FROM persons where {filters}")+ select = self._parse_select("SELECT type FROM heatmaps where {filters}")with self.assertRaisesMessage(QueryError,@@ -85,7 +87,7 @@ class TestFilters(BaseTest):replace_filters(select, HogQLFilters(), self.team)def test_raises_when_filters_and_not_events_or_sessions(self):- select = self._parse_select("SELECT person FROM persons where {filters}")+ select = self._parse_select("SELECT type FROM heatmaps where {filters}")with self.assertRaisesMessage(QueryError,@@ -500,7 +502,7 @@ class TestFilters(BaseTest):)def test_raises_when_filters_and_not_supported_table_includes_groups(self):- select = self._parse_select("SELECT person FROM persons where {filters}")+ select = self._parse_select("SELECT type FROM heatmaps where {filters}")with self.assertRaisesMessage(QueryError,@@ -508,6 +510,150 @@ class TestFilters(BaseTest):):replace_filters(select, HogQLFilters(dateRange=DateRange(date_from="2020-02-02")), self.team)+ def test_replace_filters_persons_empty(self):+ select = replace_filters(+ self._parse_select("SELECT id FROM persons where {filters}"),+ HogQLFilters(),+ self.team,+ )+ self.assertEqual(self._print_ast(select), f"SELECT id FROM persons WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}")++ select = replace_filters(+ self._parse_select("SELECT id FROM persons where {filters}"),+ None,+ self.team,+ )+ self.assertEqual(self._print_ast(select), f"SELECT id FROM persons WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}")++ def test_replace_filters_persons_date_range(self):+ with freeze_time("2020-02-15T13:37:42Z"):+ select = replace_filters(+ self._parse_select("SELECT id FROM persons where {filters}"),+ HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),+ 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')), "+ f"greaterOrEquals(created_at, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_replace_filters_persons_property(self):+ select = replace_filters(+ self._parse_select("SELECT id FROM persons where {filters}"),+ HogQLFilters(+ properties=[PersonPropertyFilter(key="email", operator="exact", value="[email protected]", type="person")]+ ),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE equals(properties.email, '[email protected]') LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_replace_filters_persons_event_property_raises(self):+ select = self._parse_select("SELECT id FROM persons where {filters}")++ with self.assertRaisesMessage(+ QueryError,+ "The 'event' property filter does not work in 'person' scope",+ ):+ replace_filters(+ select,+ HogQLFilters(+ properties=[EventPropertyFilter(key="$browser", operator="exact", value="Chrome", type="event")]+ ),+ self.team,+ )++ def test_replace_filters_persons_test_accounts(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}"),+ HogQLFilters(filterTestAccounts=True),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ f"SELECT id FROM persons WHERE notILike(toString(properties.email), '%posthog.com%') LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_replace_filters_persons_test_accounts_cohort(self):+ # The default test account filter on a new project excludes a cohort, and the cohort branch of+ # property_to_expr picks the right column per scope, so person scope resolves it fine.+ cohort = Cohort.objects.create(+ team=self.team,+ groups=[{"properties": [{"key": "email", "value": "posthog.com", "type": "person"}]}],+ )+ self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "not_in"}]+ self.team.save()++ select = replace_filters(+ self._parse_select("SELECT id FROM persons where {filters}"),+ HogQLFilters(filterTestAccounts=True),+ self.team,+ )+ # Printing expands the cohort into a subquery. The point of the assertion is the left side:+ # person scope binds the membership check to persons.id, and it resolves.+ self.assertEqual(+ self._print_ast(select),+ "SELECT id FROM persons WHERE notIn(id, (SELECT person_id FROM raw_cohort_people "+ f"WHERE equals(cohort_id, {cohort.pk}) GROUP BY person_id, cohort_id, version "+ f"HAVING greater(sum(sign), 0))) LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_replace_filters_persons_test_accounts_event_property_raises(self):+ self.team.test_account_filters = [+ {+ "key": "$host",+ "type": "event",+ "value": "localhost",+ "operator": "not_icontains",+ }+ ]+ self.team.save()++ select = self._parse_select("SELECT id FROM persons where {filters}")++ with self.assertRaisesMessage(+ QueryError,+ "A test account filter in your project settings (the event property filter on '$host') "+ "can't apply to a query that selects only from persons.",+ ):+ replace_filters(select, HogQLFilters(filterTestAccounts=True), self.team)++ def test_replace_filters_events_joined_with_persons_keep_event_scope(self):+ with freeze_time("2020-02-15T13:37:42Z"):+ select = replace_filters(+ self._parse_select(+ "SELECT event FROM events JOIN persons ON events.person_id = persons.id where {filters}"+ ),+ HogQLFilters(+ dateRange=DateRange(date_from="2020-02-02"),+ properties=[+ PersonPropertyFilter(key="email", operator="exact", value="[email protected]", type="person")+ ],+ ),+ self.team,+ )+ self.assertEqual(+ self._print_ast(select),+ "SELECT event FROM events JOIN persons ON equals(events.person_id, persons.id) WHERE "+ "and(equals(person.properties.email, '[email protected]'), "+ "lessOrEquals(timestamp, toDateTime('2020-02-15 23:59:59.999999')), "+ f"greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )+def test_raises_for_unsupported_filters_placeholder(self):select = self._parse_select("SELECT dateTrunc({filters.granularity}, timestamp) FROM events WHERE {filters}")