: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): read flag calls from flag_evaluations on the activity page (#110149)
Phil Haack543c12bb137f
diff --git a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx b/frontend/src/queries/nodes/DataTable/EventRowActions.tsxindex eed36ad2f9c3..a3ddf0d3d446 100644--- a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx+++ b/frontend/src/queries/nodes/DataTable/EventRowActions.tsx@@ -103,7 +103,7 @@ function EventRowActionsDropdown({ event }: { event: EventType }): JSX.Element {export const EventCopyLinkButton = React.forwardRef<HTMLButtonElement,- { event: Pick<EventType, 'uuid' | 'timestamp'> }+ { event: Pick<EventType, 'uuid' | 'timestamp' | 'event'> }>(function EventCopyLinkButton({ event }, ref) {return (<LemonButton@@ -113,7 +113,7 @@ export const EventCopyLinkButton = React.forwardRef<data-attr="events-table-event-link"onClick={() =>void copyToClipboard(- urls.absolute(urls.currentProject(urls.event(String(event.uuid), event.timestamp))),+ urls.absolute(urls.currentProject(urls.event(String(event.uuid), event.timestamp, event.event))),'link to event')}diff --git a/frontend/src/scenes/activity/explore/EventsScene.tsx b/frontend/src/scenes/activity/explore/EventsScene.tsxindex c93a9a4b9986..4117df88f623 100644--- a/frontend/src/scenes/activity/explore/EventsScene.tsx+++ b/frontend/src/scenes/activity/explore/EventsScene.tsx@@ -1,5 +1,6 @@import { useActions, useValues } from 'kea'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'@@ -17,7 +18,7 @@ import { buildExploreAgentContext } from '../activityAgentContext'import { eventsSceneLogic } from './eventsSceneLogic'export function EventsScene(): JSX.Element {- const { query } = useValues(eventsSceneLogic())+ const { query, showFlagCallsNote } = useValues(eventsSceneLogic())const { setQuery } = useActions(eventsSceneLogic())useAttachedContext(buildExploreAgentContext(ActivityTab.ExploreEvents, query))@@ -32,6 +33,12 @@ export function EventsScene(): JSX.Element {type: sceneConfigurations[Scene.ExploreEvents].iconType || 'default_icon_type',}}/>+ {showFlagCallsNote && (+ <LemonBanner type="info" dismissKey="activity-flag-calls-stored-separately">+ Feature flag calls are stored separately from other events. Filter by only the "Feature flag called"+ event to see them.+ </LemonBanner>+ )}<QueryattachTo={eventsSceneLogic()}uniqueKey="events-scene"diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.test.ts b/frontend/src/scenes/activity/explore/eventsSceneLogic.test.tsindex f940ea04495b..cde74266b116 100644--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.test.ts+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.test.ts@@ -1,10 +1,14 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'import { useMocks } from '~/mocks/jest'-import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'+import { DataTableNode, EventsQuery, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { ActivityTab } from '~/types'@@ -42,4 +46,53 @@ describe('eventsSceneLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.query).toEqual(query)})++ test.each([+ ['an unfiltered list', FlagEvaluationsModeEnumApi.Number2, {}, true],+ ['a list filtered to another event', FlagEvaluationsModeEnumApi.Number2, { events: ['$pageview'] }, true],+ [+ 'a list filtered to flag calls and another event',+ FlagEvaluationsModeEnumApi.Number2,+ { events: ['$feature_flag_called', '$pageview'] },+ true,+ ],+ [+ 'a list filtered to flag calls',+ FlagEvaluationsModeEnumApi.Number2,+ { events: ['$feature_flag_called'] },+ false,+ ],+ [+ 'a list filtered to flag calls by the single event field',+ FlagEvaluationsModeEnumApi.Number2,+ { event: '$feature_flag_called' },+ false,+ ],+ [+ 'a list filtered to flag calls and an action',+ FlagEvaluationsModeEnumApi.Number2,+ { event: '$feature_flag_called', actionId: 1 },+ true,+ ],+ [+ 'a list filtered to flag calls and action steps',+ FlagEvaluationsModeEnumApi.Number2,+ { event: '$feature_flag_called', actionSteps: [{ event: '$feature_flag_called' }] },+ true,+ ],+ ['an unfiltered list on the read flag evaluations mode', FlagEvaluationsModeEnumApi.Number1, {}, false],+ ])(+ 'decides whether the flag calls note shows for %s',+ (_name, mode, eventFilter: Partial<EventsQuery>, expected) => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })+ const query: DataTableNode = {+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.EventsQuery, select: ['*', 'event', 'timestamp'], ...eventFilter },+ }++ logic.actions.setQuery(query)++ expect(logic.values.showFlagCallsNote).toBe(expected)+ }+ )})diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsxindex 1897708cf4aa..03cc81fd64fd 100644--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx@@ -15,13 +15,18 @@ import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filimport { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'import { getDefaultEventsQueryForTeam } from '~/queries/nodes/DataTable/defaultEventsQuery'import { DataTableNode, Node } from '~/queries/schema/schema-general'+import { isDataTableNode, isEventsQuery } from '~/queries/utils'import { ActivityTab, Breadcrumb } from '~/types'import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { TeamPublicType, TeamType } from '../../../types'+const FLAG_EVALUATIONS_ONLY_MODE = FlagEvaluationsModeEnumApi.Number2+const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface eventsSceneLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -32,6 +37,7 @@ export interface eventsSceneLogicValues {defaultQuery: DataTableNodequery: DataTableNode | Node<Record<string, any>>savedQuery: Node | null+ showFlagCallsNote: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -62,6 +68,10 @@ export interface eventsSceneLogicMeta {savedQuery: Node<Record<string, any>> | null,defaultQuery: DataTableNode) => DataTableNode | Node<Record<string, any>>+ showFlagCallsNote: (+ currentTeam: TeamPublicType | TeamType | null,+ query: DataTableNode | Node<Record<string, any>>+ ) => boolean}}@@ -119,6 +129,24 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([(s) => [s.savedQuery, s.defaultQuery],(savedQuery: Node | null, defaultQuery: DataTableNode) => savedQuery || defaultQuery,],+ showFlagCallsNote: [+ (s) => [s.currentTeam, s.query],+ (currentTeam: TeamPublicType | TeamType | null, query: DataTableNode | Node): boolean => {+ if (+ currentTeam?.flag_evaluations_mode !== FLAG_EVALUATIONS_ONLY_MODE ||+ !isDataTableNode(query) ||+ !isEventsQuery(query.source)+ ) {+ return false+ }+ const { source, actionId, actionSteps, event, events } = query.source+ if (source || actionId || actionSteps?.length) {+ return true+ }+ const eventNames = [event, ...(events ?? [])].filter(Boolean)+ return eventNames.length === 0 || eventNames.some((name) => name !== FEATURE_FLAG_CALLED_EVENT)+ },+ ],breadcrumbs: [() => [],(): Breadcrumb[] => [diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex e1f40437f7ff..ed415aa2e9ce 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -228,6 +228,19 @@ describe('sceneLogic', () => {expect(router.values.hashParams).toEqual(hash)})+ it('redirects a copied event link to the activity list filtered to its uuid and event name', async () => {+ const uuid = '0190a4c2-0000-7000-8000-000000000001'+ router.actions.push(urls.event(uuid, '2026-01-01T00:00:00.000Z', '$feature_flag_called'))+ await expectLogic(logic).delay(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(+ urls.activity(ActivityTab.ExploreEvents)+ )+ expect(router.values.hashParams.q.source).toMatchObject({+ event: '$feature_flag_called',+ properties: [{ key: `uuid = '${uuid}'` }],+ })+ })+it.each([['the product root', () => '/engineering-analytics', () => urls.engineeringAnalytics()],[diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex 63e5a150e5a1..91653031c70b 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -646,7 +646,7 @@ export const redirects: Record<'/web/ai-search': urls.webAnalyticsPagePerformance(),'/events': urls.activity(),- '/events/:id/*': ({ id, _ }) => {+ '/events/:id/*': ({ id, _ }, { event }) => {const query = getDefaultEventsSceneQuery([{type: PropertyFilterType.HogQL,@@ -654,11 +654,16 @@ export const redirects: Record<value: null,},])+ const source = query.source as EventsQuery+ if (typeof event === 'string' && event) {+ // The events query reads some events, such as flag calls, from their own table.+ // It picks that table only when the query filters to the event name, so a uuid filter alone misses the row.+ source.event = event+ }try {const timestamp = decodeURIComponent(_)- const after = dayjs(timestamp).subtract(15, 'second').startOf('second').toISOString()- const before = dayjs(timestamp).add(15, 'second').startOf('second').toISOString()- Object.assign(query.source as EventsQuery, { before, after })+ source.after = dayjs(timestamp).subtract(15, 'second').startOf('second').toISOString()+ source.before = dayjs(timestamp).add(15, 'second').startOf('second').toISOString()} catch {lemonToast.error('Invalid event timestamp')}diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 637874720bb0..47afac71f127 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -60,8 +60,11 @@ export const urls = {transformations: (): string => '/data-management/transformations',eventFiltering: (): string => '/data-management/event-filtering',activity: (tab: ActivityTab | ':tab' = ActivityTab.ExploreEvents): string => `/activity/${tab}`,- event: (id: string, timestamp: string): string =>- `/events/${encodeURIComponent(id)}/${encodeURIComponent(timestamp)}`,+ event: (id: string, timestamp: string, eventName?: string): string =>+ combineUrl(+ `/events/${encodeURIComponent(id)}/${encodeURIComponent(timestamp)}`,+ eventName ? { event: eventName } : {}+ ).url,ingestionWarnings: (): string => '/data-management/ingestion-warnings',ingestionWarningsV2: (): string => '/data-management/ingestion-warnings-v2',revenueSettings: (): string => '/data-management/revenue',diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.pyindex 6f09a1f778be..ae26411ade28 100644--- a/posthog/hogql_queries/events_query_runner.py+++ b/posthog/hogql_queries/events_query_runner.py@@ -8,11 +8,24 @@ from django.utils.timezone import nowimport orjsonimport structlog-from posthog.schema import CachedEventsQueryResponse, DashboardFilter, EventsQuery, EventsQueryResponse+from posthog.schema import (+ AnyPropertyFilterDiscriminated,+ CachedEventsQueryResponse,+ DashboardFilter,+ EventPropertyFilter,+ EventsQuery,+ EventsQueryResponse,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+ PropertyOperator,+)from posthog.hogql import astfrom posthog.hogql.ast import Alias-from posthog.hogql.parser import parse_expr, parse_order_expr, parse_select+from 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.parser import parse_expr, parse_order_exprfrom posthog.hogql.property import (action_to_expr,has_aggregation,@@ -25,6 +38,7 @@ from posthog.hogql.query import execute_hogql_queryfrom 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@@ -32,12 +46,15 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_rfrom posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprsfrom posthog.models import Person, PropertyDefinitionfrom posthog.models.element import chain_to_elements+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENTfrom posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subqueryfrom posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_mapped_by_distinct_idfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.utils import relative_date_parsefrom products.actions.backend.models.action import Action, ActionStepJSON+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode+from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_modelogger = structlog.get_logger(__name__)@@ -57,6 +74,33 @@ SELECT_STAR_FROM_EVENTS_FIELDS = [# Wide columns that defeat presorted optimizationWIDE_COLUMNS = {"elements_chain", "properties"}++@frozen+class EventsListTable:+ chain: tuple[str, ...]+ alias: str | None+ person_id: str++ def join_expr(self) -> ast.JoinExpr:+ return ast.JoinExpr(table=ast.Field(chain=[*self.chain]), alias=self.alias)+++EVENTS_LIST_TABLE = EventsListTable(+ chain=("events",),+ alias=None,+ person_id="person.id",+)+FLAG_EVALUATIONS_LIST_TABLE = EventsListTable(+ chain=("posthog", "flag_evaluations"),+ # Resolver.visit_join_expr names an unaliased posthog.flag_evaluations "posthog__flag_evaluations".+ # LazyTableResolver looks for a join's source table by chain[0], which is "posthog". That lookup misses.+ # It then prints the persons join before the override join that the persons join condition reads.+ alias="flag_evaluations",+ # 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",+)+# 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@@ -88,6 +132,22 @@ def and_exprs(existing: ast.Expr | None, extra: ast.Expr | None) -> ast.Expr | Nreturn ast.And(exprs=[existing, extra])+QueryPropertyFilter = AnyPropertyFilterDiscriminated | PropertyGroupFilter | PropertyGroupFilterValue+++def _exact_flag_keys(prop: QueryPropertyFilter) -> list[str] | None:+ if not (+ isinstance(prop, EventPropertyFilter)+ and prop.key == "$feature_flag"+ and prop.operator == PropertyOperator.EXACT+ ):+ return None+ values = prop.value if isinstance(prop.value, list) else [prop.value]+ if not values or not all(isinstance(value, str) for value in values):+ return None+ return [str(value) for value in values]++def split_pagination_cursor(value: str) -> tuple[str, str | None]:"""Split a ``<timestamp>|<uuid>`` cursor. Plain user-supplied date filters have no delimiter andpass through unchanged with a ``None`` tiebreaker."""@@ -123,7 +183,12 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):if self.query.source is not None:self.source_runner.validate()- def select_cols(self) -> tuple[list[str], list[ast.Expr]]:+ 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")+ return f"coalesce({', '.join([*props, 'distinct_id'])}), toString({table.person_id})"++ def select_cols(self, table: EventsListTable) -> tuple[list[str], list[ast.Expr]]:select_input: list[str] = []person_indices: list[int] = []for index, col in enumerate(self.select_input_raw()):@@ -136,10 +201,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):select_input.append("distinct_id")person_indices.append(index)elif 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), distinct_id)"- select_input.append(expr)+ select_input.append(f"({self._person_display_name_key(table)}, distinct_id)")else:select_input.append(col)return select_input, [@@ -260,11 +322,14 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):checker.visit(map_virtual_properties(parse_expr(col, timings=self.timings)))def to_query(self) -> ast.SelectQuery:+ return self._build_query(EVENTS_LIST_TABLE)++ def _build_query(self, table: EventsListTable) -> ast.SelectQuery:# Note: This code is inefficient and problematic, see https://github.com/PostHog/posthog/issues/13485 for details.with self.timings.measure("build_ast"):# columns & group_bywith self.timings.measure("columns"):- select_input, select = self.select_cols()+ select_input, select = self.select_cols(table)self._raise_on_restricted_property_select()with self.timings.measure("aggregations"):@@ -272,7 +337,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):aggregations: list[ast.Expr] = [column for column in select if has_aggregation(column)]has_any_aggregation = len(aggregations) > 0- where_exprs = self._filter_where_exprs()+ where_exprs = self._filter_where_exprs(table)where_exprs.extend(self._timestamp_where_exprs())# where & having@@ -282,25 +347,78 @@ 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 = self._order_by_exprs(select_input, select, aggregations, has_any_aggregation)+ order_by = self._order_by_exprs(table, select_input, select, aggregations, has_any_aggregation)with self.timings.measure("select"):if self.query.source is not None: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)+ return self._events_query(table, select, where, having, group_by, order_by, has_any_aggregation)++ def _event_names(self) -> list[str]:+ return [e for e in [self.query.event, *(self.query.events or [])] if e]++ def _list_table(self) -> EventsListTable:+ if self.query.source is not None or self.query.actionId or self.query.actionSteps:+ return EVENTS_LIST_TABLE+ if set(self._event_names()) != {FLAG_EVALUATIONS_SOURCE_EVENT}:+ return EVENTS_LIST_TABLE+ mode = get_organization_flag_evaluations_mode(self.team.organization_id)+ if mode != FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY:+ return EVENTS_LIST_TABLE+ return FLAG_EVALUATIONS_LIST_TABLE++ def _property_where_expr(self, prop: QueryPropertyFilter, table: EventsListTable) -> ast.Expr:+ flag_keys = _exact_flag_keys(prop) if table is FLAG_EVALUATIONS_LIST_TABLE else None+ if flag_keys is None:+ return property_to_expr(prop, self.team)+ # HogQL reads properties.$feature_flag from the properties JSON, which reads the properties of every call of+ # the flag in the date range. flag_key holds the same value and leads the table's sort key after team_id.+ return ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["flag_key"]),+ right=ast.Tuple(exprs=[ast.Constant(value=key) for key in flag_keys]),+ )- def _filter_where_exprs(self) -> list[ast.Expr]:+ def _query_context(self, table: EventsListTable) -> HogQLContext:+ context = self.build_hogql_context()+ assert context.database is not None+ if 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},+ )+ return context++ def _filter_where_exprs(self, table: EventsListTable) -> 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)+ where_exprs.extend(self._property_where_expr(prop, table) for prop 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]+ where_exprs.extend(self._property_where_expr(prop, table) for prop in self.query.fixedProperties)+ all_events = self._event_names()if all_events:with self.timings.measure("event"):where_exprs.append(self._event_where_expr(all_events))@@ -410,6 +528,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):def _order_by_exprs(self,+ table: EventsListTable,select_input: list[str],select: list[ast.Expr],aggregations: list[ast.Expr],@@ -417,7 +536,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):) -> list[ast.OrderExpr]:with self.timings.measure("order"):if self.query.orderBy is not None:- order_by = self._requested_order_by(self.query.orderBy)+ order_by = self._requested_order_by(table, self.query.orderBy)else:order_by = self._default_order_by(select_input, select, aggregations)@@ -438,13 +557,11 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):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]:+ def _requested_order_by(self, table: EventsListTable, 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))"+ expr = f"({self._person_display_name_key(table)})"columns.append(re.sub(r"person_display_name -- Person ", expr, col))else:columns.append(col)@@ -484,6 +601,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):def _events_query(self,+ table: EventsListTable,select: list[ast.Expr],where: ast.Expr | None,having: ast.Expr | None,@@ -493,7 +611,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):) -> ast.SelectQuery:stmt = ast.SelectQuery(select=select,- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ select_from=table.join_expr(),where=where,having=having,group_by=group_by if has_any_aggregation else None,@@ -507,16 +625,20 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):"events_query_runner_presorted_optimization",team_id=self.team.pk,)- stmt.where = self._presorted_where(where, order_by)+ stmt.where = self._presorted_where(table, 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)+ def _presorted_where(+ self, table: EventsListTable, where: ast.Expr | None, order_by: list[ast.OrderExpr]+ ) -> ast.Expr:+ inner_query = ast.SelectQuery(+ select=[ast.Field(chain=["uuid"])],+ select_from=table.join_expr(),+ where=where,+ order_by=order_by,+ 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@@ -527,15 +649,18 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):# the `select` / `where` strings it builds are platform constants. User-facing# `EventsQuery` execution always lands in `_calculate()` via the runner.tag_contains_user_hogql()+ # Only this path reads flag_evaluations. Callers that run to_query() in their own context keep reading+ # events. Their select or database may need columns that flag_evaluations lacks.+ table = self._list_table()query_result = self.paginator.execute_hogql_query(- query=self.to_query(),+ query=self._build_query(table),team=self.team,query_type="EventsQuery",timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,user=self.user,- context=self.build_hogql_context(),+ context=self._query_context(table),)if "*" in self.select_input_raw():@@ -671,7 +796,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):self.query.properties = (self.query.properties or []) + dashboard_filter.propertiesdef columns(self, result_columns: list | None) -> list[str]:- _, select = self.select_cols()+ _, select = self.select_cols(EVENTS_LIST_TABLE)columns = result_columns or []return [columns[idx] if len(columns) > idx and isinstance(select[idx], Alias) else coldiff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.pyindex 2e4c37180f8b..20f6d54af8e6 100644--- a/posthog/hogql_queries/test/test_events_query_runner.py+++ b/posthog/hogql_queries/test/test_events_query_runner.py@@ -1,4 +1,6 @@-from datetime import datetime+import json+import uuid+from datetime import UTC, datetimefrom typing import Any, castimport time_machine@@ -22,6 +24,8 @@ from posthog.schema import (EventPropertyFilter,EventsQuery,EventsQueryActionStep,+ GroupPropertyFilter,+ PersonPropertyFilter,PropertyOperator,)@@ -32,10 +36,21 @@ from posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.events_query_runner import EventsQueryRunnerfrom posthog.models import Element, Organization, OrganizationMembership, PropertyDefinition, Teamfrom posthog.models.event.util import events_only_in_active_schema+from posthog.models.group.util import create_groupfrom posthog.models.person.util import get_person_by_distinct_id+from posthog.test.persons import create_group_type_mappingfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevel+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig++EVENTS_FLAG_KEY = "flag-written-to-events"+FLAG_EVALUATIONS_FLAG_KEY = "flag-written-to-flag-evaluations"+FLAG_EVALUATIONS_DISTINCT_ID = "flag-evaluations-user"+FLAG_EVALUATIONS_EMAIL = "[email protected]"+FLAG_EVALUATIONS_GROUP_KEY = "flag-org"+FLAG_CALL_TIMESTAMP = datetime(2020, 1, 11, 12, 0, 1, tzinfo=UTC)class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):@@ -1214,6 +1229,180 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(response.results), 1)self.assertEqual(response.results[0][0]["event"], "$pageview")+ def _set_flag_evaluations_mode(self, mode: FlagEvaluationsMode) -> None:+ OrganizationFeatureFlagsConfig.objects.update_or_create(+ 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()++ row_uuid = uuid.uuid4()+ sync_execute(+ """+ INSERT INTO writable_flag_evaluations+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id)+ VALUES+ """,+ [+ (+ 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,+ self.team.pk,+ FLAG_EVALUATIONS_DISTINCT_ID,+ FLAG_CALL_TIMESTAMP,+ str(person_id or uuid.uuid4()),+ )+ ],+ )+ return row_uuid++ def test_flag_evaluations_only_organization_reads_flag_calls_from_flag_evaluations(self):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ person = _create_person(+ team_id=self.team.pk,+ distinct_ids=[FLAG_EVALUATIONS_DISTINCT_ID],+ properties={"email": FLAG_EVALUATIONS_EMAIL},+ )+ 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=FLAG_EVALUATIONS_GROUP_KEY,+ properties={"industry": "software"},+ )+ row_uuid = self._create_flag_calls_in_both_tables(person_id=person.uuid)++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(+ kind="EventsQuery",+ select=[+ "*",+ "event",+ "person_display_name -- Person",+ "coalesce(properties.$current_url, properties.$screen_name) -- Url / Screen",+ "properties.$lib",+ "timestamp",+ "properties.$feature_flag_response",+ "elements_chain",+ "person_mode",+ ],+ event="$feature_flag_called",+ properties=[+ EventPropertyFilter(+ key="$feature_flag", value=FLAG_EVALUATIONS_FLAG_KEY, operator=PropertyOperator.EXACT+ ),+ PersonPropertyFilter(key="email", value=FLAG_EVALUATIONS_EMAIL, operator=PropertyOperator.EXACT),+ GroupPropertyFilter(+ key="industry", value="software", operator=PropertyOperator.EXACT, group_type_index=0+ ),+ ],+ after="-30d",+ )+ response = EventsQueryRunner(query=query, team=self.team).run()++ assert isinstance(response, CachedEventsQueryResponse)+ assert f"in(flag_key, tuple('{FLAG_EVALUATIONS_FLAG_KEY}'))" in response.hogql+ assert "properties.$feature_flag," not in response.hogql+ assert len(response.results) == 1+ star, *columns = response.results[0]+ assert {+ "uuid": str(star["uuid"]),+ "event": star["event"],+ "distinct_id": star["distinct_id"],+ "flag_key": star["properties"]["$feature_flag"],+ "elements_chain": star["elements_chain"],+ } == {+ "uuid": str(row_uuid),+ "event": "$feature_flag_called",+ "distinct_id": FLAG_EVALUATIONS_DISTINCT_ID,+ "flag_key": FLAG_EVALUATIONS_FLAG_KEY,+ "elements_chain": "",+ }+ assert columns == [+ "$feature_flag_called",+ {+ "display_name": FLAG_EVALUATIONS_EMAIL,+ "id": str(person.uuid),+ "distinct_id": FLAG_EVALUATIONS_DISTINCT_ID,+ },+ "https://example.com/pricing",+ "web",+ FLAG_CALL_TIMESTAMP,+ "variant-a",+ "",+ "",+ ]++ @parameterized.expand(+ [+ (+ "flag_evaluations_only_with_the_events_list_filter",+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,+ {"events": ["$feature_flag_called"]},+ FLAG_EVALUATIONS_FLAG_KEY,+ ),+ (+ "events_mode",+ FlagEvaluationsMode.EVENTS,+ {"event": "$feature_flag_called"},+ EVENTS_FLAG_KEY,+ ),+ (+ "read_flag_evaluations_mode",+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ {"event": "$feature_flag_called"},+ EVENTS_FLAG_KEY,+ ),+ (+ "flag_evaluations_only_without_an_event_filter",+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,+ {},+ EVENTS_FLAG_KEY,+ ),+ (+ "flag_evaluations_only_with_a_second_event_in_the_filter",+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,+ {"event": "$feature_flag_called", "events": ["$pageview"]},+ EVENTS_FLAG_KEY,+ ),+ (+ "flag_evaluations_only_with_action_steps",+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,+ {"event": "$feature_flag_called", "actionSteps": [EventsQueryActionStep(event="$feature_flag_called")]},+ EVENTS_FLAG_KEY,+ ),+ ]+ )+ def test_flag_calls_are_read_from_flag_evaluations_only_for_an_exact_flag_called_filter(+ self, _name: str, mode: FlagEvaluationsMode, query_filter: dict[str, Any], expected_flag_key: str+ ):+ self._set_flag_evaluations_mode(mode)+ self._create_flag_calls_in_both_tables()++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(kind="EventsQuery", select=["properties.$feature_flag"], after="-30d", **query_filter)+ response = EventsQueryRunner(query=query, team=self.team).run()++ assert isinstance(response, CachedEventsQueryResponse)+ assert [row[0] for row in response.results] == [expected_flag_key]+def _enable_property_access_control(self) -> None:from posthog.constants import AvailableFeaturediff --git a/products/dashboards/frontend/widgets/activity/ActivityEventsWidgetRow.tsx b/products/dashboards/frontend/widgets/activity/ActivityEventsWidgetRow.tsxindex 26da001b4192..44dd56c6b676 100644--- a/products/dashboards/frontend/widgets/activity/ActivityEventsWidgetRow.tsx+++ b/products/dashboards/frontend/widgets/activity/ActivityEventsWidgetRow.tsx@@ -35,7 +35,7 @@ export function ActivityEventsWidgetRowSkeleton(): JSX.Element {export function ActivityEventsWidgetRow({ event }: { event: ActivityEventsWidgetEvent }): JSX.Element {return (<Link- to={urls.event(event.uuid, event.timestamp)}+ to={urls.event(event.uuid, event.timestamp, event.event)}target="_blank"subtleclassName="@container flex flex-col gap-0.5 px-3 py-2 hover:bg-surface-secondary focus-visible:outline-offset-[-2px]"diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.pyindex 6ed0ef01d49a..f80b39b2cdc7 100644--- a/products/feature_flags/backend/facade/enums.py+++ b/products/feature_flags/backend/facade/enums.py@@ -15,9 +15,6 @@ class FlagEvaluationsMode(LabeledIntEnum):EVENTS = 0, "Events"# The Usage tab reads flag_evaluations, and the HogQL table is visible.READ_FLAG_EVALUATIONS = 1, "Read flag evaluations"- # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. Ingestion- # ignores this mode until the change that implements it deploys. Until then the Usage tab and the- # HogQL table act as they do on READ_FLAG_EVALUATIONS. Some readers, such as the organization flag- # Projects tab, read flag_evaluations only in this mode. An organization already on this mode- # stops the events writes when that change deploys.+ # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. Some readers+ # stay on events in READ_FLAG_EVALUATIONS and read flag_evaluations only in this mode.FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"diff --git a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsxindex 9211cde98e3d..0914b01d009a 100644--- a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx+++ b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx@@ -20,7 +20,7 @@ import { FLAG_EVALUATIONS_MODE_LABELS, featureFlagsStaffToolsLogic } from './feaconst MODE_DESCRIPTIONS: Record<FlagEvaluationsModeEnumApi, string> = {0: 'The Usage tab reads $feature_flag_called events from the events table.',1: 'The Usage tab reads the flag_evaluations table, and the table is available in SQL. While the FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS instance setting is on, the Usage tab reads the events table instead.',- 2: 'The Usage tab reads the flag_evaluations table, and the table is available in SQL. Ingestion also stops writing $feature_flag_called to the events table.',+ 2: 'The Usage tab and any events list filtered to $feature_flag_called read the flag_evaluations table, and the table is available in SQL. Ingestion also stops writing $feature_flag_called to the events table.',}export function StaffFlagEvaluationsModeModal(): JSX.Element {