: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(flags): look up person display names for only the page's flag calls (#110250)
Phil Haackaaee21a4804b
diff --git a/posthog/hogql/database/schema/flag_evaluations.py b/posthog/hogql/database/schema/flag_evaluations.pyindex 1fdfc3675de9..327ebd3631f5 100644--- a/posthog/hogql/database/schema/flag_evaluations.py+++ b/posthog/hogql/database/schema/flag_evaluations.py@@ -1,4 +1,7 @@-from posthog.hogql.database.lazy_join_tags import PERSON_DISTINCT_ID_OVERRIDES+from typing import TYPE_CHECKING++from posthog.hogql import ast+from posthog.hogql.database.lazy_join_tags import GROUP_N, PERSON_DISTINCT_ID_OVERRIDES, PERSONSfrom posthog.hogql.database.models import (DateTimeDatabaseField,ExpressionField,@@ -13,8 +16,14 @@ from posthog.hogql.database.models import (VirtualTable,)from posthog.hogql.database.schema.person_distinct_id_overrides import PersonDistinctIdOverridesTable+from posthog.hogql.database.schema.util.uuid import uuid_string_expr_to_uint128_exprfrom posthog.hogql.parser import parse_expr+from posthog.constants import GROUP_TYPES_LIMIT++if TYPE_CHECKING:+ from posthog.hogql.database.database import Database+# The physical read table is the Distributed `flag_evaluations` on the DATA nodes, defined in# posthog/models/flag_evaluations/sql.py. That module imports django.conf, and# posthog/hogql/test/test_no_django_imports.py imports this package with no django.setup(), so the@@ -169,3 +178,51 @@ class FlagEvaluationsTable(Table):def to_printed_hogql(self):return FLAG_EVALUATIONS_CLICKHOUSE_TABLE+++# The fields add_events_list_fields_to_flag_evaluations adds that join another table.+EVENTS_LIST_JOINED_FIELDS = frozenset({"person", "session", *(f"group_{index}" for index in range(GROUP_TYPES_LIMIT))})+++def add_events_list_fields_to_flag_evaluations(database: "Database") -> None:+ """Add the fields an events list reads to `posthog.flag_evaluations` in `database`, so a list query resolves there.++ This changes the table instance that `database` holds. Every later query compiled against `database` sees the wider+ table. Pass a database that only the events list runner uses, such as its `shared_database`.+ """+ flag_evaluations = database.get_table(["posthog", "flag_evaluations"])+ events_session = database.get_table("events").fields["session"]+ assert isinstance(events_session, LazyJoin)++ # This joins persons on the merge-corrected person_id, the way events does under+ # PERSON_ID_OVERRIDE_PROPERTIES_JOINED. The join is lazy. A query that reads no person field skips it.+ flag_evaluations.fields["person"] = LazyJoin(+ from_field=["person_id"], join_table=database.get_table("persons"), resolver=PERSONS+ )+ groups = database.get_table("groups")+ for index in range(GROUP_TYPES_LIMIT):+ flag_evaluations.fields[f"group_{index}"] = LazyJoin(+ from_field=[f"$group_{index}"], join_table=groups, resolver=GROUP_N, resolver_params={"group_index": index}+ )++ # The events session resolvers ignore from_field and read $session_id and $session_id_uuid from the source table.+ # Copying the events join keeps the sessions table version that the team's modifiers chose.+ flag_evaluations.fields["$session_id"] = ExpressionField(+ name="$session_id", expr=ast.Field(chain=["session_id"]), isolate_scope=True+ )+ flag_evaluations.fields["$session_id_uuid"] = ExpressionField(+ name="$session_id_uuid",+ expr=uuid_string_expr_to_uint128_expr(ast.Field(chain=["session_id"])),+ isolate_scope=True,+ )+ flag_evaluations.fields["session"] = events_session.model_copy()++ # The table stores no elements and no person mode. A flag call on events has no elements either.+ # An element filter therefore matches nothing on both tables. The empty array keeps its String element type.+ for name in ("elements_chain", "elements_chain_href", "person_mode"):+ flag_evaluations.fields[name] = ExpressionField(name=name, expr=ast.Constant(value=""))+ for name in ("elements_chain_texts", "elements_chain_ids", "elements_chain_elements"):+ flag_evaluations.fields[name] = ExpressionField(+ name=name,+ expr=ast.Call(name="arrayResize", args=[ast.Array(exprs=[ast.Constant(value="")]), ast.Constant(value=0)]),+ )diff --git a/posthog/hogql/database/schema/test/test_flag_evaluations.py b/posthog/hogql/database/schema/test/test_flag_evaluations.pyindex 336a2c7c1bb5..36999edc9888 100644--- a/posthog/hogql/database/schema/test/test_flag_evaluations.py+++ b/posthog/hogql/database/schema/test/test_flag_evaluations.py@@ -2,23 +2,43 @@ import jsonimport uuidfrom datetime import UTC, datetime, timedelta-from posthog.test.base import BaseTest, ClickhouseTestMixin+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patchfrom parameterized import parameterized+from posthog.schema import (+ ElementPropertyFilter,+ EventPropertyFilter,+ GroupPropertyFilter,+ PersonPropertyFilter,+ PropertyOperator,+ SessionPropertyFilter,+)++from posthog.hogql import astfrom posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.database.schema.flag_evaluations import add_events_list_fields_to_flag_evaluations+from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client import sync_executefrom posthog.constants import AvailableFeature+from posthog.hogql_queries.events_query_runner import SELECT_STAR_FROM_EVENTS_FIELDSfrom posthog.models import PropertyDefinition+from posthog.models.group.util import create_group+from posthog.models.utils import uuid7+from posthog.test.persons import create_group_type_mapping, create_personfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevelEVENT_PROBE = "from-event-properties"+# The sessions tables join only on a UUIDv7 session id.+SESSION_ID = str(uuid7())+# Compares greater than 9 as a number and less than it as a string, so the assertion tells the two# apart rather than passing under either.NUMERIC_PROBE = 10@@ -29,7 +49,7 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):super().setUp()self.row_uuid = uuid.uuid4()self.person_id = uuid.uuid4()- occurred_at = datetime.now(UTC) - timedelta(minutes=5)+ self.occurred_at = datetime.now(UTC) - timedelta(minutes=5)# The nine typed columns are DEFAULT-computed from `properties` on the sharded table, so a# producer cannot write them and this insert must not name them.sync_execute(@@ -46,17 +66,17 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):{"$feature_flag": "probe-flag","$feature_flag_response": "variant-x",- "$session_id": "sess-123",+ "$session_id": SESSION_ID,"$feature_flag_request_id": "req-456","$group_0": "acme","probe": EVENT_PROBE,"count": NUMERIC_PROBE,}),- occurred_at,+ self.occurred_at,self.team.pk,"probe-distinct-id",- occurred_at,+ self.occurred_at,str(self.person_id),)],@@ -113,7 +133,7 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):("probe-flag","variant-x",- "sess-123",+ SESSION_ID,"req-456","acme",self.person_id,@@ -184,7 +204,7 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):[("flag_key", "flag_key", "$feature_flag", "probe-flag"),("response", "response", "$feature_flag_response", "variant-x"),- ("session_id", "session_id", "$session_id", "sess-123"),+ ("session_id", "session_id", "$session_id", SESSION_ID),("request_id", "request_id", "$feature_flag_request_id", "req-456"),("group_key", "`$group_0`", "$group_0", "acme"),]@@ -216,3 +236,75 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):assert "probe" not in blobassert blob["$feature_flag"] == "probe-flag"++ @parameterized.expand(+ [+ ("event", EventPropertyFilter(key="probe", value=EVENT_PROBE, operator=PropertyOperator.EXACT), 1),+ (+ "person",+ PersonPropertyFilter(key="email", value="[email protected]", operator=PropertyOperator.EXACT),+ 1,+ ),+ (+ "group",+ GroupPropertyFilter(+ key="industry", value="software", operator=PropertyOperator.EXACT, group_type_index=0+ ),+ 1,+ ),+ (+ "session",+ SessionPropertyFilter(+ key="$entry_current_url", value="https://example.com/pricing", operator=PropertyOperator.EXACT+ ),+ 1,+ ),+ ("element_href", ElementPropertyFilter(key="href", value="/buy", operator=PropertyOperator.EXACT), 0),+ ("element_text", ElementPropertyFilter(key="text", value="Buy", operator=PropertyOperator.EXACT), 0),+ (+ "element_tag_name",+ ElementPropertyFilter(key="tag_name", value="button", operator=PropertyOperator.EXACT),+ 0,+ ),+ (+ "element_selector",+ ElementPropertyFilter(key="selector", value="button#buy", operator=PropertyOperator.EXACT),+ 0,+ ),+ ]+ )+ def test_events_shaped_table_reads_every_events_list_field(self, _name: str, prop, expected_rows: int):+ create_person(team=self.team, uuid=str(self.person_id), properties={"email": "[email protected]"})+ create_group_type_mapping(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )+ create_group(team_id=self.team.pk, group_type_index=0, group_key="acme", properties={"industry": "software"})+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="probe-distinct-id",+ timestamp=self.occurred_at,+ properties={"$session_id": SESSION_ID, "$current_url": "https://example.com/pricing"},+ )+ flush_persons_and_events()++ with patch(+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",+ return_value=True,+ ):+ database = Database.create_for(team=self.team)+ add_events_list_fields_to_flag_evaluations(database)+ response = execute_hogql_query(+ f"SELECT {', '.join(SELECT_STAR_FROM_EVENTS_FIELDS)} FROM posthog.flag_evaluations AS flag_evaluations "+ "WHERE uuid = {row_uuid} AND {filter}",+ team=self.team,+ placeholders={+ "row_uuid": ast.Constant(value=self.row_uuid),+ "filter": property_to_expr(prop, self.team),+ },+ context=HogQLContext(+ team_id=self.team.pk, team=self.team, user=self.user, enable_select_queries=True, database=database+ ),+ )++ assert len(response.results) == expected_rowsdiff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.pyindex ae26411ade28..12555e875204 100644--- a/posthog/hogql_queries/events_query_runner.py+++ b/posthog/hogql_queries/events_query_runner.py@@ -1,7 +1,9 @@import refrom datetime import datetime, timedeltafrom functools import cached_property+from itertools import batchedfrom typing import cast+from uuid import UUIDfrom django.utils.timezone import now@@ -23,8 +25,10 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.ast import Aliasfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.lazy_join_tags import GROUP_N, PERSONS-from posthog.hogql.database.models import ExpressionField, LazyJoin+from posthog.hogql.database.schema.flag_evaluations import (+ EVENTS_LIST_JOINED_FIELDS,+ add_events_list_fields_to_flag_evaluations,+)from posthog.hogql.parser import parse_expr, parse_order_exprfrom posthog.hogql.property import (action_to_expr,@@ -34,11 +38,11 @@ from posthog.hogql.property import (steps_to_expr,)from posthog.hogql.query import execute_hogql_query+from posthog.hogql.visitor import TraversingVisitorfrom posthog.api.element import ElementSerializerfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIESfrom posthog.clickhouse.query_tagging import tag_contains_user_hogql-from posthog.constants import GROUP_TYPES_LIMITfrom posthog.dataclasses import frozenfrom posthog.hogql_queries.insight_actors_query_runner import InsightActorsQueryRunnerfrom posthog.hogql_queries.paginators import HogQLHasMorePaginator@@ -80,6 +84,9 @@ class EventsListTable:chain: tuple[str, ...]alias: str | Noneperson_id: str+ looks_up_person_display_names: bool+ # Fields that join another table. The outer presorted query leaves out filters on them.+ joined_fields: frozenset[str]def join_expr(self) -> ast.JoinExpr:return ast.JoinExpr(table=ast.Field(chain=[*self.chain]), alias=self.alias)@@ -89,6 +96,8 @@ EVENTS_LIST_TABLE = EventsListTable(chain=("events",),alias=None,person_id="person.id",+ looks_up_person_display_names=False,+ joined_fields=frozenset(),)FLAG_EVALUATIONS_LIST_TABLE = EventsListTable(chain=("posthog", "flag_evaluations"),@@ -99,8 +108,31 @@ FLAG_EVALUATIONS_LIST_TABLE = EventsListTable(# The persons join reads a zero UUID from person.id for a distinct_id with no person row.# person_id holds the id that flag_evaluations resolved through person merges.person_id="person_id",+ # Reading person.properties in the query joins persons. That join deduplicates every person in the team before+ # the query picks the page. The runner reads display names for only the page's persons after the query, unless+ # the query sorts by Person and joins persons anyway.+ looks_up_person_display_names=True,+ joined_fields=EVENTS_LIST_JOINED_FIELDS,)++class _FieldUnderFinder(TraversingVisitor):+ def __init__(self, roots: frozenset[str]) -> None:+ super().__init__()+ self.roots = roots+ self.found = False++ def visit_field(self, node: ast.Field) -> None:+ if node.chain and node.chain[0] in self.roots:+ self.found = True+++def _reads_field_under(expr: ast.Expr, roots: frozenset[str]) -> bool:+ finder = _FieldUnderFinder(roots)+ finder.visit(expr)+ return finder.found++# Pagination cursors are encoded as ``<timestamp>|<uuid>`` so a stable uuid tiebreaker can advance# past events that share the boundary timestamp instead of dropping every tied row beyond the page# limit (which happens with a plain exclusive ``timestamp <`` filter). Coarse-precision sources such@@ -184,10 +216,25 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):self.source_runner.validate()def _person_display_name_key(self, table: EventsListTable) -> str:- property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES- props = person_display_name_property_exprs(property_keys, "person.properties")+ props = self._person_display_name_property_exprs("person.properties")return f"coalesce({', '.join([*props, 'distinct_id'])}), toString({table.person_id})"+ def _person_display_names_after_query(self, table: EventsListTable) -> bool:+ """Whether the page lookup fills person_display_name, rather than the page query.++ A sort by the Person column reads person.properties, which joins persons. The query then reads the names+ from that join, and the lookup does not run.+ """+ return table.looks_up_person_display_names and not self._sorts_by_person_display_name()++ def _sorts_by_person_display_name(self) -> bool:+ if self.query.orderBy is not None:+ return any(col.split("--")[0].strip() == "person_display_name" for col in self.query.orderBy)+ columns = self.select_input_raw()+ return columns[0].split("--")[0].strip() == "person_display_name" and self._default_order_is_first_column(+ columns, any(has_aggregation(parse_expr(column)) for column in columns)+ )+def select_cols(self, table: EventsListTable) -> tuple[list[str], list[ast.Expr]]:select_input: list[str] = []person_indices: list[int] = []@@ -201,7 +248,11 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):select_input.append("distinct_id")person_indices.append(index)elif col.split("--")[0].strip() == "person_display_name":- select_input.append(f"({self._person_display_name_key(table)}, distinct_id)")+ if self._person_display_names_after_query(table):+ # _expand_person_display_name_columns replaces distinct_id with the person's name.+ select_input.append(f"(distinct_id, toString({table.person_id}), distinct_id)")+ else:+ select_input.append(f"({self._person_display_name_key(table)}, distinct_id)")else:select_input.append(col)return select_input, [@@ -383,28 +434,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):context = self.build_hogql_context()assert context.database is not Noneif table is FLAG_EVALUATIONS_LIST_TABLE:- # flag_evaluations.person carries only the id, but the default columns and test account filters read- # person.properties. This joins persons the way events does under PERSON_ID_OVERRIDE_PROPERTIES_JOINED.- # The change applies only to this runner's database. Every other reader keeps the narrow person.- flag_evaluations = context.database.get_table([*table.chain])- flag_evaluations.fields["person"] = LazyJoin(- from_field=["person_id"],- join_table=context.database.get_table("persons"),- resolver=PERSONS,- )- # flag_evaluations has no elements_chain or person_mode column. Empty strings let `*`, a saved column,- # a filter, or an order by that names either one still resolve.- for name in ("elements_chain", "person_mode"):- flag_evaluations.fields[name] = ExpressionField(name=name, expr=ast.Constant(value=""))- # Group property filters, including test account filters, read group_N.properties as they do on events.- groups = context.database.get_table("groups")- for index in range(GROUP_TYPES_LIMIT):- flag_evaluations.fields[f"group_{index}"] = LazyJoin(- from_field=[f"$group_{index}"],- join_table=groups,- resolver=GROUP_N,- resolver_params={"group_index": index},- )+ add_events_list_fields_to_flag_evaluations(context.database)return contextdef _filter_where_exprs(self, table: EventsListTable) -> list[ast.Expr]:@@ -567,18 +597,20 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):columns.append(col)return [parse_order_expr(column, timings=self.timings) for column in columns]+ @staticmethod+ def _default_order_is_first_column(select_input: list[str], has_any_aggregation: bool) -> bool:+ return "count()" not in select_input and not has_any_aggregation and "timestamp" not in select_input+def _default_order_by(self, select_input: list[str], select: list[ast.Expr], aggregations: list[ast.Expr]) -> list[ast.OrderExpr]:+ if self._default_order_is_first_column(select_input, len(aggregations) > 0):+ return [ast.OrderExpr(expr=select[0], order="ASC")] if select else []if "count()" in select_input:return [ast.OrderExpr(expr=parse_expr("count()"), order="DESC")]if len(aggregations) > 0:return [ast.OrderExpr(expr=aggregations[0], order="DESC")]- if "timestamp" in select_input:- return [ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="DESC")]- if len(select) > 0:- return [ast.OrderExpr(expr=select[0], order="ASC")]- return []+ return [ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="DESC")]def _source_events_query(self,@@ -641,7 +673,18 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):)prefilter_sorted = parse_expr("uuid in ({inner_query})", {"inner_query": inner_query})- return ast.And(exprs=[prefilter_sorted, where]) if where is not None else prefilter_sorted+ outer_where = self._presorted_outer_where(table, where)+ return ast.And(exprs=[prefilter_sorted, outer_where]) if outer_where is not None else prefilter_sorted++ @staticmethod+ def _presorted_outer_where(table: EventsListTable, where: ast.Expr | None) -> ast.Expr | None:+ # The inner query applies every filter. The outer query keeps a filter only to narrow its own scan.+ # A filter that reads a joined field would join that table a second time.+ if where is None or not table.joined_fields:+ return where+ exprs = where.exprs if isinstance(where, ast.And) else [where]+ kept = [expr for expr in exprs if not _reads_field_under(expr, table.joined_fields)]+ return ast.And(exprs=kept) if kept else Nonedef _calculate(self) -> EventsQueryResponse:# Tag here (not in `to_query()`) so platform code that calls `to_query()` as a@@ -668,7 +711,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):if len(self.paginator.results) > 0:self._annotate_session_recordings()- person_indices = self._expand_person_display_name_columns()+ person_indices = self._expand_person_display_name_columns(table)# TODO: get rid of this logic once we don't use `person` columns anywhereif len(person_indices) > 0 and len(self.paginator.results) > 0:@@ -715,24 +758,78 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):if isinstance(session_id, str) and session_id:properties["$has_recording"] = session_id in session_recordings_map- def _expand_person_display_name_columns(self) -> list[int]:- """Convert each person_display_name tuple into a dict, and return the `person` column indices."""+ def _expand_person_display_name_columns(self, table: EventsListTable) -> list[int]:+ """Convert each person_display_name tuple into a dict, and return the `person` column indices.++ When the page lookup fills the names, this queries `persons` in ClickHouse for the page's person ids.+ """person_indices: list[int] = []+ display_name_indices: list[int] = []for column_index, col in enumerate(self.select_input_raw()):stripped = col.split("--")[0].strip()if stripped == "person":person_indices.append(column_index)if stripped == "person_display_name":- for index, result in enumerate(self.paginator.results):- row = list(self.paginator.results[index])- row[column_index] = {- "display_name": result[column_index][0],- "id": str(result[column_index][1]),- "distinct_id": str(result[column_index][2]),+ display_name_indices.append(column_index)++ names: dict[str, str] = {}+ if display_name_indices and self._person_display_names_after_query(table):+ with self.timings.measure("person_display_name_lookup"):+ names = self._person_display_names(+ {+ str(row[column_index][1])+ for row in self.paginator.results+ for column_index in display_name_indices}- self.paginator.results[index] = row+ )++ for column_index in display_name_indices:+ for index, result in enumerate(self.paginator.results):+ row = list(self.paginator.results[index])+ person_id = str(result[column_index][1])+ row[column_index] = {+ "display_name": names.get(person_id, result[column_index][0]),+ "id": person_id,+ "distinct_id": str(result[column_index][2]),+ }+ self.paginator.results[index] = rowreturn person_indices+ def _person_display_name_property_exprs(self, prefix: str) -> list[str]:+ property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES+ return person_display_name_property_exprs(property_keys, prefix)++ def _person_display_names(self, person_ids: set[str]) -> dict[str, str]:+ """Read display names from ClickHouse for only the given persons, keyed by person id."""+ name_exprs = [parse_expr(expr) for expr in self._person_display_name_property_exprs("properties")]+ names: dict[str, str] = {}+ # Sorting keeps the printed query the same for the same page.+ for batch in batched(sorted(person_ids), 1000, strict=False):+ # persons applies this id filter before it deduplicates person versions only when persons is the+ # query's own unaliased FROM. Under a join or an alias it deduplicates every person in the team first.+ query = ast.SelectQuery(+ select=[ast.Field(chain=["id"]), ast.Call(name="coalesce", args=name_exprs)],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["id"]),+ right=ast.Tuple(exprs=[ast.Constant(value=UUID(person_id)) for person_id in batch]),+ ),+ # Without a LIMIT, execute_hogql_query returns at most its default row count.+ limit=ast.Constant(value=len(batch)),+ )+ response = execute_hogql_query(+ query=query,+ team=self.team,+ user=self.user,+ query_type="EventsQueryPersonDisplayNames",+ timings=self.timings,+ modifiers=self.modifiers,+ context=self.build_hogql_context(),+ )+ names.update((str(person_id), name) for person_id, name in response.results if name)+ return names+def _expand_person_columns(self, person_indices: list[int]) -> None:with self.timings.measure("person_column_extra_query"):distinct_to_person = self._persons_by_distinct_id(person_indices[0])diff --git a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambrindex caff3c804432..b4d814b2816f 100644--- a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr+++ b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr@@ -289,6 +289,71 @@use_hive_partitioning=0'''# ---+# name: TestEventsQueryRunner.test_flag_evaluations_person_display_names_resolve_each_rows_person_id+ '''+ SELECT tuple(flag_evaluations.distinct_id, toString(if(not(empty(flag_evaluations__override.distinct_id)), flag_evaluations__override.person_id, flag_evaluations.person_id)), flag_evaluations.distinct_id)+ FROM flag_evaluations+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS flag_evaluations__override ON equals(flag_evaluations.distinct_id, flag_evaluations__override.distinct_id)+ WHERE and(equals(flag_evaluations.team_id, 99999), in(flag_evaluations.uuid,+ (SELECT flag_evaluations.uuid AS uuid+ FROM flag_evaluations+ WHERE and(equals(flag_evaluations.team_id, 99999), equals(flag_evaluations.event, '$feature_flag_called'), less(flag_evaluations.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), greater(flag_evaluations.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))+ ORDER BY toTimeZone(flag_evaluations.timestamp, 'UTC') ASC, flag_evaluations.uuid ASC+ LIMIT 101)), and(equals(flag_evaluations.event, '$feature_flag_called'), less(flag_evaluations.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), greater(flag_evaluations.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))+ ORDER BY toTimeZone(flag_evaluations.timestamp, 'UTC') ASC, flag_evaluations.uuid ASC+ LIMIT 101+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestEventsQueryRunner.test_flag_evaluations_person_display_names_resolve_each_rows_person_id.1+ '''+ SELECT persons.id AS id,+ coalesce(nullIf(toString(persons.properties___email), ''), nullIf(toString(persons.properties___name), ''), nullIf(toString(persons.properties___username), '')) AS `coalesce(nullIf(toString(properties.email), ''), nullIf(toString(properties.name), ''), nullIf(toString(properties.username), ''))`+ FROM+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'username'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___username,+ person.id AS id+ FROM person+ WHERE and(equals(person.team_id, 99999), in(id,+ (SELECT where_optimization.id AS id+ FROM person AS where_optimization+ WHERE and(equals(where_optimization.team_id, 99999), in(where_optimization.id, tuple(toUUIDOrNull('00000000-0000-4000-8000-000000000000'), toUUIDOrNull('00000000-0000-4000-8000-000000000001'), toUUIDOrNull('00000000-0000-4000-8000-000000000002'), toUUIDOrNull('0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b')))))))+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons+ WHERE in(persons.id,+ tuple(toUUIDOrNull('00000000-0000-4000-8000-000000000000'), toUUIDOrNull('00000000-0000-4000-8000-000000000001'), toUUIDOrNull('00000000-0000-4000-8000-000000000002'), toUUIDOrNull('0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b')))+ LIMIT 4 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestEventsQueryRunner.test_presorted_events_table'''SELECT tuple(events.uuid, events.event, events.properties, toTimeZone(events.timestamp, 'UTC'), events.team_id, events.distinct_id, events.elements_chain, toTimeZone(events.created_at, 'UTC'), events.person_mode) AS `tuple(uuid, event, properties, toTimeZone(timestamp, 'UTC'), team_id, distinct_id, elements_chain, toTimeZone(created_at, 'UTC'), person_mode)`diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.pyindex 20f6d54af8e6..b790699de7c0 100644--- a/posthog/hogql_queries/test/test_events_query_runner.py+++ b/posthog/hogql_queries/test/test_events_query_runner.py@@ -1,6 +1,7 @@+import reimport jsonimport uuid-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, castimport time_machine@@ -1234,13 +1235,13 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):organization=self.organization, defaults={"flag_evaluations_mode": mode})- def _create_flag_calls_in_both_tables(self, person_id: uuid.UUID | None = None) -> uuid.UUID:- self._create_events(- data=[("events-user", FLAG_CALL_TIMESTAMP.isoformat(), {"$feature_flag": EVENTS_FLAG_KEY})],- event="$feature_flag_called",- )- flush_persons_and_events()-+ def _insert_flag_evaluation(+ self,+ distinct_id: str,+ person_id: uuid.UUID,+ timestamp: datetime = FLAG_CALL_TIMESTAMP,+ properties: dict[str, Any] | None = None,+ ) -> uuid.UUID:row_uuid = uuid.uuid4()sync_execute("""@@ -1252,27 +1253,54 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):(str(row_uuid),"$feature_flag_called",- json.dumps(- {- "$feature_flag": FLAG_EVALUATIONS_FLAG_KEY,- "$feature_flag_response": "variant-a",- "$current_url": "https://example.com/pricing",- "$lib": "web",- "$group_0": FLAG_EVALUATIONS_GROUP_KEY,- }- ),- FLAG_CALL_TIMESTAMP,+ json.dumps(properties or {"$feature_flag": FLAG_EVALUATIONS_FLAG_KEY}),+ timestamp,self.team.pk,- FLAG_EVALUATIONS_DISTINCT_ID,- FLAG_CALL_TIMESTAMP,- str(person_id or uuid.uuid4()),+ distinct_id,+ timestamp,+ str(person_id),)],)return row_uuid- def test_flag_evaluations_only_organization_reads_flag_calls_from_flag_evaluations(self):+ def _create_flag_calls_in_both_tables(self, person_id: uuid.UUID | None = None) -> uuid.UUID:+ self._create_events(+ data=[("events-user", FLAG_CALL_TIMESTAMP.isoformat(), {"$feature_flag": EVENTS_FLAG_KEY})],+ event="$feature_flag_called",+ )+ flush_persons_and_events()++ return self._insert_flag_evaluation(+ FLAG_EVALUATIONS_DISTINCT_ID,+ person_id or uuid.uuid4(),+ properties={+ "$feature_flag": FLAG_EVALUATIONS_FLAG_KEY,+ "$feature_flag_response": "variant-a",+ "$current_url": "https://example.com/pricing",+ "$lib": "web",+ "$group_0": FLAG_EVALUATIONS_GROUP_KEY,+ },+ )++ @parameterized.expand(+ [+ (+ "person_property_filter",+ [PersonPropertyFilter(key="email", value=FLAG_EVALUATIONS_EMAIL, operator=PropertyOperator.EXACT)],+ False,+ ),+ ("test_account_filter", [], True),+ ]+ )+ def test_flag_evaluations_only_organization_reads_flag_calls_from_flag_evaluations(+ self, _name: str, person_filters: list[PersonPropertyFilter], filter_test_accounts: bool+ ):self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ self.team.test_account_filters = [+ {"key": "email", "type": "person", "value": "test-account", "operator": "not_icontains"}+ ]+ self.team.save()person = _create_person(team_id=self.team.pk,distinct_ids=[FLAG_EVALUATIONS_DISTINCT_ID],@@ -1287,7 +1315,17 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):group_key=FLAG_EVALUATIONS_GROUP_KEY,properties={"industry": "software"},)+ test_account = _create_person(+ team_id=self.team.pk,+ distinct_ids=["flag-test-account"],+ properties={"email": "[email protected]"},+ )row_uuid = self._create_flag_calls_in_both_tables(person_id=person.uuid)+ self._insert_flag_evaluation(+ "flag-test-account",+ test_account.uuid,+ properties={"$feature_flag": FLAG_EVALUATIONS_FLAG_KEY, "$group_0": FLAG_EVALUATIONS_GROUP_KEY},+ )with time_machine.travel("2020-01-11T12:01:00Z", tick=False):query = EventsQuery(@@ -1308,15 +1346,20 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):EventPropertyFilter(key="$feature_flag", value=FLAG_EVALUATIONS_FLAG_KEY, operator=PropertyOperator.EXACT),- PersonPropertyFilter(key="email", value=FLAG_EVALUATIONS_EMAIL, operator=PropertyOperator.EXACT),+ *person_filters,GroupPropertyFilter(key="industry", value="software", operator=PropertyOperator.EXACT, group_type_index=0),],+ filterTestAccounts=filter_test_accounts,after="-30d",)- response = EventsQueryRunner(query=query, team=self.team).run()+ with self.capture_select_queries() as queries:+ response = EventsQueryRunner(query=query, team=self.team).run()+ page_queries = [query for query in queries if re.search(r"\bFROM\s+flag_evaluations\b", query)]+ assert len(page_queries) == 1+ assert len(re.findall(r"\bAS\s+flag_evaluations__person\s+ON\b", page_queries[0])) == 1assert isinstance(response, CachedEventsQueryResponse)assert f"in(flag_key, tuple('{FLAG_EVALUATIONS_FLAG_KEY}'))" in response.hogqlassert "properties.$feature_flag," not in response.hogql@@ -1403,6 +1446,85 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert isinstance(response, CachedEventsQueryResponse)assert [row[0] for row in response.results] == [expected_flag_key]+ @snapshot_clickhouse_queries+ def test_flag_evaluations_person_display_names_resolve_each_rows_person_id(self):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ first = _create_person(+ team_id=self.team.pk, distinct_ids=["first-user"], properties={"email": "[email protected]"}+ )+ merged = _create_person(+ team_id=self.team.pk,+ distinct_ids=["merged-user", "merged-user-anon"],+ properties={"email": "[email protected]"},+ )+ unnamed = _create_person(team_id=self.team.pk, distinct_ids=["unnamed-user"], properties={"plan": "free"})+ flush_persons_and_events()+ orphan_person_id = uuid.UUID("0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b")+ self._insert_flag_evaluation("first-user", first.uuid)+ # The stored person_id has no person row. Only the override resolves this distinct_id to the merged person.+ self._insert_flag_evaluation("merged-user-anon", uuid.uuid4(), FLAG_CALL_TIMESTAMP + timedelta(seconds=1))+ self._insert_flag_evaluation("orphan-user", orphan_person_id, FLAG_CALL_TIMESTAMP + timedelta(seconds=2))+ self._insert_flag_evaluation("first-user", first.uuid, FLAG_CALL_TIMESTAMP + timedelta(seconds=3))+ self._insert_flag_evaluation("unnamed-user", unnamed.uuid, FLAG_CALL_TIMESTAMP + timedelta(seconds=4))+ sync_execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted) VALUES",+ [(self.team.pk, "merged-user-anon", str(merged.uuid), 1, 0)],+ )++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(+ kind="EventsQuery",+ select=["person_display_name -- Person"],+ event="$feature_flag_called",+ orderBy=["timestamp ASC"],+ after="-30d",+ )+ with self.capture_select_queries() as queries:+ response = EventsQueryRunner(query=query, team=self.team).run()++ page_queries = [query for query in queries if re.search(r"\bFROM\s+flag_evaluations\b", query)]+ assert len(page_queries) == 1+ assert not re.search(r"\bFROM\s+person\b", page_queries[0])+ lookup_queries = [query for query in queries if re.search(r"\bFROM\s+person\b", query)]+ assert len(lookup_queries) == 1+ assert lookup_queries[0].index("toUUIDOrNull") < lookup_queries[0].index("GROUP BY")+ assert isinstance(response, CachedEventsQueryResponse)+ assert [row[0] for row in response.results] == [+ {"display_name": "[email protected]", "id": str(first.uuid), "distinct_id": "first-user"},+ {"display_name": "[email protected]", "id": str(merged.uuid), "distinct_id": "merged-user-anon"},+ {"display_name": "orphan-user", "id": str(orphan_person_id), "distinct_id": "orphan-user"},+ {"display_name": "[email protected]", "id": str(first.uuid), "distinct_id": "first-user"},+ {"display_name": "unnamed-user", "id": str(unnamed.uuid), "distinct_id": "unnamed-user"},+ ]++ @parameterized.expand([("default_order", None), ("requested_order", ["person_display_name -- Person ASC"])])+ def test_flag_evaluations_sort_by_person_display_name(self, _name: str, order_by: list[str] | None):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ first_by_name = _create_person(+ team_id=self.team.pk, distinct_ids=["zz-user"], properties={"email": "[email protected]"}+ )+ last_by_name = _create_person(+ team_id=self.team.pk, distinct_ids=["aa-user"], properties={"email": "[email protected]"}+ )+ flush_persons_and_events()+ self._insert_flag_evaluation("aa-user", last_by_name.uuid)+ self._insert_flag_evaluation("zz-user", first_by_name.uuid)++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(+ kind="EventsQuery",+ select=["person_display_name -- Person"],+ event="$feature_flag_called",+ orderBy=order_by,+ after="-30d",+ )+ with self.capture_select_queries() as queries:+ response = EventsQueryRunner(query=query, team=self.team).run()++ assert len([query for query in queries if re.search(r"\bFROM\s+person\b", query)]) == 1+ assert isinstance(response, CachedEventsQueryResponse)+ assert [row[0]["display_name"] for row in response.results] == ["[email protected]", "[email protected]"]+def _enable_property_access_control(self) -> None:from posthog.constants import AvailableFeature@@ -1536,6 +1658,44 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert len(response.results) > 0assert response.results[0][0]["display_name"] == "Test User"+ def test_flag_evaluations_person_display_names_mask_restricted_person_properties(self):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ self._enable_property_access_control()+ person = _create_person(+ team_id=self.team.pk,+ distinct_ids=[FLAG_EVALUATIONS_DISTINCT_ID],+ properties={"email": FLAG_EVALUATIONS_EMAIL, "name": "Flag User"},+ )+ flush_persons_and_events()+ self._insert_flag_evaluation(FLAG_EVALUATIONS_DISTINCT_ID, person.uuid)+ prop_def = PropertyDefinition.objects.create(+ team=self.team,+ name="email",+ type=PropertyDefinition.Type.PERSON,+ )+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=prop_def,+ access_level=PropertyAccessLevel.NONE.value,+ )++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(+ kind="EventsQuery",+ select=["person_display_name -- Person"],+ event="$feature_flag_called",+ orderBy=["timestamp ASC"],+ after="-30d",+ )+ with self.capture_select_queries() as queries:+ response = EventsQueryRunner(query=query, team=self.team, user=self.user).run()++ page_queries = [query for query in queries if re.search(r"\bFROM\s+flag_evaluations\b", query)]+ assert len(page_queries) == 1+ assert not re.search(r"\bFROM\s+person\b", page_queries[0])+ assert isinstance(response, CachedEventsQueryResponse)+ assert [row[0]["display_name"] for row in response.results] == ["Flag User"]+@time_machine.travel("2020-01-11T12:00:05Z", tick=False)def test_users_with_different_restrictions_get_different_cache_keys(self):self._enable_property_access_control()