Skip to content

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

chore(hogql): split events query runner into focused helpers (#98117)

Paul D'Ambrac07b5ca13a1d
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index 920d714cea25..6f09a1f778be 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -25,6 +25,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.element import ElementSerializer
from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
+from posthog.dataclasses import frozen
from posthog.hogql_queries.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.hogql_queries.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runner
@@ -63,6 +64,30 @@ WIDE_COLUMNS = {"elements_chain", "properties"}
CURSOR_DELIMITER = "|"
+@frozen
+class TimestampBoundary:
+ plain: str
+ with_uuid_tiebreaker: str
+
+
+BEFORE_BOUNDARY = TimestampBoundary(
+ plain="timestamp < {boundary}",
+ with_uuid_tiebreaker="timestamp < {boundary} OR (timestamp = {boundary_eq} AND uuid < {boundary_uuid})",
+)
+AFTER_BOUNDARY = TimestampBoundary(
+ plain="timestamp > {boundary}",
+ with_uuid_tiebreaker="timestamp > {boundary} OR (timestamp = {boundary_eq} AND uuid > {boundary_uuid})",
+)
+
+
+def and_exprs(existing: ast.Expr | None, extra: ast.Expr | None) -> ast.Expr | None:
+ if extra is None:
+ return existing
+ if existing is None:
+ return extra
+ return ast.And(exprs=[existing, extra])
+
+
def split_pagination_cursor(value: str) -> tuple[str, str | None]:
"""Split a ``<timestamp>|<uuid>`` cursor. Plain user-supplied date filters have no delimiter and
pass through unchanged with a ``None`` tiebreaker."""
@@ -247,140 +272,8 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
aggregations: list[ast.Expr] = [column for column in select if has_aggregation(column)]
has_any_aggregation = len(aggregations) > 0
- # filters
- with self.timings.measure("filters"):
- with self.timings.measure("where"):
- where_input = self.query.where or []
- where_exprs = [parse_expr(expr, timings=self.timings) for expr in where_input]
- if self.query.properties:
- with self.timings.measure("properties"):
- where_exprs.extend(property_to_expr(property, self.team) for property in self.query.properties)
- if self.query.fixedProperties:
- with self.timings.measure("fixed_properties"):
- where_exprs.extend(
- property_to_expr(property, self.team) for property in self.query.fixedProperties
- )
- all_events: list[str] = [e for e in [self.query.event, *(self.query.events or [])] if e]
- if all_events:
- with self.timings.measure("event"):
- if len(all_events) == 1:
- where_exprs.append(
- parse_expr(
- "event = {event}",
- {"event": ast.Constant(value=all_events[0])},
- timings=self.timings,
- )
- )
- else:
- where_exprs.append(
- ast.CompareOperation(
- op=ast.CompareOperationOp.In,
- left=ast.Field(chain=["event"]),
- right=ast.Tuple(exprs=[ast.Constant(value=e) for e in all_events]),
- )
- )
- if self.query.actionId:
- with self.timings.measure("action_id"):
- try:
- action = Action.objects.get(pk=self.query.actionId, team__project_id=self.team.project_id)
- except Action.DoesNotExist:
- raise Exception("Action does not exist")
- if not action.steps:
- raise Exception("Action does not have any match groups")
- where_exprs.append(action_to_expr(action))
- elif self.query.actionSteps:
- with self.timings.measure("action_steps"):
- steps = [
- ActionStepJSON(
- event=s.event,
- tag_name=s.tag_name,
- text=s.text,
- text_matching=s.text_matching.value if s.text_matching else None,
- href=s.href,
- href_matching=s.href_matching.value if s.href_matching else None,
- selector=s.selector,
- url=s.url,
- url_matching=s.url_matching.value if s.url_matching else None,
- properties=[p.model_dump() for p in s.properties] if s.properties else None,
- )
- for s in self.query.actionSteps
- ]
- where_exprs.append(steps_to_expr(steps, self.team))
- if self.query.personId:
- with self.timings.measure("person_id"), personhog_caller_tag("persons/events-query"):
- person: Person | None = get_person_by_pk_or_uuid(
- self.team.pk, self.query.personId, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS
- )
- where_exprs.append(
- ast.CompareOperation(
- left=ast.Call(name="cityHash64", args=[ast.Field(chain=["distinct_id"])]),
- right=ast.Tuple(
- exprs=[
- ast.Call(name="cityHash64", args=[ast.Constant(value=id)])
- for id in get_distinct_ids_for_subquery(person, self.team)
- ]
- ),
- op=ast.CompareOperationOp.In,
- )
- )
- if self.query.filterTestAccounts:
- with self.timings.measure("test_account_filters"):
- for prop in self.team.test_account_filters or []:
- where_exprs.append(property_to_expr(prop, self.team))
-
- with self.timings.measure("timestamps"):
- # prevent accidentally future events from being visible by default
- before = self.query.before or (now() + timedelta(seconds=5)).isoformat()
- before_timestamp, before_uuid = split_pagination_cursor(before)
- parsed_date = relative_date_parse(before_timestamp, self.team.timezone_info)
- if before_uuid:
- # Advance past events sharing the boundary timestamp using uuid as a tiebreaker,
- # matching the ``timestamp DESC, uuid DESC`` ordering applied below.
- where_exprs.append(
- parse_expr(
- "timestamp < {before} OR (timestamp = {before_eq} AND uuid < {before_uuid})",
- {
- "before": ast.Constant(value=parsed_date),
- "before_eq": ast.Constant(value=parsed_date),
- "before_uuid": ast.Call(name="toUUID", args=[ast.Constant(value=before_uuid)]),
- },
- timings=self.timings,
- )
- )
- else:
- where_exprs.append(
- parse_expr(
- "timestamp < {timestamp}",
- {"timestamp": ast.Constant(value=parsed_date)},
- timings=self.timings,
- )
- )
-
- # limit to the last 24h by default
- after = self.query.after or "-24h"
- if after != "all":
- after_timestamp, after_uuid = split_pagination_cursor(after)
- parsed_date = relative_date_parse(after_timestamp, self.team.timezone_info)
- if after_uuid:
- where_exprs.append(
- parse_expr(
- "timestamp > {after} OR (timestamp = {after_eq} AND uuid > {after_uuid})",
- {
- "after": ast.Constant(value=parsed_date),
- "after_eq": ast.Constant(value=parsed_date),
- "after_uuid": ast.Call(name="toUUID", args=[ast.Constant(value=after_uuid)]),
- },
- timings=self.timings,
- )
- )
- else:
- where_exprs.append(
- parse_expr(
- "timestamp > {timestamp}",
- {"timestamp": ast.Constant(value=parsed_date)},
- timings=self.timings,
- )
- )
+ where_exprs = self._filter_where_exprs()
+ where_exprs.extend(self._timestamp_where_exprs())
# where & having
with self.timings.measure("where"):
@@ -389,99 +282,244 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
having_list = [expr for expr in where_exprs if has_aggregation(expr)]
having: ast.Expr | None = ast.And(exprs=having_list) if len(having_list) > 0 else None
- # order by
- with self.timings.measure("order"):
- if self.query.orderBy is not None:
- columns: list[str] = []
- for _, col in enumerate(self.query.orderBy):
- if col.split("--")[0].strip() == "person_display_name":
- property_keys = (
- self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
- )
- props = person_display_name_property_exprs(property_keys, "person.properties")
- expr = f"(coalesce({', '.join([*props, 'distinct_id'])}), toString(person.id))"
- newCol = re.sub(r"person_display_name -- Person ", expr, col)
- columns.append(newCol)
- else:
- columns.append(col)
- order_by = [parse_order_expr(column, timings=self.timings) for column in columns]
- elif "count()" in select_input:
- order_by = [ast.OrderExpr(expr=parse_expr("count()"), order="DESC")]
- elif len(aggregations) > 0:
- order_by = [ast.OrderExpr(expr=aggregations[0], order="DESC")]
- elif "timestamp" in select_input:
- order_by = [ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="DESC")]
- elif len(select) > 0:
- order_by = [ast.OrderExpr(expr=select[0], order="ASC")]
- else:
- order_by = []
-
- first_order = order_by[0].expr if order_by else None
- self._cursor_eligible = (
- self.query.source is None
- and not has_any_aggregation
- and isinstance(first_order, ast.Field)
- and first_order.chain == ["timestamp"]
- )
-
- # When ordering by timestamp, append uuid as a stable secondary sort so the ordering
- # is total. Ties on timestamp would otherwise be arbitrary and shift between pages,
- # which is what lets cursor pagination silently skip events sharing a timestamp.
- if self._cursor_eligible and not any(
- isinstance(o.expr, ast.Field) and o.expr.chain == ["uuid"] for o in order_by
- ):
- order_by.append(ast.OrderExpr(expr=ast.Field(chain=["uuid"]), order=order_by[0].order))
+ order_by = self._order_by_exprs(select_input, select, aggregations, has_any_aggregation)
with self.timings.measure("select"):
if self.query.source is not None:
- # Kludge: If the events_query has logic in select that the where clauses depends on, this will potentially error.
- # If we implement that for other runners, make this smarter.
- events_query = self.source_runner.to_events_query()
- events_query.select = select
- if where is not None:
- if events_query.where is None:
- events_query.where = where
- else:
- events_query.where = ast.And(exprs=[events_query.where, where])
- if having is not None:
- if events_query.having is None:
- events_query.having = having
- else:
- events_query.having = ast.And(exprs=[events_query.having, having])
- events_query.group_by = group_by if has_any_aggregation else None
- events_query.order_by = order_by
- return events_query
-
- stmt = ast.SelectQuery(
- select=select,
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=where,
- having=having,
- group_by=group_by if has_any_aggregation else None,
- order_by=order_by,
- )
+ return self._source_events_query(select, where, having, group_by, order_by, has_any_aggregation)
+ return self._events_query(select, where, having, group_by, order_by, has_any_aggregation)
- # Presorted optimization: sort narrow data (uuid) first, then fetch wide data for matched rows.
- # Avoids sorting giant rows with properties and elements_chain cols - instead sorts uuids.
- if self._can_use_presorted_optimization(order_by) and not has_any_aggregation:
- logger.info(
- "events_query_runner_presorted_optimization",
- team_id=self.team.pk,
+ def _filter_where_exprs(self) -> list[ast.Expr]:
+ with self.timings.measure("filters"):
+ with self.timings.measure("where"):
+ where_input = self.query.where or []
+ where_exprs = [parse_expr(expr, timings=self.timings) for expr in where_input]
+ if self.query.properties:
+ with self.timings.measure("properties"):
+ where_exprs.extend(property_to_expr(property, self.team) for property in self.query.properties)
+ if self.query.fixedProperties:
+ with self.timings.measure("fixed_properties"):
+ where_exprs.extend(property_to_expr(property, self.team) for property in self.query.fixedProperties)
+ all_events: list[str] = [e for e in [self.query.event, *(self.query.events or [])] if e]
+ if all_events:
+ with self.timings.measure("event"):
+ where_exprs.append(self._event_where_expr(all_events))
+ if self.query.actionId:
+ with self.timings.measure("action_id"):
+ where_exprs.append(self._action_where_expr(self.query.actionId))
+ elif self.query.actionSteps:
+ with self.timings.measure("action_steps"):
+ where_exprs.append(self._action_steps_where_expr())
+ if self.query.personId:
+ with self.timings.measure("person_id"), personhog_caller_tag("persons/events-query"):
+ where_exprs.append(self._person_where_expr(self.query.personId))
+ if self.query.filterTestAccounts:
+ with self.timings.measure("test_account_filters"):
+ where_exprs.extend(
+ property_to_expr(prop, self.team) for prop in self.team.test_account_filters or []
)
- inner_query = parse_select("SELECT uuid FROM events")
- assert isinstance(inner_query, ast.SelectQuery)
- inner_query.where = where
- inner_query.order_by = order_by
- inner_query.limit = ast.Constant(value=self.paginator.limit + self.paginator.offset + 1)
+ return where_exprs
+
+ def _event_where_expr(self, all_events: list[str]) -> ast.Expr:
+ if len(all_events) == 1:
+ return parse_expr(
+ "event = {event}",
+ {"event": ast.Constant(value=all_events[0])},
+ timings=self.timings,
+ )
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["event"]),
+ right=ast.Tuple(exprs=[ast.Constant(value=e) for e in all_events]),
+ )
+
+ def _action_where_expr(self, action_id: int) -> ast.Expr:
+ try:
+ action = Action.objects.get(pk=action_id, team__project_id=self.team.project_id)
+ except Action.DoesNotExist:
+ raise Exception("Action does not exist")
+ if not action.steps:
+ raise Exception("Action does not have any match groups")
+ return action_to_expr(action)
+
+ def _action_steps_where_expr(self) -> ast.Expr:
+ steps = [
+ ActionStepJSON(
+ event=s.event,
+ tag_name=s.tag_name,
+ text=s.text,
+ text_matching=s.text_matching.value if s.text_matching else None,
+ href=s.href,
+ href_matching=s.href_matching.value if s.href_matching else None,
+ selector=s.selector,
+ url=s.url,
+ url_matching=s.url_matching.value if s.url_matching else None,
+ properties=[p.model_dump() for p in s.properties] if s.properties else None,
+ )
+ for s in self.query.actionSteps or []
+ ]
+ return steps_to_expr(steps, self.team)
- prefilter_sorted = parse_expr("uuid in ({inner_query})", {"inner_query": inner_query})
+ def _person_where_expr(self, person_id: str) -> ast.Expr:
+ person: Person | None = get_person_by_pk_or_uuid(
+ self.team.pk, person_id, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS
+ )
+ return ast.CompareOperation(
+ left=ast.Call(name="cityHash64", args=[ast.Field(chain=["distinct_id"])]),
+ right=ast.Tuple(
+ exprs=[
+ ast.Call(name="cityHash64", args=[ast.Constant(value=id)])
+ for id in get_distinct_ids_for_subquery(person, self.team)
+ ]
+ ),
+ op=ast.CompareOperationOp.In,
+ )
- if where is not None:
- stmt.where = ast.And(exprs=[prefilter_sorted, where])
- else:
- stmt.where = prefilter_sorted
+ def _timestamp_where_exprs(self) -> list[ast.Expr]:
+ with self.timings.measure("timestamps"):
+ # prevent accidentally future events from being visible by default
+ before = self.query.before or (now() + timedelta(seconds=5)).isoformat()
+ exprs = [self._timestamp_boundary_expr(before, BEFORE_BOUNDARY)]
+
+ # limit to the last 24h by default
+ after = self.query.after or "-24h"
+ if after != "all":
+ exprs.append(self._timestamp_boundary_expr(after, AFTER_BOUNDARY))
+ return exprs
+
+ def _timestamp_boundary_expr(self, cursor: str, boundary: TimestampBoundary) -> ast.Expr:
+ timestamp, cursor_uuid = split_pagination_cursor(cursor)
+ parsed_date = relative_date_parse(timestamp, self.team.timezone_info)
+ if cursor_uuid is None:
+ return parse_expr(
+ boundary.plain,
+ {"boundary": ast.Constant(value=parsed_date)},
+ timings=self.timings,
+ )
+ # Advance past events sharing the boundary timestamp using uuid as a tiebreaker,
+ # matching the ``timestamp DESC, uuid DESC`` ordering that `_order_by_exprs` applies.
+ return parse_expr(
+ boundary.with_uuid_tiebreaker,
+ {
+ "boundary": ast.Constant(value=parsed_date),
+ "boundary_eq": ast.Constant(value=parsed_date),
+ "boundary_uuid": ast.Call(name="toUUID", args=[ast.Constant(value=cursor_uuid)]),
+ },
+ timings=self.timings,
+ )
- return stmt
+ def _order_by_exprs(
+ self,
+ select_input: list[str],
+ select: list[ast.Expr],
+ aggregations: list[ast.Expr],
+ has_any_aggregation: bool,
+ ) -> list[ast.OrderExpr]:
+ with self.timings.measure("order"):
+ if self.query.orderBy is not None:
+ order_by = self._requested_order_by(self.query.orderBy)
+ else:
+ order_by = self._default_order_by(select_input, select, aggregations)
+
+ first_order = order_by[0].expr if order_by else None
+ self._cursor_eligible = (
+ self.query.source is None
+ and not has_any_aggregation
+ and isinstance(first_order, ast.Field)
+ and first_order.chain == ["timestamp"]
+ )
+
+ # When ordering by timestamp, append uuid as a stable secondary sort so the ordering
+ # is total. Ties on timestamp would otherwise be arbitrary and shift between pages,
+ # which is what lets cursor pagination silently skip events sharing a timestamp.
+ if self._cursor_eligible and not any(
+ isinstance(o.expr, ast.Field) and o.expr.chain == ["uuid"] for o in order_by
+ ):
+ order_by.append(ast.OrderExpr(expr=ast.Field(chain=["uuid"]), order=order_by[0].order))
+ return order_by
+
+ def _requested_order_by(self, order_by_input: list[str]) -> list[ast.OrderExpr]:
+ columns: list[str] = []
+ for col in order_by_input:
+ if col.split("--")[0].strip() == "person_display_name":
+ property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
+ props = person_display_name_property_exprs(property_keys, "person.properties")
+ expr = f"(coalesce({', '.join([*props, 'distinct_id'])}), toString(person.id))"
+ columns.append(re.sub(r"person_display_name -- Person ", expr, col))
+ else:
+ columns.append(col)
+ return [parse_order_expr(column, timings=self.timings) for column in columns]
+
+ def _default_order_by(
+ self, select_input: list[str], select: list[ast.Expr], aggregations: list[ast.Expr]
+ ) -> list[ast.OrderExpr]:
+ 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 []
+
+ def _source_events_query(
+ self,
+ select: list[ast.Expr],
+ where: ast.Expr | None,
+ having: ast.Expr | None,
+ group_by: list[ast.Expr],
+ order_by: list[ast.OrderExpr],
+ has_any_aggregation: bool,
+ ) -> ast.SelectQuery:
+ # Kludge: If the events_query has logic in select that the where clauses depends on, this will potentially error.
+ # If we implement that for other runners, make this smarter.
+ events_query = self.source_runner.to_events_query()
+ events_query.select = select
+ events_query.where = and_exprs(events_query.where, where)
+ events_query.having = and_exprs(events_query.having, having)
+ events_query.group_by = group_by if has_any_aggregation else None
+ events_query.order_by = order_by
+ return events_query
+
+ def _events_query(
+ self,
+ select: list[ast.Expr],
+ where: ast.Expr | None,
+ having: ast.Expr | None,
+ group_by: list[ast.Expr],
+ order_by: list[ast.OrderExpr],
+ has_any_aggregation: bool,
+ ) -> ast.SelectQuery:
+ stmt = ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=where,
+ having=having,
+ group_by=group_by if has_any_aggregation else None,
+ order_by=order_by,
+ )
+
+ # Presorted optimization: sort narrow data (uuid) first, then fetch wide data for matched rows.
+ # Avoids sorting giant rows with properties and elements_chain cols - instead sorts uuids.
+ if self._can_use_presorted_optimization(order_by) and not has_any_aggregation:
+ logger.info(
+ "events_query_runner_presorted_optimization",
+ team_id=self.team.pk,
+ )
+ stmt.where = self._presorted_where(where, order_by)
+
+ return stmt
+
+ def _presorted_where(self, where: ast.Expr | None, order_by: list[ast.OrderExpr]) -> ast.Expr:
+ inner_query = parse_select("SELECT uuid FROM events")
+ assert isinstance(inner_query, ast.SelectQuery)
+ inner_query.where = where
+ inner_query.order_by = order_by
+ inner_query.limit = ast.Constant(value=self.paginator.limit + self.paginator.offset + 1)
+
+ 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
def _calculate(self) -> EventsQueryResponse:
# Tag here (not in `to_query()`) so platform code that calls `to_query()` as a
@@ -500,40 +538,66 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
context=self.build_hogql_context(),
)
- # Convert star field from tuple to dict in each result
if "*" in self.select_input_raw():
- with self.timings.measure("expand_asterisk"):
- star_idx = self.select_input_raw().index("*")
- for index, result in enumerate(self.paginator.results):
- self.paginator.results[index] = list(result)
- select = result[star_idx]
- new_result = dict(zip(SELECT_STAR_FROM_EVENTS_FIELDS, select))
- new_result["properties"] = orjson.loads(new_result["properties"])
- if new_result["elements_chain"]:
- new_result["elements"] = ElementSerializer(
- chain_to_elements(new_result["elements_chain"]), many=True
- ).data
- self.paginator.results[index][star_idx] = new_result
-
- # Batch check which session IDs have recordings
- if "*" in self.select_input_raw() and len(self.paginator.results) > 0:
- with self.timings.measure("session_recordings_check"):
- session_recordings_map = self.batch_check_session_recordings()
- star_idx = self.select_input_raw().index("*")
- for result in self.paginator.results:
- if isinstance(result[star_idx], dict):
- properties = result[star_idx].get("properties", {})
- if isinstance(properties, dict):
- session_id = properties.get("$session_id")
- if isinstance(session_id, str) and session_id:
- properties["$has_recording"] = session_id in session_recordings_map
+ self._expand_star_column()
+ if len(self.paginator.results) > 0:
+ self._annotate_session_recordings()
+ person_indices = self._expand_person_display_name_columns()
+
+ # TODO: get rid of this logic once we don't use `person` columns anywhere
+ if len(person_indices) > 0 and len(self.paginator.results) > 0:
+ self._expand_person_columns(person_indices)
+
+ return EventsQueryResponse(
+ results=self.paginator.results,
+ columns=self.columns(query_result.columns),
+ types=[t for _, t in query_result.types] if query_result.types else [],
+ timings=self.timings.to_list(),
+ hogql=query_result.hogql,
+ modifiers=self.modifiers,
+ nextCursor=self._next_cursor(),
+ **self.paginator.response_params(),
+ )
+
+ def _expand_star_column(self) -> None:
+ """Convert the star field from a tuple to a dict in each result."""
+ with self.timings.measure("expand_asterisk"):
+ star_idx = self.select_input_raw().index("*")
+ for index, result in enumerate(self.paginator.results):
+ self.paginator.results[index] = list(result)
+ select = result[star_idx]
+ new_result = dict(zip(SELECT_STAR_FROM_EVENTS_FIELDS, select))
+ new_result["properties"] = orjson.loads(new_result["properties"])
+ if new_result["elements_chain"]:
+ new_result["elements"] = ElementSerializer(
+ chain_to_elements(new_result["elements_chain"]), many=True
+ ).data
+ self.paginator.results[index][star_idx] = new_result
+
+ def _annotate_session_recordings(self) -> None:
+ """Batch check which session IDs have recordings."""
+ with self.timings.measure("session_recordings_check"):
+ session_recordings_map = self.batch_check_session_recordings()
+ star_idx = self.select_input_raw().index("*")
+ for result in self.paginator.results:
+ if not isinstance(result[star_idx], dict):
+ continue
+ properties = result[star_idx].get("properties", {})
+ if not isinstance(properties, dict):
+ continue
+ session_id = properties.get("$session_id")
+ 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."""
person_indices: list[int] = []
for column_index, col in enumerate(self.select_input_raw()):
- if col.split("--")[0].strip() == "person":
+ stripped = col.split("--")[0].strip()
+ if stripped == "person":
person_indices.append(column_index)
- # convert tuple that gets returned into a dict
- if col.split("--")[0].strip() == "person_display_name":
+ if stripped == "person_display_name":
for index, result in enumerate(self.paginator.results):
row = list(self.paginator.results[index])
row[column_index] = {
@@ -542,70 +606,61 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
"distinct_id": str(result[column_index][2]),
}
self.paginator.results[index] = row
+ return person_indices
- # TODO: get rid of this logic once we don't use `person` columns anywhere
- if len(person_indices) > 0 and len(self.paginator.results) > 0:
- with self.timings.measure("person_column_extra_query"):
- # Make a query into postgres to fetch person
- person_idx = person_indices[0]
- distinct_ids = list({event[person_idx] for event in self.paginator.results})
-
- distinct_to_person: dict[str, Person] = {}
- batch_size = 1000
- with personhog_caller_tag("persons/events-person-column"):
- for i in range(0, len(distinct_ids), batch_size):
- batch_distinct_ids = distinct_ids[i : i + batch_size]
- distinct_to_person.update(get_persons_mapped_by_distinct_id(self.team.pk, batch_distinct_ids))
-
- # Load restricted person properties to strip from the side-channel result
- from products.access_control.backend.property_access_control import (
- get_restricted_property_names,
- strip_restricted_properties,
- )
+ 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])
- restricted_person_props = get_restricted_property_names(
- team_id=self.team.pk,
- user=self.user,
- property_type=PropertyDefinition.Type.PERSON,
- )
+ # Load restricted person properties to strip from the side-channel result
+ from products.access_control.backend.property_access_control import (
+ get_restricted_property_names,
+ strip_restricted_properties,
+ )
- # Loop over all columns in case there is more than one "person" column
- for column_index in person_indices:
- for index, result in enumerate(self.paginator.results):
- distinct_id: str = result[column_index]
- self.paginator.results[index] = list(result)
- if distinct_to_person.get(distinct_id):
- person = distinct_to_person[distinct_id]
- properties = strip_restricted_properties(person.properties or {}, restricted_person_props)
- self.paginator.results[index][column_index] = {
- "uuid": person.uuid,
- "created_at": person.created_at,
- "properties": properties,
- "distinct_id": distinct_id,
- }
- else:
- self.paginator.results[index][column_index] = {
- "distinct_id": distinct_id,
- }
-
- next_cursor = None
- if self._cursor_eligible and self.paginator.has_more() and self.paginator.results:
- last_row = self.paginator.results[-1]
- last_timestamp = self._extract_last_timestamp(last_row)
- if last_timestamp is not None:
- last_uuid = self._extract_last_uuid(last_row)
- next_cursor = f"{last_timestamp}{CURSOR_DELIMITER}{last_uuid}" if last_uuid else last_timestamp
+ restricted_person_props = get_restricted_property_names(
+ team_id=self.team.pk,
+ user=self.user,
+ property_type=PropertyDefinition.Type.PERSON,
+ )
- return EventsQueryResponse(
- results=self.paginator.results,
- columns=self.columns(query_result.columns),
- types=[t for _, t in query_result.types] if query_result.types else [],
- timings=self.timings.to_list(),
- hogql=query_result.hogql,
- modifiers=self.modifiers,
- nextCursor=next_cursor,
- **self.paginator.response_params(),
- )
+ # Loop over all columns in case there is more than one "person" column
+ for column_index in person_indices:
+ for index, result in enumerate(self.paginator.results):
+ distinct_id: str = result[column_index]
+ self.paginator.results[index] = list(result)
+ person = distinct_to_person.get(distinct_id)
+ if person is None:
+ self.paginator.results[index][column_index] = {"distinct_id": distinct_id}
+ continue
+ self.paginator.results[index][column_index] = {
+ "uuid": person.uuid,
+ "created_at": person.created_at,
+ "properties": strip_restricted_properties(person.properties or {}, restricted_person_props),
+ "distinct_id": distinct_id,
+ }
+
+ def _persons_by_distinct_id(self, person_idx: int) -> dict[str, Person]:
+ """Make a query into postgres to fetch the persons behind the `person` column."""
+ distinct_ids = list({event[person_idx] for event in self.paginator.results})
+
+ distinct_to_person: dict[str, Person] = {}
+ batch_size = 1000
+ with personhog_caller_tag("persons/events-person-column"):
+ for i in range(0, len(distinct_ids), batch_size):
+ batch_distinct_ids = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(get_persons_mapped_by_distinct_id(self.team.pk, batch_distinct_ids))
+ return distinct_to_person
+
+ def _next_cursor(self) -> str | None:
+ if not (self._cursor_eligible and self.paginator.has_more() and self.paginator.results):
+ return None
+ last_row = self.paginator.results[-1]
+ last_timestamp = self._extract_last_timestamp(last_row)
+ if last_timestamp is None:
+ return None
+ last_uuid = self._extract_last_uuid(last_row)
+ return f"{last_timestamp}{CURSOR_DELIMITER}{last_uuid}" if last_uuid else last_timestamp
def apply_dashboard_filters(self, dashboard_filter: DashboardFilter):
if dashboard_filter.date_to or dashboard_filter.date_from: