: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_evaluations for every flag view on mode 1 (#112117)
Phil Haack716a2960e8d3
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.tsindex 9bf78cdf590e..9bd16bb4a817 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts@@ -35,7 +35,7 @@ const HIDDEN_EVENT_NAMES = EVENTS_HIDDEN_IN_QUERY_BUILDERS.map(({ name }) => nam* group's event feed, ingestion triggers) and the experiment pickers pass it.** For an organization on mode 1, the team API reports Events while the- * `FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS` instance setting is on, so its pickers show these events again.+ * `FLAG_EVALUATIONS_READS_FORCE_EVENTS` instance setting is on, so its pickers show these events again.*/export function hiddenEventNames(flagEvaluationsMode: FlagEvaluationsModeEnumApi | undefined,diff --git a/frontend/src/scenes/activity/explore/EventsScene.tsx b/frontend/src/scenes/activity/explore/EventsScene.tsxindex 24847a2988f4..5eca7de8ca8e 100644--- a/frontend/src/scenes/activity/explore/EventsScene.tsx+++ b/frontend/src/scenes/activity/explore/EventsScene.tsx@@ -5,6 +5,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'+import { FLAG_EVALUATIONS_RETENTION_DAYS } from 'scenes/feature-flags/featureFlagUsageQueries'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { LiveRecordingsCount } from 'scenes/session-recordings/components/LiveRecordingsCount'@@ -22,7 +23,7 @@ import { buildExploreAgentContext } from '../activityAgentContext'import { eventsSceneLogic } from './eventsSceneLogic'export function EventsScene(): JSX.Element {- const { query, showFlagCallsNote } = useValues(eventsSceneLogic())+ const { query, flagCallsNote } = useValues(eventsSceneLogic())const { setQuery } = useActions(eventsSceneLogic())const { featureFlags } = useValues(featureFlagLogic)@@ -44,12 +45,17 @@ export function EventsScene(): JSX.Element {<LiveRecordingsCount /></div>)}- {showFlagCallsNote && (+ {flagCallsNote === 'stored-separately' && (<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>)}+ {flagCallsNote === 'retention' && (+ <LemonBanner type="info">+ This list shows feature flag calls from the last {FLAG_EVALUATIONS_RETENTION_DAYS} days.+ </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 cde74266b116..c50e09f9e73d 100644--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.test.ts+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.test.ts@@ -12,7 +12,7 @@ import { DataTableNode, EventsQuery, NodeKind } from '~/queries/schema/schema-geimport { initKeaTests } from '~/test/init'import { ActivityTab } from '~/types'-import { eventsSceneLogic } from './eventsSceneLogic'+import { FlagCallsNote, eventsSceneLogic } from './eventsSceneLogic'describe('eventsSceneLogic', () => {let logic: ReturnType<typeof eventsSceneLogic.build>@@ -47,52 +47,78 @@ describe('eventsSceneLogic', () => {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],+ test.each<[string, FlagEvaluationsModeEnumApi, Partial<EventsQuery>, FlagCallsNote | null]>([+ ['an unfiltered list', FlagEvaluationsModeEnumApi.Number2, {}, 'stored-separately'],+ [+ 'a list filtered to another event',+ FlagEvaluationsModeEnumApi.Number2,+ { events: ['$pageview'] },+ 'stored-separately',+ ],['a list filtered to flag calls and another event',FlagEvaluationsModeEnumApi.Number2,{ events: ['$feature_flag_called', '$pageview'] },- true,+ 'stored-separately',],['a list filtered to flag calls',FlagEvaluationsModeEnumApi.Number2,{ events: ['$feature_flag_called'] },- false,+ null,],['a list filtered to flag calls by the single event field',FlagEvaluationsModeEnumApi.Number2,{ event: '$feature_flag_called' },- false,+ null,],['a list filtered to flag calls and an action',FlagEvaluationsModeEnumApi.Number2,{ event: '$feature_flag_called', actionId: 1 },- true,+ 'stored-separately',],['a list filtered to flag calls and action steps',FlagEvaluationsModeEnumApi.Number2,{ event: '$feature_flag_called', actionSteps: [{ event: '$feature_flag_called' }] },- true,+ 'stored-separately',+ ],+ ['an unfiltered list on the read flag evaluations mode', FlagEvaluationsModeEnumApi.Number1, {}, null],+ [+ 'flag calls over a range older than the retention window',+ FlagEvaluationsModeEnumApi.Number1,+ { event: '$feature_flag_called', after: '-180d' },+ 'retention',],- ['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 },- }+ [+ 'flag calls over all time',+ FlagEvaluationsModeEnumApi.Number2,+ { events: ['$feature_flag_called'], after: 'all' },+ 'retention',+ ],+ [+ 'flag calls over a range inside the retention window',+ FlagEvaluationsModeEnumApi.Number1,+ { event: '$feature_flag_called', after: '-30d' },+ null,+ ],+ [+ 'flag calls over all time on the events mode',+ FlagEvaluationsModeEnumApi.Number0,+ { event: '$feature_flag_called', after: 'all' },+ null,+ ],+ ])('decides which flag calls note shows for %s', (_name, mode, eventFilter, 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)+ logic.actions.setQuery(query)- expect(logic.values.showFlagCallsNote).toBe(expected)- }- )+ expect(logic.values.flagCallsNote).toBe(expected)+ })})diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsxindex 03cc81fd64fd..d7daa9a6ebb5 100644--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx@@ -9,6 +9,10 @@ import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { objectsEqual } from 'lib/utils/objects'import { applyTestAccountFilter, getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'+import {+ reachesPastFlagEvaluationsRetention,+ readsFlagEvaluationsTable,+} from 'scenes/feature-flags/featureFlagUsageQueries'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'@@ -17,7 +21,7 @@ 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 { DataTableNode, EventsQuery, Node } from '~/queries/schema/schema-general'import { isDataTableNode, isEventsQuery } from '~/queries/utils'import { ActivityTab, Breadcrumb } from '~/types'@@ -27,6 +31,17 @@ import type { TeamPublicType, TeamType } from '../../../types'const FLAG_EVALUATIONS_ONLY_MODE = FlagEvaluationsModeEnumApi.Number2const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'+export type FlagCallsNote = 'stored-separately' | 'retention'++// Mirrors EventsQueryRunner._list_table, which reads flag_evaluations only for a list of nothing but flag calls.+function listsOnlyFlagCalls({ source, actionId, actionSteps, event, events }: EventsQuery): boolean {+ if (source || actionId || actionSteps?.length) {+ return false+ }+ const eventNames = [event, ...(events ?? [])].filter(Boolean)+ return eventNames.length > 0 && eventNames.every((name) => name === FEATURE_FLAG_CALLED_EVENT)+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface eventsSceneLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -35,9 +50,9 @@ export interface eventsSceneLogicValues {currentTeam: TeamPublicType | TeamType | null // teamLogicbreadcrumbs: Breadcrumb[]defaultQuery: DataTableNode+ flagCallsNote: FlagCallsNote | nullquery: 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.@@ -68,10 +83,10 @@ export interface eventsSceneLogicMeta {savedQuery: Node<Record<string, any>> | null,defaultQuery: DataTableNode) => DataTableNode | Node<Record<string, any>>- showFlagCallsNote: (+ flagCallsNote: (currentTeam: TeamPublicType | TeamType | null,query: DataTableNode | Node<Record<string, any>>- ) => boolean+ ) => FlagCallsNote | null}}@@ -129,22 +144,24 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([(s) => [s.savedQuery, s.defaultQuery],(savedQuery: Node | null, defaultQuery: DataTableNode) => savedQuery || defaultQuery,],- showFlagCallsNote: [+ flagCallsNote: [(s) => [s.currentTeam, s.query],- (currentTeam: TeamPublicType | TeamType | null, query: DataTableNode | Node): boolean => {+ (currentTeam: TeamPublicType | TeamType | null, query: DataTableNode | Node): FlagCallsNote | null => {if (- currentTeam?.flag_evaluations_mode !== FLAG_EVALUATIONS_ONLY_MODE ||+ !readsFlagEvaluationsTable(currentTeam) ||!isDataTableNode(query) ||!isEventsQuery(query.source)) {- return false+ return null}- const { source, actionId, actionSteps, event, events } = query.source- if (source || actionId || actionSteps?.length) {- return true+ if (!listsOnlyFlagCalls(query.source)) {+ return currentTeam?.flag_evaluations_mode === FLAG_EVALUATIONS_ONLY_MODE+ ? 'stored-separately'+ : null}- const eventNames = [event, ...(events ?? [])].filter(Boolean)- return eventNames.length === 0 || eventNames.some((name) => name !== FEATURE_FLAG_CALLED_EVENT)+ const { after } = query.source+ // The runner reads a missing start as the last 24 hours. The retention window covers that range.+ return after && reachesPastFlagEvaluationsRetention(after) ? 'retention' : null},],breadcrumbs: [diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 5e45de328ca4..5b3401de0eac 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -101,6 +101,7 @@ import FeatureFlagSchedule from './FeatureFlagSchedule'import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'import { FeatureFlagUsageMetrics } from './FeatureFlagUsageMetrics'+import { FLAG_EVALUATIONS_RETENTION_DAYS, readsFlagEvaluationsTable } from './featureFlagUsageQueries'import { useFeatureFlagAgentRefresh } from './useFeatureFlagAgentRefresh'const RESOURCE_TYPE = 'feature_flag'@@ -763,6 +764,7 @@ function UsageTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Elemen} = featureFlagconst { enrichAnalyticsNoticeAcknowledged } = useValues(featureFlagsLogic)const { closeEnrichAnalyticsNotice } = useActions(featureFlagsLogic)+ const { currentTeam } = useValues(teamLogic)const propertyFilter: AnyPropertyFilter[] = [{@@ -803,6 +805,11 @@ function UsageTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Elemen<div className="mt-4 mb-4"><b>Log</b><div className="text-secondary">{`Feature flag calls for "${featureFlagKey}" will appear here`}</div>+ {readsFlagEvaluationsTable(currentTeam) && (+ <div className="text-secondary">+ The log can show calls from up to {FLAG_EVALUATIONS_RETENTION_DAYS} days ago.+ </div>+ )}</div><Queryquery={{diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.tsindex c0e26f0fadba..e16909516a04 100644--- a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts@@ -4,7 +4,6 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'import { Noun, groupsModel } from '~/models/groupsModel'import { DateRange } from '~/queries/schema/schema-general'import { DateMappingOption, FeatureFlagType, TeamPublicType, TeamType } from '~/types'@@ -21,10 +20,9 @@ import {buildFlagEvaluationsUniqueCallersChart,clampToFlagEvaluationsRetention,flagEvaluationsDateOptions,+ readsFlagEvaluationsTable,} from './featureFlagUsageQueries'-const EVENTS_MODE = FlagEvaluationsModeEnumApi.Number0-// The Usage tab only renders for persisted flags, so unlike featureFlagLogic this// logic never mounts for 'new'/'link' ids.export interface FeatureFlagUsageLogicProps {@@ -128,8 +126,7 @@ export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = ke// a missing table.readsFlagEvaluationsTable: [(s) => [s.currentTeam],- (currentTeam: TeamPublicType | TeamType | null): boolean =>- (currentTeam?.flag_evaluations_mode ?? EVENTS_MODE) !== EVENTS_MODE,+ (currentTeam: TeamPublicType | TeamType | null): boolean => readsFlagEvaluationsTable(currentTeam),],// flag_evaluations holds 90 days, so a longer range would show fewer rows than the events// table. The clamp covers the date picker, a shared link, and a range typed into the URL.diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.tsindex d79d29b3f060..f182764be789 100644--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts@@ -9,6 +9,7 @@ import { dayjs } from 'lib/dayjs'import { dateMapping, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'import { BREAKDOWN_NULL_DISPLAY } from 'scenes/insights/utils'+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'import { Noun } from '~/models/groupsModel'import {ChartSettings,@@ -30,6 +31,8 @@ import {GroupTypeIndex,PropertyFilterType,PropertyOperator,+ TeamPublicType,+ TeamType,} from '~/types'export interface FlagUsageQueryOptions {@@ -193,9 +196,18 @@ const FLAG_EVALUATIONS_TABLE = 'posthog.flag_evaluations'// editor rejects that key, but the API accepts it.const FLAG_EVALUATIONS_VARIANT = `if(response IN ('', 'null'), ${escapeHogQLString(BREAKDOWN_NULL_DISPLAY)}, response)`-/** How long a row stays in flag_evaluations. The events table keeps $feature_flag_called forever. */+/**+ * How long a row stays in flag_evaluations. The events table keeps $feature_flag_called forever.+ * Keep it equal to FLAG_EVALUATIONS_TTL_DAYS in posthog/models/flag_evaluations/sql.py.+ */export const FLAG_EVALUATIONS_RETENTION_DAYS = 90+const EVENTS_MODE = FlagEvaluationsModeEnumApi.Number0++export function readsFlagEvaluationsTable(team: TeamPublicType | TeamType | null): boolean {+ return (team?.flag_evaluations_mode ?? EVENTS_MODE) !== EVENTS_MODE+}+// Start of the oldest day the table still holds. dateStringToDayJs resolves the ranges this is// compared to against UTC, so the boundary is UTC too: a browser-local midnight sits hours off it,// which drops the 90-day preset in a timezone ahead of UTC.@@ -203,14 +215,18 @@ function earliestRetainedDay(): dayjs.Dayjs {return dayjs.utc().startOf('day').subtract(FLAG_EVALUATIONS_RETENTION_DAYS, 'day')}+export function reachesPastFlagEvaluationsRetention(dateFrom: string | null): boolean {+ const parsed = dateStringToDayJs(dateFrom)+ // A null start and "all" are all time, which reaches further than any retained day.+ return !parsed || parsed.isBefore(earliestRetainedDay())+}+/** Pulls a range back inside the retention window, where it cannot quietly show fewer rows than the events table. */export function clampToFlagEvaluationsRetention(dateRange: DateRange): DateRange {- const earliest = earliestRetainedDay()- const dateFrom = dateStringToDayJs(dateRange.date_from ?? null)- // A null start is "all time", which reaches further than any retained day.- if (dateFrom && !dateFrom.isBefore(earliest)) {+ if (!reachesPastFlagEvaluationsRetention(dateRange.date_from ?? null)) {return dateRange}+ const earliest = earliestRetainedDay()const dateTo = dateStringToDayJs(dateRange.date_to ?? null)return {date_from: `-${FLAG_EVALUATIONS_RETENTION_DAYS}d`,@@ -222,14 +238,9 @@ export function clampToFlagEvaluationsRetention(dateRange: DateRange): DateRange/** The presets that stay inside the retention window, plus the custom-range entry. */export function flagEvaluationsDateOptions(): DateMappingOption[] {- const earliest = earliestRetainedDay()return dateMapping.filter(({ values }) => {const dateFrom = values[0]- if (dateFrom === undefined) {- return true- }- const parsed = dateStringToDayJs(dateFrom)- return !!parsed && !parsed.isBefore(earliest)+ return dateFrom === undefined || !reachesPastFlagEvaluationsRetention(dateFrom)})}diff --git a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.tsindex 34801360ac78..a2f765f91cc0 100644--- a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts+++ b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts@@ -59,7 +59,7 @@ const EDITABLE_INSTANCE_SETTINGS = ['RATE_LIMIT_ENABLED','RATE_LIMITING_ALLOW_LIST_TEAMS','FLAGS_LOG_BODIES_TEAMS',- 'FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS',+ 'FLAG_EVALUATIONS_READS_FORCE_EVENTS','CLICKHOUSE_KILL_SWITCH','CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS','CLICKHOUSE_KILL_SWITCH_FULL_TEAMS',diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 53d28273c50c..fe4db4ec7ceb 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -127,7 +127,7 @@ from products.access_control.backend.presentation.access_control import ()from products.access_control.backend.presentation.access_control_settings import AccessControlSettingsViewSetMixinfrom products.feature_flags.backend.facade.enums import FlagEvaluationsMode-from products.feature_flags.backend.facade.flags import get_usage_tab_flag_evaluations_mode+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_modefrom products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfigfrom products.feature_flags.backend.models.evaluation_context import (EvaluationContext,@@ -983,7 +983,7 @@ class ProjectBackwardCompatSerializer(@extend_schema_field(serializers.ChoiceField(choices=FlagEvaluationsMode.choices))def get_flag_evaluations_mode(self, obj: Project) -> int:- return get_usage_tab_flag_evaluations_mode(obj.organization_id)+ return get_flag_evaluations_read_mode(obj.organization_id)@staticmethoddef validate_revenue_analytics_config(value):diff --git a/posthog/api/team.py b/posthog/api/team.pyindex c6103f284d3f..350b5a9794c6 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -131,7 +131,7 @@ from products.customer_analytics.backend.facade.contracts import PinnedAccountPrfrom products.customer_analytics.backend.facade.enums import ACCOUNT_PROPERTY_PIN_KIND_CHOICESfrom products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfigfrom products.feature_flags.backend.facade.enums import FlagEvaluationsMode-from products.feature_flags.backend.facade.flags import get_usage_tab_flag_evaluations_mode+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_modefrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_namefrom products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.logs.backend.models import TeamLogsConfig@@ -1524,7 +1524,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin@extend_schema_field(serializers.ChoiceField(choices=FlagEvaluationsMode.choices))def get_flag_evaluations_mode(self, obj: Team) -> int:- return get_usage_tab_flag_evaluations_mode(obj.organization_id)+ return get_flag_evaluations_read_mode(obj.organization_id)@extend_schema_field(serializers.ListField(child=serializers.ChoiceField(choices=[(e.value, e.value) for e in SetupTaskId]))diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex e99884655b48..c2007b14611d 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -1271,12 +1271,12 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore),])- def test_flag_evaluations_mode_while_the_usage_tab_is_forced_to_events(self, _name, stored_mode, expected_mode):+ def test_flag_evaluations_mode_while_reads_are_forced_to_events(self, _name, stored_mode, expected_mode):OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).update(flag_evaluations_mode=stored_mode)- with override_instance_config("FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS", True):+ with override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", True):response = self.client.get(f"/api/projects/{self.project.id}/")self.assertEqual(response.json()["flag_evaluations_mode"], expected_mode)diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex b7da400ecd96..f4f8b534e732 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -3033,7 +3033,7 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore),])- def test_page_load_team_follows_the_usage_tab_switch(self, _name, stored_mode, expected_mode):+ def test_page_load_team_follows_the_reads_switch(self, _name, stored_mode, expected_mode):OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).update(flag_evaluations_mode=stored_mode)@@ -3041,7 +3041,7 @@ class TestTeamAPI(team_api_test_factory()): # type: ignorerequest.user = self.userrequest.session = self.client.session- with override_instance_config("FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS", True):+ with override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", True):context = get_context_for_template("index.html", request)self.assertEqual(context["posthog_app_context"]["current_team"]["flag_evaluations_mode"], expected_mode)diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.pyindex 13645a41880c..44407bd05ac7 100644--- a/posthog/hogql_queries/events_query_runner.py+++ b/posthog/hogql_queries/events_query_runner.py@@ -45,13 +45,14 @@ from posthog.api.element import ElementSerializerfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIESfrom posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.dataclasses import frozen+from posthog.date_util import start_of_dayfrom posthog.hogql_queries.insight_actors_query_runner import InsightActorsQueryRunnerfrom posthog.hogql_queries.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runnerfrom 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_EVENT+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENT, FLAG_EVALUATIONS_TTL_DAYSfrom 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_tag@@ -59,7 +60,7 @@ from posthog.utils import relative_date_parsefrom products.actions.backend.models.action import Action, ActionStepJSONfrom products.feature_flags.backend.facade.enums import FlagEvaluationsMode-from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_modelogger = structlog.get_logger(__name__)@@ -88,6 +89,9 @@ class EventsListTable:looks_up_person_display_names: bool# Fields that join another table. The outer presorted query leaves out filters on them.joined_fields: frozenset[str]+ # The list starts no earlier than the UTC start of the day this many days back.+ retention_days: int | None+ cache_key_variant: strdef join_expr(self) -> ast.JoinExpr:return ast.JoinExpr(table=ast.Field(chain=[*self.chain]), alias=self.alias)@@ -99,6 +103,8 @@ EVENTS_LIST_TABLE = EventsListTable(person_id="person.id",looks_up_person_display_names=False,joined_fields=frozenset(),+ retention_days=None,+ cache_key_variant="",)FLAG_EVALUATIONS_LIST_TABLE = EventsListTable(chain=("posthog", "flag_evaluations"),@@ -114,6 +120,12 @@ FLAG_EVALUATIONS_LIST_TABLE = EventsListTable(# the query sorts by Person and joins persons anyway.looks_up_person_display_names=True,joined_fields=EVENTS_LIST_JOINED_FIELDS,+ # flag_evaluations drops a monthly part only after its newest row passes the TTL. Rows older than the TTL can+ # therefore remain for up to a month. This bound ends the list at the first day that the Usage tab charts show.+ # The TTL has already expired the rows of that day when today starts, so the list can show only part of that day.+ # The day is empty after a TTL merge drops every part that holds it.+ retention_days=FLAG_EVALUATIONS_TTL_DAYS,+ cache_key_variant="_flag_evaluations",)@@ -181,6 +193,11 @@ def _exact_flag_keys(prop: QueryPropertyFilter) -> list[str] | None:return [str(value) for value in values]+def _retention_start_expr(retention_days: int) -> ast.Expr:+ retention_start = start_of_day(now()) - timedelta(days=retention_days)+ return parse_expr("timestamp >= {retention_start}", {"retention_start": ast.Constant(value=retention_start)})++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."""@@ -390,7 +407,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):has_any_aggregation = len(aggregations) > 0where_exprs = self._filter_where_exprs(table)- where_exprs.extend(self._timestamp_where_exprs())+ where_exprs.extend(self._timestamp_where_exprs(table))# where & havingwith self.timings.measure("where"):@@ -409,16 +426,19 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):def _event_names(self) -> list[str]:return [e for e in [self.query.event, *(self.query.events or [])] if e]+ @cached_propertydef _list_table(self) -> EventsListTable:if self.query.source is not None or self.query.actionId or self.query.actionSteps:return EVENTS_LIST_TABLEif 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:+ if get_flag_evaluations_read_mode(self.team.organization_id) == FlagEvaluationsMode.EVENTS:return EVENTS_LIST_TABLEreturn FLAG_EVALUATIONS_LIST_TABLE+ def get_cache_key_variant(self) -> str:+ return super().get_cache_key_variant() + self._list_table.cache_key_variant+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 Noneif flag_keys is None:@@ -532,7 +552,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):op=ast.CompareOperationOp.In,)- def _timestamp_where_exprs(self) -> list[ast.Expr]:+ def _timestamp_where_exprs(self, table: EventsListTable) -> list[ast.Expr]:with self.timings.measure("timestamps"):# prevent accidentally future events from being visible by defaultbefore = self.query.before or (now() + timedelta(seconds=5)).isoformat()@@ -542,6 +562,8 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):after = self.query.after or "-24h"if after != "all":exprs.append(self._timestamp_boundary_expr(after, AFTER_BOUNDARY))+ if table.retention_days is not None:+ exprs.append(_retention_start_expr(table.retention_days))return exprsdef _timestamp_boundary_expr(self, cursor: str, boundary: TimestampBoundary) -> ast.Expr:@@ -703,7 +725,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):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()+ table = self._list_tablemodifiers = self._query_modifiers(table)query_result = self.paginator.execute_hogql_query(query=self._build_query(table),diff --git a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambrindex b4d814b2816f..8f82d9a6375d 100644--- a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr+++ b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr@@ -303,9 +303,9 @@WHERE and(equals(flag_evaluations.team_id, 99999), in(flag_evaluations.uuid,(SELECT flag_evaluations.uuid AS uuidFROM 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')))+ 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')), greaterOrEquals(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'))))+ 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')), greaterOrEquals(flag_evaluations.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))ORDER BY toTimeZone(flag_evaluations.timestamp, 'UTC') ASC, flag_evaluations.uuid ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.pyindex b36b7733a119..942051f46036 100644--- a/posthog/hogql_queries/test/test_events_query_runner.py+++ b/posthog/hogql_queries/test/test_events_query_runner.py@@ -35,10 +35,13 @@ from posthog.hogql import astfrom posthog.hogql.ast import CompareOperationOpfrom posthog.clickhouse.client import sync_execute+from posthog.date_util import start_of_dayfrom 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.flag_evaluations.sql import FLAG_EVALUATIONS_TTL_DAYSfrom posthog.models.group.util import create_group+from posthog.models.instance_setting import override_instance_configfrom posthog.models.person.util import get_person_by_distinct_idfrom posthog.test.persons import create_group_type_mapping@@ -1428,7 +1431,14 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):"read_flag_evaluations_mode",FlagEvaluationsMode.READ_FLAG_EVALUATIONS,{"event": "$feature_flag_called"},+ FLAG_EVALUATIONS_FLAG_KEY,+ ),+ (+ "read_flag_evaluations_mode_while_reads_are_forced_to_events",+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ {"event": "$feature_flag_called"},EVENTS_FLAG_KEY,+ True,),("flag_evaluations_only_without_an_event_filter",@@ -1451,18 +1461,63 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):])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,+ _name: str,+ mode: FlagEvaluationsMode,+ query_filter: dict[str, Any],+ expected_flag_key: str,+ reads_forced_to_events: bool = False,):self._set_flag_evaluations_mode(mode)self._create_flag_calls_in_both_tables()- with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ with (+ time_machine.travel("2020-01-11T12:01:00Z", tick=False),+ override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", reads_forced_to_events),+ ):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 test_forcing_reads_to_events_skips_a_list_cached_from_flag_evaluations(self):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)+ self._create_flag_calls_in_both_tables()+ query = EventsQuery(+ kind="EventsQuery", select=["properties.$feature_flag"], event="$feature_flag_called", after="-30d"+ )++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ from_flag_evaluations = EventsQueryRunner(query=query, team=self.team).run()+ with override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", True):+ from_events = EventsQueryRunner(query=query, team=self.team).run()++ assert isinstance(from_flag_evaluations, CachedEventsQueryResponse)+ assert isinstance(from_events, CachedEventsQueryResponse)+ assert [row[0] for row in from_flag_evaluations.results] == [FLAG_EVALUATIONS_FLAG_KEY]+ assert [row[0] for row in from_events.results] == [EVENTS_FLAG_KEY]++ @parameterized.expand([("range_older_than_retention", "-180d"), ("all_time", "all")])+ def test_flag_evaluations_list_stops_at_the_retention_window(self, _name: str, after: str):+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)+ self._insert_flag_evaluation("recent-user", uuid.uuid4())+ self._insert_flag_evaluation(+ "first-retained-day-user",+ uuid.uuid4(),+ timestamp=start_of_day(FLAG_CALL_TIMESTAMP - timedelta(days=FLAG_EVALUATIONS_TTL_DAYS)),+ )+ self._insert_flag_evaluation(+ "expired-user", uuid.uuid4(), timestamp=FLAG_CALL_TIMESTAMP - timedelta(days=FLAG_EVALUATIONS_TTL_DAYS + 30)+ )++ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):+ query = EventsQuery(kind="EventsQuery", select=["distinct_id"], event="$feature_flag_called", after=after)+ response = EventsQueryRunner(query=query, team=self.team).run()++ assert isinstance(response, CachedEventsQueryResponse)+ assert sorted(row[0] for row in response.results) == ["first-retained-day-user", "recent-user"]+@snapshot_clickhouse_queriesdef test_flag_evaluations_person_display_names_resolve_each_rows_person_id(self):self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex 15c8eb69a628..459775c73caf 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -337,14 +337,16 @@ CONSTANCE_CONFIG = {'Per-team /flags request and response body logging. JSON object mapping team_id (string) to a non-empty list of flag-key wildcard patterns; the response is filtered to flags matching any pattern. "{}" disables logging entirely. Examples: \'{"123": ["my-feature", "checkout-*"]}\' logs only matching flag keys for team 123. To capture every flag (rare, noisy), use [\\"*\\"] explicitly. The Rust feature-flags service polls this every ~60s. Limits: at most 100 teams, 50 patterns per team, 256 bytes per pattern.',str,),- "FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS": (- get_from_env("FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS", False, type_cast=str_to_bool),- "When on, the feature flag Usage tab reads the events table for every organization on flag_evaluations "- "mode 1. Use it when the flag_evaluations table stops receiving rows. Organizations on mode 2 keep reading "- "flag_evaluations, because ingestion writes no flag calls to events for their teams in the ingestion "- "allowlist. "+ "FLAG_EVALUATIONS_READS_FORCE_EVENTS": (+ get_from_env("FLAG_EVALUATIONS_READS_FORCE_EVENTS", False, type_cast=str_to_bool),+ "When on, every organization on flag_evaluations mode 1 reads its flag calls from the events table: the "+ "feature flag Usage tab, the per-project counts on a flag's Projects tab, and event lists filtered to only "+ "$feature_flag_called. Use it when the flag_evaluations table stops receiving rows. Organizations on mode 2 "+ "keep reading flag_evaluations, because ingestion writes no flag calls to events for their teams in the "+ "ingestion allowlist. ""Stored modes and the flag_evaluations SQL table stay as they are, so turning it off restores every "- "organization. Takes up to a minute to apply, and a page reload to show.",+ "organization. Takes up to a minute to apply. Pages that are already open need a reload to update the Usage "+ "tab charts and the 90-day notes.",bool,),"REDIRECT_APP_TO_US": (@@ -468,7 +470,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("RATE_LIMIT_ENABLED","RATE_LIMITING_ALLOW_LIST_TEAMS","FLAGS_LOG_BODIES_TEAMS",- "FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS",+ "FLAG_EVALUATIONS_READS_FORCE_EVENTS","CLICKHOUSE_KILL_SWITCH","CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS","CLICKHOUSE_KILL_SWITCH_FULL_TEAMS",diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 4678b6a1e176..4c8cb0d975eb 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -170,10 +170,10 @@ TEAM_METADATA_CACHE_VERIFICATION_GRACE_PERIOD_MINUTES: int = get_from_env()# OrganizationFeatureFlagsConfig.flag_evaluations_mode for a new organization. 0 reads-# $feature_flag_called from events. 1 reads it from flag_evaluations for the flag Usage tab charts.-# 2 also reads it from flag_evaluations for the per-project counts on a flag's Projects tab and for-# events lists filtered to only $feature_flag_called, and stops writing it to events for teams in the-# ingestion allowlist. A change here never moves an existing organization.+# $feature_flag_called from events. 1 reads it from flag_evaluations for the flag Usage tab, the+# per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called.+# 2 also stops writing it to events for teams in the ingestion allowlist. A change here never moves an+# existing organization.FLAG_EVALUATIONS_NEW_ORG_MODE: int = get_from_env("FLAG_EVALUATIONS_NEW_ORG_MODE", 0, type_cast=int)# Feature flag limits to prevent memory issues during flag evaluation/caching.diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.pyindex 1d0396c8a68e..499752e4ceaf 100644--- a/products/feature_flags/backend/api/staff_team_config.py+++ b/products/feature_flags/backend/api/staff_team_config.py@@ -22,6 +22,7 @@ from products.feature_flags.backend.api.staff_cache import _team_ids_fieldfrom products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_modefrom products.feature_flags.backend.flag_evaluations_mode import (+ FLAG_EVALUATIONS_MODES_HELP,OrganizationModeChange,UnknownIdsError,get_organizations_of_teams,@@ -111,13 +112,8 @@ class StaffTeamConfigSerializer(serializers.Serializer):choices=FlagEvaluationsMode.choices,help_text=("Which table the $feature_flag_called data of this team's organization is read from. Every team of "- "an organization shares one mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab "- "charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's "- "Projects tab and for events lists filtered to only $feature_flag_called, such as the Activity page and "- "the Usage tab log. On 2, ingestion stops writing $feature_flag_called to events for the teams it "- "writes to flag_evaluations. This is the stored mode: while the "- "FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS instance setting is on, an organization on 1 has its Usage tab "- "read events anyway."+ f"an organization shares one mode. {FLAG_EVALUATIONS_MODES_HELP} This is the stored mode: while the "+ "FLAG_EVALUATIONS_READS_FORCE_EVENTS instance setting is on, an organization on 1 reads events anyway."),)feature_flag_count = serializers.IntegerField(@@ -173,12 +169,7 @@ class StaffTeamConfigMutationSerializer(serializers.Serializer):class StaffFlagEvaluationsModeMutationSerializer(serializers.Serializer):flag_evaluations_mode = serializers.ChoiceField(choices=FlagEvaluationsMode.choices,- help_text=(- "Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab "- "charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's "- "Projects tab and for events lists filtered to only $feature_flag_called, and stops ingestion writing "- "$feature_flag_called to events for the teams it writes to flag_evaluations."- ),+ help_text=f"Target flag_evaluations mode. {FLAG_EVALUATIONS_MODES_HELP}",)team_ids = serializers.ListField(child=serializers.IntegerField(),diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 9aa94cefb1d7..75048f522bae 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -19,6 +19,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.models.instance_setting import override_instance_configfrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team@@ -3956,11 +3957,20 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):@parameterized.expand([("events", FlagEvaluationsMode.EVENTS, 2, 1),- ("read_flag_evaluations", FlagEvaluationsMode.READ_FLAG_EVALUATIONS, 2, 1),+ ("read_flag_evaluations", FlagEvaluationsMode.READ_FLAG_EVALUATIONS, 1, 3),("flag_evaluations_only", FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY, 1, 3),+ (+ "read_flag_evaluations_while_reads_are_forced_to_events",+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ 2,+ 1,+ True,+ ),])- def test_evaluation_counts_come_from_the_table_the_mode_selects(self, _name, mode, team_count, other_team_count):+ def test_evaluation_counts_come_from_the_table_the_mode_selects(+ self, _name, mode, team_count, other_team_count, reads_forced_to_events=False+ ):OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).update(flag_evaluations_mode=mode)_create_event(team=self.team,@@ -3984,7 +3994,8 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):_create_flag_evaluations(self.team.id, "shared_flag")_create_flag_evaluations(self.other_team.id, "shared_flag", count=3)- body = self.client.get(self._url("shared_flag")).json()+ with override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", reads_forced_to_events):+ body = self.client.get(self._url("shared_flag")).json()by_team = {entry["team_id"]: entry["evaluations_7d"] for entry in body}assert by_team == {self.team.id: team_count, self.other_team.id: other_team_count}diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.pyindex 163dd1502cd3..4f2ff63bad10 100644--- a/products/feature_flags/backend/facade/enums.py+++ b/products/feature_flags/backend/facade/enums.py@@ -10,14 +10,16 @@ class FlagEvaluationsMode(LabeledIntEnum):allowlist includes."""- # The Usage tab reads the events table. The flag_evaluations HogQL table stays hidden unless- # the flag-evaluations-hogql-table flag is on for the organization.+ # Every reader of $feature_flag_called reads the events table. The flag_evaluations HogQL table stays+ # hidden unless the flag-evaluations-hogql-table flag is on for the organization.EVENTS = 0, "Events"- # The Usage tab charts read flag_evaluations, and the HogQL table is visible.+ # The Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only+ # $feature_flag_called read flag_evaluations. Other readers, such as experiment exposures, still read events.+ # The HogQL table is visible.+ # Ingestion still writes every flag call to events, so FLAG_EVALUATIONS_READS_FORCE_EVENTS can move these+ # readers back to events.READ_FLAG_EVALUATIONS = 1, "Read flag evaluations"- # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. These readers- # stay on events in READ_FLAG_EVALUATIONS and read flag_evaluations only in this mode: the per-project- # counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called. A team- # outside the ingestion allowlist still writes to events. INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED- # makes ingestion treat this mode as READ_FLAG_EVALUATIONS for every organization.+ # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. A team outside+ # the ingestion allowlist still writes to events. INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED makes+ # ingestion treat this mode as READ_FLAG_EVALUATIONS for every organization.FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"diff --git a/products/feature_flags/backend/facade/flags.py b/products/feature_flags/backend/facade/flags.pyindex 5205c8d020a1..c7369f3114a1 100644--- a/products/feature_flags/backend/facade/flags.py+++ b/products/feature_flags/backend/facade/flags.py@@ -31,14 +31,15 @@ def get_organization_flag_evaluations_mode(organization_id: UUID) -> int:return FlagEvaluationsMode.EVENTS if mode is None else mode-def get_usage_tab_flag_evaluations_mode(organization_id: UUID) -> int:- """The mode that decides which table the flag Usage tab reads. FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS makes- it EVENTS for an organization on READ_FLAG_EVALUATIONS and leaves the stored mode unchanged."""+def get_flag_evaluations_read_mode(organization_id: UUID) -> int:+ """The mode that picks the table for the flag-call readers that the READ_FLAG_EVALUATIONS comment lists.+ FLAG_EVALUATIONS_READS_FORCE_EVENTS makes it EVENTS for an organization on READ_FLAG_EVALUATIONS and leaves+ the stored mode unchanged."""mode = get_organization_flag_evaluations_mode(organization_id)# The switch skips FLAG_EVALUATIONS_ONLY. For teams in the ingestion allowlist, events holds none of that- # organization's flag calls, so the Usage tab would show empty days instead of the flag_evaluations rows.+ # organization's flag calls, so the readers would show no calls instead of the flag_evaluations rows.if mode == FlagEvaluationsMode.READ_FLAG_EVALUATIONS and get_instance_setting(- "FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS"+ "FLAG_EVALUATIONS_READS_FORCE_EVENTS"):return FlagEvaluationsMode.EVENTSreturn modediff --git a/products/feature_flags/backend/flag_analytics.py b/products/feature_flags/backend/flag_analytics.pyindex 4d0b01efba64..23dc8c2ec738 100644--- a/products/feature_flags/backend/flag_analytics.py+++ b/products/feature_flags/backend/flag_analytics.py@@ -18,7 +18,7 @@ from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_TABLEfrom posthog.redis import get_client, redisfrom products.feature_flags.backend.facade.enums import FlagEvaluationsMode-from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_modefrom products.feature_flags.backend.models.feature_flag import FeatureFlagif TYPE_CHECKING:@@ -357,18 +357,13 @@ def get_cached_evaluations_7d_by_team("""Cached variant of get_evaluations_7d_by_team with a 5-minute TTL.Every team in `team_ids` must belong to the organization `organization_id`.- Only an organization on FLAG_EVALUATIONS_ONLY reads flag_evaluations. Unlike- the Usage tab, READ_FLAG_EVALUATIONS stays on events, because ingestion keeps- writing every flag call to events in that mode.Failure results (None) are not cached, so recovery is immediate onceClickHouse is reachable again."""if not team_ids:return {}- from_flag_evaluations = (- get_organization_flag_evaluations_mode(organization_id) == FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY- )+ from_flag_evaluations = get_flag_evaluations_read_mode(organization_id) != FlagEvaluationsMode.EVENTS# The key names the source table, so a mode change cannot serve a count read from the other table.source = FLAG_EVALUATIONS_TABLE if from_flag_evaluations else "events"cache_key = f"flag_analytics:evals_7d:{source}:{flag_key}:" + ",".join(str(t) for t in sorted(team_ids))diff --git a/products/feature_flags/backend/flag_evaluations_mode.py b/products/feature_flags/backend/flag_evaluations_mode.pyindex e2851dff3178..b9707006a921 100644--- a/products/feature_flags/backend/flag_evaluations_mode.py+++ b/products/feature_flags/backend/flag_evaluations_mode.py@@ -15,6 +15,13 @@ from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_modefrom products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig+FLAG_EVALUATIONS_MODES_HELP = (+ "0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects "+ "tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is "+ "available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for "+ "teams in the ingestion allowlist."+)+@frozenclass OrganizationModeChange:diff --git a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.pyindex 90bff81ff2d2..21f987e11356 100644--- a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py+++ b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py@@ -18,6 +18,7 @@ from django.db import transactionfrom products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.flag_evaluations_mode import (+ FLAG_EVALUATIONS_MODES_HELP,UnknownIdsError,get_organizations,select_organizations,@@ -43,11 +44,7 @@ class Command(BaseCommand):required=True,choices=FlagEvaluationsMode.values,help=(- "0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is "- "available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for "- "events lists filtered to only $feature_flag_called, such as the Activity page and the Usage tab "- "log. On 2, ingestion stops writing $feature_flag_called to events for teams in the ingestion "- "allowlist. "+ f"{FLAG_EVALUATIONS_MODES_HELP} ""flag_evaluations holds rows only from the day ingestion started writing them ""(2026-09-09 for PostHog Cloud), so on mode 1 or 2 the Usage tab shows no data for earlier days."),diff --git a/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py b/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.pyindex 75a1751ccaed..dd7758c656b4 100644--- a/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py+++ b/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py@@ -116,10 +116,10 @@ class TestSetFlagEvaluationsMode(BaseTest):self.assertEqual(get_organization_flag_evaluations_mode(self.organization.id), expected_mode)self.assertIn(expected_output, output)- def test_allow_downgrade_lowers_the_stored_mode_while_the_usage_tab_is_forced_to_events(self) -> None:+ def test_allow_downgrade_lowers_the_stored_mode_while_reads_are_forced_to_events(self) -> None:self._store_mode(self.organization, FlagEvaluationsMode.READ_FLAG_EVALUATIONS)- with override_instance_config("FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS", True):+ with override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", True):self._run("--mode", "0", "--organization-id", str(self.organization.id), "--allow-downgrade")self.assertEqual(self._stored_mode(self.organization), FlagEvaluationsMode.EVENTS)diff --git a/products/feature_flags/backend/test/test_organization_feature_flags_config.py b/products/feature_flags/backend/test/test_organization_feature_flags_config.pyindex 39c86afc65eb..0055a133b7ed 100644--- a/products/feature_flags/backend/test/test_organization_feature_flags_config.py+++ b/products/feature_flags/backend/test/test_organization_feature_flags_config.py@@ -57,7 +57,7 @@ class TestFlagEvaluationsTableGate(BaseTest):),("no_config_row_without_the_flag", None, False, False, False),(- "read_flag_evaluations_while_the_usage_tab_is_forced_to_events",+ "read_flag_evaluations_while_reads_are_forced_to_events",FlagEvaluationsMode.READ_FLAG_EVALUATIONS,False,True,@@ -66,7 +66,7 @@ class TestFlagEvaluationsTableGate(BaseTest):])def test_table_is_enabled_by_the_organization_mode_or_the_flag(- self, _name, mode, flag_enabled, usage_tab_forced_to_events, expected+ self, _name, mode, flag_enabled, reads_forced_to_events, expected):config = OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization)if mode is None:@@ -77,6 +77,6 @@ class TestFlagEvaluationsTableGate(BaseTest):with (self.settings(DEBUG=False, E2E_TESTING=False),patch("products.feature_flags.backend.facade.flags.feature_enabled_or_false", return_value=flag_enabled),- override_instance_config("FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS", usage_tab_forced_to_events),+ override_instance_config("FLAG_EVALUATIONS_READS_FORCE_EVENTS", reads_forced_to_events),):self.assertEqual(is_flag_evaluations_table_enabled(self.team), expected)diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 6c18f60b04fa..a9476c36e00c 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -209,7 +209,7 @@ export interface StaffTeamConfigApi {max_feature_flags_override: number | null/** The flag-count limit actually enforced for this team: the override when one is set, otherwise the global MAX_FEATURE_FLAGS_PER_TEAM setting. */effective_max_feature_flags: number- /** Which table the $feature_flag_called data of this team's organization is read from. Every team of an organization shares one mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for events lists filtered to only $feature_flag_called, such as the Activity page and the Usage tab log. On 2, ingestion stops writing $feature_flag_called to events for the teams it writes to flag_evaluations. This is the stored mode: while the FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS instance setting is on, an organization on 1 has its Usage tab read events anyway.+ /** Which table the $feature_flag_called data of this team's organization is read from. Every team of an organization shares one mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for teams in the ingestion allowlist. This is the stored mode: while the FLAG_EVALUATIONS_READS_FORCE_EVENTS instance setting is on, an organization on 1 reads events anyway.** * `0` - Events* * `1` - Read flag evaluations@@ -244,7 +244,7 @@ export interface StaffTeamConfigMutationApi {}export interface StaffFlagEvaluationsModeMutationApi {- /** Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for events lists filtered to only $feature_flag_called, and stops ingestion writing $feature_flag_called to events for the teams it writes to flag_evaluations.+ /** Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for teams in the ingestion allowlist.** * `0` - Events* * `1` - Read flag evaluationsdiff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 1dbeaf8e3372..b9233fcbc909 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -139,7 +139,7 @@ export const FeatureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBody = /* @_flag_evaluations_mode: zod.union([zod.literal(0), zod.literal(1), zod.literal(2)]).describe(- "Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for events lists filtered to only $feature_flag_called, and stops ingestion writing $feature_flag_called to events for the teams it writes to flag_evaluations.\n\n\* `0` - Events\n\* `1` - Read flag evaluations\n\* `2` - Flag evaluations only"+ "Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for teams in the ingestion allowlist.\n\n\* `0` - Events\n\* `1` - Read flag evaluations\n\* `2` - Flag evaluations only"),team_ids: zod.array(zod.number())diff --git a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsxindex 5549eccaa382..52a3ecefda2e 100644--- a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx+++ b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx@@ -17,10 +17,13 @@ import { pluralize } from 'lib/utils/strings'import { FlagEvaluationsModeEnumApi, StaffOrganizationModeChangeApi } from '../generated/api.schemas'import { FLAG_EVALUATIONS_MODE_LABELS, featureFlagsStaffToolsLogic } from './featureFlagsStaffToolsLogic'+const FLAG_CALL_READERS =+ "The Usage tab, the per-project counts on a flag's Projects tab, and any events list filtered to $feature_flag_called"+const 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, the per-project counts on a flag's Projects tab, and any events list filtered to $feature_flag_called read the flag_evaluations table, and the table is available in SQL. For teams in the ingestion allowlist, ingestion also stops writing $feature_flag_called to the events table.",+ 0: `${FLAG_CALL_READERS} read the events table.`,+ 1: `${FLAG_CALL_READERS} read the flag_evaluations table, and the table is available in SQL. While the FLAG_EVALUATIONS_READS_FORCE_EVENTS instance setting is on, they read the events table instead.`,+ 2: `${FLAG_CALL_READERS} read the flag_evaluations table, and the table is available in SQL. For teams in the ingestion allowlist, ingestion also stops writing $feature_flag_called to the events table.`,}export function StaffFlagEvaluationsModeModal(): JSX.Element {@@ -74,7 +77,7 @@ export function StaffFlagEvaluationsModeModal(): JSX.Element {return (<LemonModaltitle="Set flag evaluations mode"- description="Choose which table the flag Usage tab reads $feature_flag_called data from. The mode applies to the whole organization of each selected team."+ description="Choose which table $feature_flag_called data is read from. The mode applies to the whole organization of each selected team."isOpen={isFlagEvaluationsModeModalOpen}onClose={closeFlagEvaluationsModeModal}closable={!flagEvaluationsModeResultLoading}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c2450bbf6924..4fd664e44c0b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101907,7 +101907,7 @@ export namespace Schemas {}export interface StaffFlagEvaluationsModeMutation {- /** Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for events lists filtered to only $feature_flag_called, and stops ingestion writing $feature_flag_called to events for the teams it writes to flag_evaluations.+ /** Target flag_evaluations mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for teams in the ingestion allowlist.** * `0` - Events* * `1` - Read flag evaluations@@ -101989,7 +101989,7 @@ export namespace Schemas {max_feature_flags_override: number | null;/** The flag-count limit actually enforced for this team: the override when one is set, otherwise the global MAX_FEATURE_FLAGS_PER_TEAM setting. */effective_max_feature_flags: number;- /** Which table the $feature_flag_called data of this team's organization is read from. Every team of an organization shares one mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab charts, and the table is available in SQL. 2 also reads it for the per-project counts on a flag's Projects tab and for events lists filtered to only $feature_flag_called, such as the Activity page and the Usage tab log. On 2, ingestion stops writing $feature_flag_called to events for the teams it writes to flag_evaluations. This is the stored mode: while the FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS instance setting is on, an organization on 1 has its Usage tab read events anyway.+ /** Which table the $feature_flag_called data of this team's organization is read from. Every team of an organization shares one mode. 0 reads events. 1 reads flag_evaluations for the flag Usage tab, the per-project counts on a flag's Projects tab, and events lists filtered to only $feature_flag_called, such as the Activity page, and the table is available in SQL. 2 reads the same way as 1, and ingestion stops writing $feature_flag_called to events for teams in the ingestion allowlist. This is the stored mode: while the FLAG_EVALUATIONS_READS_FORCE_EVENTS instance setting is on, an organization on 1 reads events anyway.** * `0` - Events* * `1` - Read flag evaluations