: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
fix(flags): support the {filters} placeholder on flag_evaluations (#117397)
Phil Haack919de078cbb2
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.pyindex 8ee93a2f0d2e..1a8cd331f760 100644--- a/posthog/hogql/filters.py+++ b/posthog/hogql/filters.py@@ -21,6 +21,7 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import Tablefrom posthog.hogql.database.schema.ai_events import AiEventsTablefrom posthog.hogql.database.schema.events import EventsTable+from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTablefrom posthog.hogql.database.schema.logs import LogAttributesTable, LogsTablefrom posthog.hogql.database.schema.persons import PersonsTable@@ -309,7 +310,7 @@ class ReplaceFilters(CloningVisitor):while last_join is not None:if isinstance(last_join.table, ast.Field):resolved = self._resolve_table(last_join.table.chain)- if isinstance(resolved, (EventsTable, AiEventsTable)):+ if isinstance(resolved, (EventsTable, AiEventsTable, FlagEvaluationsTable)):found_events = Trueif isinstance(resolved, SessionsTableV1 | SessionsTableV2 | SessionsTableV3):found_sessions = True@@ -327,7 +328,7 @@ class ReplaceFilters(CloningVisitor):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, groups or persons table."+ "Cannot use 'filters' placeholder in a SELECT clause that does not select from the events, ai_events, flag_evaluations, sessions, logs, traces, groups or persons table.")# Person semantics apply only when persons is the sole recognized table; any query that alsodiff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.pyindex 9ff2b784eb5d..76dbf9b4af72 100644--- a/posthog/hogql/test/test_filters.py+++ b/posthog/hogql/test/test_filters.py@@ -3,6 +3,7 @@ from typing import Any, Optionalimport time_machinefrom posthog.test.base import BaseTest+from unittest.mock import patchfrom parameterized import parameterized@@ -797,6 +798,64 @@ class TestFilters(BaseTest):f"greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",)+ def _print_flag_evaluations_filters(self, filters: HogQLFilters) -> str:+ # The org gate reads false under the test runner. A false gate prunes posthog.flag_evaluations+ # from the database. replace_filters and the printer each build their own database. The patch+ # must cover both builds.+ with patch(+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",+ return_value=True,+ ):+ select = replace_filters(+ self._parse_select("SELECT flag_key FROM posthog.flag_evaluations WHERE {filters}"),+ filters,+ self.team,+ )+ return self._print_ast(select)++ @parameterized.expand(+ [+ ("no_filters", HogQLFilters(), "true"),+ (+ "date_range",+ HogQLFilters(dateRange=DateRange(date_from="2020-02-02", date_to="2020-02-03 23:59:59")),+ "and(less(timestamp, toDateTime('2020-02-03 23:59:59.000000')), "+ "greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000')))",+ ),+ (+ "event_property",+ HogQLFilters(+ properties=[+ EventPropertyFilter(key="$feature_flag_response", operator="exact", value="test", type="event")+ ]+ ),+ "equals(properties.$feature_flag_response, 'test')",+ ),+ ]+ )+ def test_replace_filters_flag_evaluations(self, _name: str, filters: HogQLFilters, expected_where: str) -> None:+ self.assertEqual(+ self._print_flag_evaluations_filters(filters),+ f"SELECT flag_key FROM flag_evaluations WHERE {expected_where} LIMIT {MAX_SELECT_RETURNED_ROWS}",+ )++ def test_replace_filters_flag_evaluations_cohort(self) -> None:+ cohort = Cohort.objects.create(+ team=self.team,+ groups=[{"properties": [{"key": "email", "value": "posthog.com", "type": "person"}]}],+ )++ printed = self._print_flag_evaluations_filters(+ HogQLFilters(properties=[CohortPropertyFilter(key="id", value=cohort.pk, type="cohort")])+ )++ self.assertEqual(+ printed,+ "SELECT flag_key FROM flag_evaluations WHERE in(person_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_raises_for_unsupported_filters_placeholder(self):select = self._parse_select("SELECT dateTrunc({filters.granularity}, timestamp) FROM events WHERE {filters}")