: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): skip events writes for flag evaluations only orgs (#110254)
Phil Haack6b2869bef969
diff --git a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.test.ts b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.test.tsindex 8f75c7e31d6d..7737344e2621 100644--- a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.test.ts+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.test.ts@@ -1,4 +1,5 @@import { IngestionLane } from '~/ingestion/config'+import { FlagEvaluationsMode } from '~/types'import { FlagEvaluationsEnvConfig, createFlagEvaluationsService } from './flag-evaluations-service'@@ -14,6 +15,7 @@ describe('FlagEvaluationsService', () => {INGESTION_FLAG_EVALUATIONS_MODE: mode,INGESTION_FLAG_EVALUATIONS_TEAMS: teams,INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: excludedTeams,+ INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED: false,INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: topic,})@@ -52,4 +54,23 @@ describe('FlagEvaluationsService', () => {expect(service?.isEnabledForTeam(teamId)).toBe(expected)})})++ describe('stopsEventsWritesFor', () => {+ it.each([+ [false, true],+ [true, false],+ ])(+ 'INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED=%s -> %s for a FLAG_EVALUATIONS_ONLY team',+ (onlyDisabled, expected) => {+ const service = createFlagEvaluationsService({+ ...envConfig('dual_write'),+ INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED: onlyDisabled,+ })++ expect(+ service?.stopsEventsWritesFor({ flag_evaluations_mode: FlagEvaluationsMode.FlagEvaluationsOnly })+ ).toBe(expected)+ }+ )+ })})diff --git a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.tsindex 24158854f487..c0aba0d79900 100644--- a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts@@ -7,21 +7,24 @@ import {IngestionOutputsConfig,REALTIME_INGESTION_LANES,} from '~/ingestion/config'-import { ValueMatcher } from '~/types'+import { FlagEvaluationsMode, Team, ValueMatcher } from '~/types'export interface FlagEvaluationsConfig {/** '*' for all teams, or an explicit allowlist of team IDs. */teams: number[] | '*'/** Escape hatch: teams never forked, even when `teams` is '*'. */excludedTeams: number[]+ /** Keeps the events writes for teams on FLAG_EVALUATIONS_ONLY. */+ flagEvaluationsOnlyDisabled: boolean}/**- * Gate for the $feature_flag_called fork that shadow-writes flag evaluations to- * the ClickHouse flag_evaluations table (via the clickhouse_flag_evaluations- * topic) while the event continues to the events table unchanged.+ * Gate for the $feature_flag_called fork that writes flag evaluations to the+ * ClickHouse flag_evaluations table (via the clickhouse_flag_evaluations+ * topic). The event continues to the events table unless the team's+ * organization is on FLAG_EVALUATIONS_ONLY.*- * The shadow write is never load-bearing for an individual event, but the batch+ * The fork write is never load-bearing for a dual-written event, but the batch* does not commit its offsets until the broker answers. See* createForkFlagEvaluationsStep for the ack contract and* flagEvaluationsPendingAcks for the stall it can cause.@@ -34,14 +37,22 @@ export interface FlagEvaluationsConfig {*/export class FlagEvaluationsService {private isEnabled: ValueMatcher<number>+ private flagEvaluationsOnlyDisabled: booleanconstructor(config: FlagEvaluationsConfig) {this.isEnabled = buildTeamGate(config.teams, config.excludedTeams)+ this.flagEvaluationsOnlyDisabled = config.flagEvaluationsOnlyDisabled}isEnabledForTeam(teamId: number): boolean {return this.isEnabled(teamId)}++ stopsEventsWritesFor(team: Pick<Team, 'flag_evaluations_mode'>): boolean {+ return (+ team.flag_evaluations_mode === FlagEvaluationsMode.FlagEvaluationsOnly && !this.flagEvaluationsOnlyDisabled+ )+ }}export type FlagEvaluationsEnvConfig = Pick<@@ -50,6 +61,7 @@ export type FlagEvaluationsEnvConfig = Pick<| 'INGESTION_FLAG_EVALUATIONS_MODE'| 'INGESTION_FLAG_EVALUATIONS_TEAMS'| 'INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS'+ | 'INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED'> &Pick<IngestionOutputsConfig, 'INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC'>@@ -104,5 +116,9 @@ export function createFlagEvaluationsService(envConfig: FlagEvaluationsEnvConfiglogger.warn('INGESTION_FLAG_EVALUATIONS_MODE is set but INGESTION_FLAG_EVALUATIONS_TEAMS is empty, not forking')return undefined}- return new FlagEvaluationsService({ teams, excludedTeams })+ return new FlagEvaluationsService({+ teams,+ excludedTeams,+ flagEvaluationsOnlyDisabled: envConfig.INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED,+ })}diff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.test.tsindex f6dd20684ad1..5c878ed302a0 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.test.ts@@ -6,7 +6,8 @@ import { castTimestampOrNow } from '~/common/utils/utils'import { isOkResult } from '~/ingestion/framework/results'import { createTestEventHeaders } from '~/tests/helpers/event-headers'import { createTestMessage } from '~/tests/helpers/kafka-message'-import { Person, PersonMode, PreIngestionEvent, ProjectId, TimestampFormat } from '~/types'+import { createTestTeam } from '~/tests/helpers/team'+import { Person, PersonMode, PreIngestionEvent, ProjectId, Team, TimestampFormat } from '~/types'import { CreateEventStepInput, createCreateEventStep } from './create-event-step'@@ -14,9 +15,11 @@ describe('create-event-step', () => {let mockPerson: Personlet mockPreparedEvent: PreIngestionEventlet mockMessage: Message+ let mockTeam: TeambeforeEach(() => {mockMessage = createTestMessage()+ mockTeam = createTestTeam({ id: 1 })mockPerson = {team_id: 1,properties: { email: '[email protected]', name: 'Test User' },@@ -40,6 +43,7 @@ describe('create-event-step', () => {it('should create event with processPerson=true', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -75,6 +79,7 @@ describe('create-event-step', () => {it('should create event with processPerson=false', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: false,@@ -105,6 +110,7 @@ describe('create-event-step', () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: personWithForceUpgrade,preparedEvent: mockPreparedEvent,processPerson: true,@@ -134,6 +140,7 @@ describe('create-event-step', () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: eventWithSetProperties,processPerson: true,@@ -159,6 +166,7 @@ describe('create-event-step', () => {it('should preserve event properties as native object', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -191,6 +199,7 @@ describe('create-event-step', () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: eventWithElements,processPerson: true,@@ -217,6 +226,7 @@ describe('create-event-step', () => {const step = createCreateEventStep<typeof EVENTS_OUTPUT, CustomInput>(EVENTS_OUTPUT)const input: CustomInput = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -238,6 +248,7 @@ describe('create-event-step', () => {it('should set correct timestamps', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -269,6 +280,7 @@ describe('create-event-step', () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: eventWithType,processPerson: true,@@ -292,6 +304,7 @@ describe('create-event-step', () => {it('duplicates multivariate $feature_flag_called events for allowlisted teams with a deterministic uuid', async () => {const step = createCreateEventStep(EVENTS_OUTPUT, '2')const input = {+ team: mockTeam,person: mockPerson,preparedEvent: {...mockPreparedEvent,@@ -340,6 +353,7 @@ describe('create-event-step', () => {])('does not duplicate %s', async (_, teamId, event, response) => {const step = createCreateEventStep(EVENTS_OUTPUT, '2')const result = await step({+ team: mockTeam,person: mockPerson,preparedEvent: {...mockPreparedEvent,@@ -363,6 +377,7 @@ describe('create-event-step', () => {it('does not duplicate when no teams are configured', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const result = await step({+ team: mockTeam,person: mockPerson,preparedEvent: {...mockPreparedEvent,@@ -388,6 +403,7 @@ describe('create-event-step', () => {it('should include historical_migration in event when historicalMigration=true', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -409,6 +425,7 @@ describe('create-event-step', () => {it('should not include historical_migration in event when historicalMigration=false', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: mockPerson,preparedEvent: mockPreparedEvent,processPerson: true,@@ -441,6 +458,7 @@ describe('create-event-step', () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person,preparedEvent: mockPreparedEvent,processPerson: config.processPerson,@@ -464,6 +482,7 @@ describe('create-event-step', () => {it('should generate deterministic person_id from distinct_id when person is undefined', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: undefined,preparedEvent: mockPreparedEvent,processPerson: true,@@ -486,6 +505,7 @@ describe('create-event-step', () => {it('should return empty person_properties when person is undefined', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: undefined,preparedEvent: mockPreparedEvent,processPerson: true,@@ -507,6 +527,7 @@ describe('create-event-step', () => {it('should set person_created_at to null when person is undefined', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: undefined,preparedEvent: mockPreparedEvent,processPerson: true,@@ -528,6 +549,7 @@ describe('create-event-step', () => {it('should set person_mode to full when person is undefined and processPerson=true', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: undefined,preparedEvent: mockPreparedEvent,processPerson: true,@@ -549,6 +571,7 @@ describe('create-event-step', () => {it('should set person_mode to propertyless when person is undefined and processPerson=false', async () => {const step = createCreateEventStep(EVENTS_OUTPUT)const input = {+ team: mockTeam,person: undefined,preparedEvent: mockPreparedEvent,processPerson: false,diff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.tsindex 927c80555c52..8946c2bb92d8 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts@@ -7,7 +7,7 @@ import { createEvent } from '~/ingestion/common/steps/event-processing/create-evimport { EventUsageRecord } from '~/ingestion/common/steps/usage-records-steps'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { EventHeaders, Person, PreIngestionEvent } from '~/types'+import { EventHeaders, Person, PreIngestionEvent, Team } from '~/types'import { EventToEmit } from './emit-event-step'@@ -34,6 +34,7 @@ function isMultivariateFeatureFlagCalledEvent(event: PreIngestionEvent): boolean}export interface CreateEventStepInput {+ team: Teamperson?: PersonpreparedEvent: PreIngestionEventprocessPerson: boolean@@ -45,6 +46,7 @@ export interface CreateEventStepInput {}export interface CreateEventStepResult<O extends string> {+ team: TeameventsToEmit: EventToEmit<O>[]teamId: numberheaders: EventHeaders@@ -61,6 +63,7 @@ export function createCreateEventStep<O extends string, T extends CreateEventStereturn function createEventStep(input) {const {+ team,person,preparedEvent,processPerson,@@ -95,6 +98,7 @@ export function createCreateEventStep<O extends string, T extends CreateEventSte}const result: CreateEventStepResult<O> = {+ team,eventsToEmit,teamId: preparedEvent.teamId,headers,diff --git a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.tsindex d806904d3260..49f311be0626 100644--- a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts@@ -8,7 +8,7 @@ import { MessageSizeTooLarge } from '~/common/utils/db/error'import { safeClickhouseString } from '~/common/utils/db/utils'import { castTimestampOrNow, castTimestampToClickhouseFormat } from '~/common/utils/utils'import { isAiEventName } from '~/ingestion/common/ai-event-types'-import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'+import { IngestionWarning, emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'import { eventProcessedAndIngestedCounter } from '~/ingestion/common/metrics'import { EventUsageRecord } from '~/ingestion/common/steps/usage-records-steps'import { ok } from '~/ingestion/framework/results'@@ -97,15 +97,11 @@ export function createEmitEventStep<O extends string, T extends EmitEventStepInp// Some messages end up significantly larger than the original// after plugin processing, person & group enrichment, etc.if (error instanceof MessageSizeTooLarge) {- await emitIngestionWarning(outputs, serialized.team_id, {- type: 'message_size_too_large',- details: {- eventUuid: serialized.uuid,- distinctId: serialized.distinct_id,- personId: serialized.person_id,- },- pipelineStep: 'emit-event',- })+ await emitIngestionWarning(+ outputs,+ serialized.team_id,+ eventTooLargeWarning(serialized, 'emit-event')+ )// The event was not ingested, so there is no info to resolve withreturn null} else {@@ -129,6 +125,17 @@ export function createEmitEventStep<O extends string, T extends EmitEventStepInp}}+export function eventTooLargeWarning(+ event: { uuid: string; distinct_id: string; person_id?: string },+ pipelineStep: string+): IngestionWarning {+ return {+ type: 'message_size_too_large',+ details: { eventUuid: event.uuid, distinctId: event.distinct_id, personId: event.person_id },+ pipelineStep,+ }+}+export function serializeEvent(event: ProcessedEvent): RawKafkaEvent {return {uuid: event.uuid,diff --git a/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.test.tsindex 128b36cb5440..f7dc8fe8d65e 100644--- a/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.test.ts@@ -1,12 +1,12 @@import { DateTime } from 'luxon'-import { FlagEvaluationsOutput } from '~/common/outputs'+import { FlagEvaluationsOutput, IngestionWarningsOutput } from '~/common/outputs'import { MessageSizeTooLarge } from '~/common/utils/db/error'import { parseJSON } from '~/common/utils/json-parse'import { FlagEvaluationsService } from '~/ingestion/common/flag-evaluations/flag-evaluations-service'import { isOkResult } from '~/ingestion/framework/results'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'-import { ISOTimestamp, ProcessedEvent, ProjectId } from '~/types'+import { FlagEvaluationsMode, ISOTimestamp, ProcessedEvent, ProjectId } from '~/types'import { EventToEmit } from './emit-event-step'import {@@ -19,15 +19,19 @@ import {// Real instances: the service is a pure, synchronous config gate, so mocking// it would only hide drift from the real class. Team 7 matches createInput.-const enabledService = () => new FlagEvaluationsService({ teams: '*', excludedTeams: [] })-const teamExcludedService = () => new FlagEvaluationsService({ teams: '*', excludedTeams: [7] })+const enabledService = (flagEvaluationsOnlyDisabled = false) =>+ new FlagEvaluationsService({ teams: '*', excludedTeams: [], flagEvaluationsOnlyDisabled })+const teamExcludedService = () =>+ new FlagEvaluationsService({ teams: '*', excludedTeams: [7], flagEvaluationsOnlyDisabled: false })const createStep = (service: FlagEvaluationsService) => {- const outputs = createMockIngestionOutputs<FlagEvaluationsOutput>()+ const outputs = createMockIngestionOutputs<FlagEvaluationsOutput | IngestionWarningsOutput>()const step = createForkFlagEvaluationsStep<ForkFlagEvaluationsStepInput>(outputs, service)return { step, outputs }}+type StepDeps = ReturnType<typeof createStep>+const createProcessedEvent = (overrides: Partial<ProcessedEvent> = {}): ProcessedEvent => ({uuid: 'event-uuid-1',event: '$feature_flag_called',@@ -46,9 +50,18 @@ const createProcessedEvent = (overrides: Partial<ProcessedEvent> = {}): Processe...overrides,})-const createInput = (events: ProcessedEvent[] = [createProcessedEvent()]): ForkFlagEvaluationsStepInput => ({+// create-event appends this renamed copy of a multivariate flag call for+// exposure-allowlisted teams. The copy belongs to the events table only.+const createExposureDuplicate = (): ProcessedEvent =>+ createProcessedEvent({ event: '$experiment_exposure', uuid: 'dup-uuid' })++const createInput = (+ events: ProcessedEvent[] = [createProcessedEvent()],+ mode: FlagEvaluationsMode = FlagEvaluationsMode.Events+): ForkFlagEvaluationsStepInput => ({eventsToEmit: events.map((event): EventToEmit<string> => ({ event, output: 'events' })),teamId: 7,+ team: { flag_evaluations_mode: mode },})describe('createForkFlagEvaluationsStep', () => {@@ -148,12 +161,8 @@ describe('createForkFlagEvaluationsStep', () => {})it('forks only the $feature_flag_called entry, not the $experiment_exposure duplicate', async () => {- // create-event appends a renamed duplicate for exposure-allowlisted- // teams; that copy belongs to the events table only.const { step, outputs } = createStep(enabledService())- const original = createProcessedEvent()- const exposureDuplicate = createProcessedEvent({ event: '$experiment_exposure', uuid: 'dup-uuid' })- const input = createInput([original, exposureDuplicate])+ const input = createInput([createProcessedEvent(), createExposureDuplicate()])await step(input)@@ -215,24 +224,52 @@ describe('createForkFlagEvaluationsStep', () => {expect((await flagEvaluationsPendingAcks.get()).values[0].value).toBe(0)})- it('does not block the batch when the row exceeds the broker message limit', async () => {- const { step, outputs } = createStep(enabledService())- outputs.queueMessages.mockRejectedValue(new MessageSizeTooLarge('too large', new Error('too large')))- const input = createInput()-- const result = await step(input)-- // An oversized row gets its own outcome and no warning, because- // retrying or alerting on it would change nothing.- expect(isOkResult(result)).toBe(true)- if (isOkResult(result)) {- await expect(result.sideEffects[0]).resolves.toBeUndefined()+ // An oversized row gets its own outcome and no log warning, because+ // retrying or alerting on it would change nothing. A FLAG_EVALUATIONS_ONLY+ // team has no events row to carry emit-event's oversize warning, so the+ // fork sends that ingestion warning instead.+ it.each([+ {+ name: 'an EVENTS',+ mode: FlagEvaluationsMode.Events,+ outcome: 'continued_message_too_large',+ producedOutputs: ['flag_evaluations'],+ warnings: [],+ },+ {+ name: 'a FLAG_EVALUATIONS_ONLY',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ outcome: 'lost_message_too_large',+ producedOutputs: ['flag_evaluations', 'ingestion_warnings'],+ warnings: [{ type: 'message_size_too_large', eventUuid: 'event-uuid-1' }],+ },+ ])(+ 'does not block the batch when the row exceeds the broker message limit for $name team',+ async ({ mode, outcome, producedOutputs, warnings }) => {+ const { step, outputs } = createStep(enabledService())+ outputs.queueMessages.mockRejectedValueOnce(+ new MessageSizeTooLarge('too large', new Error('too large'))+ )+ const input = createInput([createProcessedEvent()], mode)++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ await result.sideEffects[0]+ }+ expect((await flagEvaluationsEventsTotal.get()).values).toEqual([+ expect.objectContaining({ labels: { outcome }, value: 1 }),+ ])+ expect(outputs.queueMessages.mock.calls.map(([output]) => output)).toEqual(producedOutputs)+ const sentWarnings = outputs.queueMessages.mock.calls+ .filter(([output]) => output === 'ingestion_warnings')+ .flatMap(([, messages]) => messages.map((message) => parseJSON(message.value!.toString())))+ .map((warning) => ({ type: warning.type, eventUuid: parseJSON(warning.details).eventUuid }))+ expect(sentWarnings).toEqual(warnings)+ expect((await flagEvaluationsPendingAcks.get()).values[0].value).toBe(0)}- expect((await flagEvaluationsEventsTotal.get()).values).toContainEqual(- expect.objectContaining({ labels: { outcome: 'continued_message_too_large' }, value: 1 })- )- expect((await flagEvaluationsPendingAcks.get()).values[0].value).toBe(0)- })+ )it('still returns ok(input) with no ack side effect when queueMessages throws synchronously', async () => {const { step, outputs } = createStep(enabledService())@@ -263,4 +300,94 @@ describe('createForkFlagEvaluationsStep', () => {)})})++ describe('FLAG_EVALUATIONS_ONLY mode', () => {+ it('removes the queued $feature_flag_called event from eventsToEmit and keeps the $experiment_exposure copy', async () => {+ const { step, outputs } = createStep(enabledService())+ const input = createInput(+ [createProcessedEvent(), createExposureDuplicate()],+ FlagEvaluationsMode.FlagEvaluationsOnly+ )++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.eventsToEmit.map(({ event }) => event.uuid)).toEqual(['dup-uuid'])+ await Promise.all(result.sideEffects)+ }+ // For a FLAG_EVALUATIONS_ONLY team the flag_evaluations row is the only copy of the call.+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)+ expect(outputs.queueMessages.mock.calls[0][1].map((message) => message.key)).toEqual(['event-uuid-1'])+ // The counter records one outcome per event, so the removed call must not also count as dual_written.+ expect((await flagEvaluationsEventsTotal.get()).values).toEqual([+ expect.objectContaining({ labels: { outcome: 'flag_evaluations_only' }, value: 1 }),+ ])+ })++ it.each([+ {+ name: 'the mode is EVENTS',+ mode: FlagEvaluationsMode.Events,+ buildService: () => enabledService(),+ },+ {+ name: 'the mode is READ_FLAG_EVALUATIONS',+ mode: FlagEvaluationsMode.ReadFlagEvaluations,+ buildService: () => enabledService(),+ },+ {+ name: 'INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED is on',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ buildService: () => enabledService(true),+ },+ {+ name: 'the team is not enabled',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ buildService: () => teamExcludedService(),+ },+ {+ name: 'the flag key is missing',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ buildService: () => enabledService(),+ flagCalledProperties: { $feature_flag_response: true },+ },+ {+ name: 'queueing the row throws',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ buildService: () => enabledService(),+ arrange: ({ outputs }: StepDeps) =>+ outputs.queueMessages.mockImplementation(() => {+ throw new Error('sync produce failure')+ }),+ },+ ])(+ 'keeps the $feature_flag_called event in eventsToEmit when $name',+ async ({ mode, buildService, flagCalledProperties, arrange }) => {+ const deps = createStep(buildService())+ arrange?.(deps)+ const input = createInput(+ [+ createProcessedEvent(flagCalledProperties && { properties: flagCalledProperties }),+ createExposureDuplicate(),+ ],+ mode+ )++ const result = await deps.step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value.eventsToEmit.map(({ event }) => event.uuid)).toEqual([+ 'event-uuid-1',+ 'dup-uuid',+ ])+ await Promise.all(result.sideEffects)+ }+ expect((await flagEvaluationsEventsTotal.get()).values).not.toContainEqual(+ expect.objectContaining({ labels: { outcome: 'flag_evaluations_only' } })+ )+ }+ )+ })})diff --git a/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.ts b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.tsindex c7aaac343960..a153315e100c 100644--- a/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.ts@@ -1,16 +1,18 @@import { Counter, Gauge } from 'prom-client'-import { FLAG_EVALUATIONS_OUTPUT, FlagEvaluationsOutput } from '~/common/outputs'+import { FLAG_EVALUATIONS_OUTPUT, FlagEvaluationsOutput, IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { IngestionOutputMessage } from '~/common/outputs/types'import { MessageSizeTooLarge } from '~/common/utils/db/error'import { logger } from '~/common/utils/logger'import { mapProcessedEventToFlagEvaluationRow } from '~/ingestion/common/flag-evaluations/flag-evaluation-row'import { FlagEvaluationsService } from '~/ingestion/common/flag-evaluations/flag-evaluations-service'+import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'+import { Team } from '~/types'-import { EventToEmit } from './emit-event-step'+import { EventToEmit, eventTooLargeWarning } from './emit-event-step'export const flagEvaluationsEventsTotal = new Counter({name: 'ingestion_flag_evaluations_events_total',@@ -52,13 +54,16 @@ const hasFlagKey = ({ event }: EventToEmit<string>): boolean => {export interface ForkFlagEvaluationsStepInput {eventsToEmit: EventToEmit<string>[]teamId: number+ team: Pick<Team, 'flag_evaluations_mode'>}/*** Forks $feature_flag_called events into the flag_evaluations ClickHouse table:* narrows the assembled events row to the flag_evaluations column set and- * produces it to the clickhouse_flag_evaluations topic while the event- * continues to the events table unchanged.+ * produces it to the clickhouse_flag_evaluations topic. The event continues to+ * the events table unchanged, except for a team whose organization is on+ * FLAG_EVALUATIONS_ONLY: this step removes each event it queued for that team+ * from eventsToEmit.** Sits between create-event and emit-event, where the fully assembled* ProcessedEvent exists: person_id and person_properties from person@@ -67,14 +72,15 @@ export interface ForkFlagEvaluationsStepInput {* name excludes the $experiment_exposure duplicate that create-event appends* for allowlisted teams.*- * Every failure path continues toward the events table, including a produce- * that fails permanently: the row is counted and dropped, never retried. The ack+ * Every failure path before the produce is queued continues toward the events+ * table. A produce that fails permanently is counted and dropped, never+ * retried, so for a FLAG_EVALUATIONS_ONLY team the call is lost. The ack* rides as a side effect, so the batch does not commit its offsets until the* broker answers. Pipe this step without a retry envelope, because a retry* would queue the produce again.*/export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepInput>(- outputs: IngestionOutputs<FlagEvaluationsOutput>,+ outputs: IngestionOutputs<FlagEvaluationsOutput | IngestionWarningsOutput>,flagEvaluationsService: FlagEvaluationsService): ProcessingStep<T, T> {return function forkFlagEvaluationsStep(input) {@@ -94,6 +100,7 @@ export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepIif (mappableEvents.length === 0) {return Promise.resolve(ok(input))}+ const stopsEventsWrites = flagEvaluationsService.stopsEventsWritesFor(input.team)try {const messages: IngestionOutputMessage[] = mappableEvents.map(({ event }) => {if (event.properties['$set'] || event.properties['$set_once']) {@@ -107,31 +114,64 @@ export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepIconst ack = outputs.queueMessages(FLAG_EVALUATIONS_OUTPUT, messages)flagEvaluationsPendingAcks.inc(messages.length)// Count on the ack, not the enqueue, so a failed produce is not reported as- // dual-written.+ // written.//// The ack never rejects. Only one host redelivers the batch on a rejected// side effect; the rest stop the process or the pod (see// PipelineContext.sideEffects). The backfill owns history for this table,- // so a lost row costs less than a stopped consumer.+ // so a lost dual-written row costs less than a stopped consumer.+ //+ // The fork alerts in PostHog/charts alerts/specs/feature-flags.yaml match these+ // outcome names. FlagEvaluationsForkStalled must list every outcome counted+ // below, or a healthy pod that emits only a new outcome pages as stalled.const settled = ack.then(() => {flagEvaluationsPendingAcks.dec(messages.length)- flagEvaluationsEventsTotal.labels('dual_written').inc(messages.length)+ flagEvaluationsEventsTotal+ .labels(stopsEventsWrites ? 'flag_evaluations_only' : 'dual_written')+ .inc(messages.length)},(error: unknown) => {flagEvaluationsPendingAcks.dec(messages.length)if (error instanceof MessageSizeTooLarge) {// An oversized row is a property of the row, not of the broker, so- // it gets its own outcome and no warning: retrying or alerting on- // it would change nothing. emit-event skips an oversized event for- // the same reason.- flagEvaluationsEventsTotal.labels('continued_message_too_large').inc(messages.length)- return+ // it gets its own outcome and no log warning: retrying or alerting+ // on it would change nothing. emit-event skips an oversized event+ // for the same reason.+ flagEvaluationsEventsTotal+ .labels(stopsEventsWrites ? 'lost_message_too_large' : 'continued_message_too_large')+ .inc(messages.length)+ if (!stopsEventsWrites) {+ return+ }+ // The row carries the event's full properties, so the events row+ // would also be oversized. emit-event sends the team an ingestion+ // warning for an oversized event. No events row exists here, so this+ // step sends that warning.+ return Promise.all(+ mappableEvents.map(({ event }) =>+ emitIngestionWarning(+ outputs,+ event.team_id,+ eventTooLargeWarning(event, 'fork-flag-evaluations')+ )+ )+ )}flagEvaluationsEventsTotal.labels('produce_failed').inc(messages.length)})- return Promise.resolve(ok(input, [settled]))+ if (!stopsEventsWrites) {+ return Promise.resolve(ok(input, [settled]))+ }+ // The queued produce is the only copy of these calls. A produce that fails+ // after this step returns loses the call. produce_failed and+ // lost_message_too_large count those losses. The+ // FlagEvaluationsForkProduceFailing alert fires on produce_failed.+ // Matching by object identity keeps the $experiment_exposure copy and any+ // call without a flag key in eventsToEmit.+ const eventsToEmit = input.eventsToEmit.filter((toEmit) => !mappableEvents.includes(toEmit))+ return Promise.resolve(ok({ ...input, eventsToEmit }, [settled]))} catch (error) {logger.warn('Failed to fork $feature_flag_called event to flag_evaluations, continuing', {teamId: input.teamId,diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 2b5dcae6bc53..3354c5951bf4 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -253,12 +253,14 @@ export type IngestionConsumerConfig = {EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: string// $feature_flag_called fork into the flag_evaluations ClickHouse table- /** 'disabled' | 'dual_write' (produce to flag_evaluations while the event continues to events) */+ /** 'disabled' | 'dual_write' (produce to flag_evaluations). With dual_write the event also continues to events unless its organization is on FLAG_EVALUATIONS_ONLY. */INGESTION_FLAG_EVALUATIONS_MODE: string/** '*' for all teams, or comma-separated team IDs */INGESTION_FLAG_EVALUATIONS_TEAMS: string/** Comma-separated team IDs never forked, even when TEAMS is '*' */INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: string+ /** Rollback for FLAG_EVALUATIONS_ONLY. True keeps writing $feature_flag_called to events for organizations on that mode, as if they were on READ_FLAG_EVALUATIONS. */+ INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED: boolean// $feature_flag_called keep-first dedup config/** 'disabled' | 'shadow' (claim + count, never drop) | 'drop' */@@ -427,6 +429,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {INGESTION_FLAG_EVALUATIONS_MODE: 'disabled',INGESTION_FLAG_EVALUATIONS_TEAMS: '',INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: '',+ INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED: false,// $feature_flag_called keep-first dedup configINGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: 'disabled',diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.tsindex 521ca1713e32..8094eb424cb6 100644--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts@@ -176,7 +176,7 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi// Composed at build time so the disabled fleet default pays no per-event step// overhead. No retry envelope: a retry would queue the produce again. Unlike// emit-event below, this produce is best effort: its ack settles inside the- // step and a failure drops the shadow row.+ // step and a failure drops the row.if (flagEvaluationsService) {pipeline = pipeline.pipe(createForkFlagEvaluationsStep(outputs, flagEvaluationsService))}diff --git a/nodejs/tests/helpers/sql.ts b/nodejs/tests/helpers/sql.tsindex 0739e0690dbc..4ae38ad8cb87 100644--- a/nodejs/tests/helpers/sql.ts+++ b/nodejs/tests/helpers/sql.ts@@ -266,7 +266,14 @@ export async function createUserTeamAndOrganization(})// Map drop_events_older_than_seconds to drop_events_older_than for database insertion- const { drop_events_older_than_seconds, ...otherTeamOverrides } = teamOverrides+ const { drop_events_older_than_seconds, flag_evaluations_mode, ...otherTeamOverrides } = teamOverrides+ // The team reads flag_evaluations_mode from its organization's config row, not from posthog_team.+ if (flag_evaluations_mode !== undefined) {+ await insertRow(db, 'feature_flags_organizationfeatureflagsconfig', {+ organization_id: organizationId,+ flag_evaluations_mode,+ })+ }const teamData: Record<string, any> = {id: teamId,project_id: teamId,diff --git a/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts b/nodejs/tests/ingestion/flag-evaluations-e2e.test.tsindex ffdf62c189c4..291936114c32 100644--- a/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts+++ b/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts@@ -22,6 +22,8 @@ import {waitForKafkaMessages,} from '~/tests/helpers/ingestion-e2e'import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'+import { fetchPostgresPersons } from '~/tests/helpers/sql'+import { FlagEvaluationsMode } from '~/types'jest.mock('~/common/utils/logger')@@ -103,6 +105,49 @@ describe('Flag evaluations shadow-routing E2E', () => {})+ testWithTeamIngester(+ 'FLAG_EVALUATIONS_ONLY team: the call lands only in flag_evaluations, and its person update and $experiment_exposure copy still land',+ {+ teamOverrides: { flag_evaluations_mode: FlagEvaluationsMode.FlagEvaluationsOnly },+ pluginServerConfig: {+ INGESTION_FLAG_EVALUATIONS_MODE: 'dual_write',+ INGESTION_FLAG_EVALUATIONS_TEAMS: '*',+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,+ EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: '*',+ },+ },+ async ({ infra, ingester, team, kafkaProducer, token }) => {+ // A variant response makes create-event append the $experiment_exposure copy.+ const event = new EventBuilder(team)+ .withEvent('$feature_flag_called')+ .withProperties({+ $feature_flag: 'my-flag',+ $feature_flag_response: 'test-variant',+ $set: { plan: 'pro' },+ })+ .build()++ await ingester.handleKafkaBatch(createKafkaMessages([event], token))+ await waitForKafkaMessages(kafkaProducer)++ const persons = await fetchPostgresPersons(infra.postgres, team.id)+ expect(persons).toEqual([expect.objectContaining({ properties: expect.objectContaining({ plan: 'pro' }) })])++ await waitForExpect(async () => {+ expect(await fetchFlagEvaluations(clickhouse, team.id)).toHaveLength(1)+ }, 30_000)+ const events = await waitForExpect(async () => {+ const rows = await fetchEvents(clickhouse, team.id)+ expect(rows.map((row) => row.event)).toContain('$experiment_exposure')+ return rows+ }, 30_000)+ // create-event puts the call before its copy, and both go to the same+ // single-partition topic. A call written to events would already be visible here.+ expect(events.map((row) => row.event)).toEqual(['$experiment_exposure'])+ expect(events[0].person_id).toBe(persons[0].uuid)+ }+ )+it('ships disabled by default', () => {// The only thing the round trip above would add for the disabled case:// that nothing flipped the fleet default. createFlagEvaluationsServicediff --git a/posthog/models/flag_evaluations/PARITY_CHECK.md b/posthog/models/flag_evaluations/PARITY_CHECK.mdindex 3be8ed6bf589..805c5618709b 100644--- a/posthog/models/flag_evaluations/PARITY_CHECK.md+++ b/posthog/models/flag_evaluations/PARITY_CHECK.md@@ -80,7 +80,7 @@ A team with no rows on the day produces no result row at all. Compare the return**`only_in_events` is a deficit.** The events table has a uuid the fork never wrote. This is the failure the check exists for, and it blocks widening. Deficit has measured zero on every day checked that was not a team's activation day, so treat any non-zero value as real rather than as noise. Walk the four items in the next section before chasing it, because three of them produce a false deficit.-**`only_in_flag_evaluations` is an excess.** The fork wrote a uuid the events table has no row for, which is loss on the events side. It has been small and non-zero on some days and zero on others. It is not explained yet, and on its own it does not block widening. Raise it if it grows.+**`only_in_flag_evaluations` is an excess.** The fork wrote a uuid the events table has no row for, which is loss on the events side. It has been small and non-zero on some days and zero on others. It is not explained yet, and on its own it does not block widening. Raise it if it grows. For a team whose organization is on `FLAG_EVALUATIONS_ONLY`, ingestion writes no `$feature_flag_called` rows to events, so every uuid lands here and the check does not apply to that team.**`in_both` is the covered population.** Use it as the denominator when judging whether either of the other two columns is large enough to matter.diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 354fb4b0a513..5ea73e64c84e 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -168,9 +168,8 @@ 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. 2 also stops writing it to events-# once ingestion supports that. Until then 2 acts as 1. A change here never moves an existing-# organization.+# $feature_flag_called from events. 1 reads it from flag_evaluations. 2 also stops writing it to events.+# 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/experiments/backend/facade/__init__.py b/products/experiments/backend/facade/__init__.pyindex 229377bf7b9a..0c06d59cadd1 100644--- a/products/experiments/backend/facade/__init__.py+++ b/products/experiments/backend/facade/__init__.py@@ -4,10 +4,11 @@ Facade for experiments product.This module provides the public interface for other products to interact with experiments."""-from .api import create_experiment+from .api import count_running_experiments_on_feature_flag_called, create_experimentfrom .contracts import CreateExperimentInput, Experiment, FeatureFlag__all__ = [+ "count_running_experiments_on_feature_flag_called","create_experiment","CreateExperimentInput","Experiment",diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.pyindex 1252c200c9ed..4b97d50783e5 100644--- a/products/experiments/backend/facade/api.py+++ b/products/experiments/backend/facade/api.py@@ -5,12 +5,19 @@ This module provides the public interface for creating and managing experimentsusing framework-free DTOs, wrapping the existing ExperimentService."""+from uuid import UUID+from rest_framework.exceptions import ValidationErrorfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom products.experiments.backend.experiment_service import ExperimentService+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ DEFAULT_EXPOSURE_EVENT,+ get_exposure_event_and_property,+ resolve_default_exposure_event,+)from products.experiments.backend.models.experiment import Experiment as ExperimentModelfrom .contracts import CreateExperimentInput, Experiment@@ -89,6 +96,30 @@ def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInpureturn _experiment_model_to_dto(experiment_model)+def count_running_experiments_on_feature_flag_called(organization_id: UUID) -> int:+ """Count the organization's running experiments that count exposures on $feature_flag_called.++ Those exposures come from the events table, so they stop when ingestion stops writing+ $feature_flag_called to events.+ """+ experiments = (+ ExperimentModel.objects.filter(+ team__organization_id=organization_id, start_date__isnull=False, end_date__isnull=True, archived=False+ )+ .exclude(deleted=True)+ .select_related("team", "feature_flag")+ )+ count = 0+ for experiment in experiments:+ exposure_event, _ = get_exposure_event_and_property(+ experiment.feature_flag.key,+ experiment.exposure_criteria,+ default_exposure_event=resolve_default_exposure_event(experiment.team, experiment.start_date),+ )+ count += exposure_event == DEFAULT_EXPOSURE_EVENT+ return count++def _experiment_model_to_dto(experiment: ExperimentModel) -> Experiment:"""Convert Django model to DTO."""return Experiment(diff --git a/products/experiments/backend/test/test_facade.py b/products/experiments/backend/test/test_facade.pyindex eca1c5096855..1f11cf5e41e5 100644--- a/products/experiments/backend/test/test_facade.py+++ b/products/experiments/backend/test/test_facade.py@@ -3,10 +3,21 @@from datetime import UTC, datetimeimport time_machine-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, BaseTest-from products.experiments.backend.facade import create_experiment+from parameterized import parameterized++from posthog.models.organization import Organization+from posthog.models.team import Team++from products.experiments.backend.facade import count_running_experiments_on_feature_flag_called, create_experimentfrom products.experiments.backend.facade.contracts import CreateExperimentInput+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag++PAGEVIEW_EXPOSURE = {+ "exposure_config": {"kind": "ExperimentEventExposureConfig", "event": "$pageview", "properties": []}+}class TestCreateExperiment(APIBaseTest):@@ -128,3 +139,55 @@ class TestCreateExperiment(APIBaseTest):assert result.name == "Comprehensive Test"assert result.description == "Full feature test"+++class TestCountRunningExperimentsOnFeatureFlagCalled(BaseTest):+ @parameterized.expand(+ [+ ("running_on_the_default_exposure", {}, datetime(2026, 8, 1, tzinfo=UTC), None, False, False, False, 1),+ (+ "custom_exposure_event",+ PAGEVIEW_EXPOSURE,+ datetime(2026, 8, 1, tzinfo=UTC),+ None,+ False,+ False,+ False,+ 0,+ ),+ ("draft", {}, None, None, False, False, False, 0),+ ("ended", {}, datetime(2026, 8, 1, tzinfo=UTC), datetime(2026, 8, 20, tzinfo=UTC), False, False, False, 0),+ ("archived", {}, datetime(2026, 8, 1, tzinfo=UTC), None, True, False, False, 0),+ ("deleted", {}, datetime(2026, 8, 1, tzinfo=UTC), None, False, True, False, 0),+ ("another_organization", {}, datetime(2026, 8, 1, tzinfo=UTC), None, False, False, True, 0),+ ]+ )+ def test_counts_only_running_experiments_that_count_exposures_on_feature_flag_called(+ self,+ _name: str,+ exposure_criteria: dict,+ start_date: datetime | None,+ end_date: datetime | None,+ archived: bool,+ deleted: bool,+ other_organization: bool,+ expected: int,+ ) -> None:+ team = (+ Team.objects.create(organization=Organization.objects.create(name="Other"), name="Other")+ if other_organization+ else self.team+ )+ flag = FeatureFlag.objects.create(team=team, key="experiment-flag", created_by=self.user)+ Experiment.objects.create(+ team=team,+ name="Experiment",+ feature_flag=flag,+ exposure_criteria=exposure_criteria,+ start_date=start_date,+ end_date=end_date,+ archived=archived,+ deleted=deleted,+ )++ assert count_running_experiments_on_feature_flag_called(self.organization.id) == expecteddiff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.pyindex affb04ee1ade..ae5a938b8a37 100644--- a/products/feature_flags/backend/api/staff_team_config.py+++ b/products/feature_flags/backend/api/staff_team_config.py@@ -111,9 +111,9 @@ 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 and 2 read flag_evaluations. 2 is reserved for "- "ingestion to stop writing $feature_flag_called to events. Ingestion ignores 2 until that support "- "deploys, so 2 acts as 1 until then. This is the stored mode: while the "+ "an organization shares one mode. 0 reads events, 1 and 2 read flag_evaluations. 2 also stops "+ "ingestion 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."),@@ -172,9 +172,8 @@ 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, 2 also stops writing "- "$feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts "- "as 1 until then."+ "Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops ingestion "+ "writing $feature_flag_called to events for the teams it writes to flag_evaluations."),)team_ids = serializers.ListField(@@ -213,6 +212,9 @@ class StaffOrganizationModeChangeSerializer(DataclassSerializer):"organization_id": {"help_text": "Organization id."},"organization_name": {"help_text": "Organization name."},"team_count": {"help_text": "Teams of the organization. They all read the organization's mode."},+ "running_experiments_on_feature_flag_called": {+ "help_text": "Running experiments of the organization that count exposures on $feature_flag_called. On teams in the ingestion allowlist, mode 2 stops those exposures."+ },"changed": {"help_text": "True when the write moved the organization to the target mode, or would on a dry run."},diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.pyindex f80b39b2cdc7..62e93e8bf249 100644--- a/products/feature_flags/backend/facade/enums.py+++ b/products/feature_flags/backend/facade/enums.py@@ -4,10 +4,10 @@ from posthog.enums import LabeledIntEnumclass FlagEvaluationsMode(LabeledIntEnum):- """Which table the product reads an organization's $feature_flag_called data from. This field does not- control ingestion. The INGESTION_FLAG_EVALUATIONS_TEAMS allowlist in FlagEvaluationsService- decides which teams ingestion also writes to flag_evaluations. FLAG_EVALUATIONS_ONLY is- reserved for the ingestion change that stops the events writes.+ """Which table the product reads an organization's $feature_flag_called data from. The+ INGESTION_FLAG_EVALUATIONS_TEAMS allowlist in FlagEvaluationsService decides which teams ingestion+ writes to flag_evaluations. FLAG_EVALUATIONS_ONLY also stops the events writes for the teams that+ allowlist includes."""# The Usage tab reads the events table. The flag_evaluations HogQL table stays hidden unless@@ -16,5 +16,7 @@ class FlagEvaluationsMode(LabeledIntEnum):# 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. Some readers- # stay on events in READ_FLAG_EVALUATIONS and read flag_evaluations only in this mode.+ # stay on events in READ_FLAG_EVALUATIONS and read flag_evaluations only in this mode. 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/flag_evaluations_mode.py b/products/feature_flags/backend/flag_evaluations_mode.pyindex 079185cb6e68..e2851dff3178 100644--- a/products/feature_flags/backend/flag_evaluations_mode.py+++ b/products/feature_flags/backend/flag_evaluations_mode.py@@ -10,6 +10,7 @@ from django.db.models import QuerySetfrom posthog.dataclasses import frozenfrom posthog.models import Organization, Team+from products.experiments.backend.facade import count_running_experiments_on_feature_flag_calledfrom 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@@ -22,6 +23,9 @@ class OrganizationModeChange:organization_created_at: datetime# Teams of the organization, for display only. The write never touches team rows.team_count: int+ # On FLAG_EVALUATIONS_ONLY these experiments stop gaining exposures for teams in the ingestion+ # allowlist, because ingestion stops writing $feature_flag_called to events for those teams.+ running_experiments_on_feature_flag_called: intcurrent_mode: inttarget_mode: int# True when the write moved the organization to target_mode, or would on a dry run.@@ -91,9 +95,9 @@ def set_organization_flag_evaluations_mode() -> OrganizationModeChange:"""Move the organization to `mode`.- An organization above `mode` stays where it is unless `allow_downgrade` is set. Once ingestion- supports FLAG_EVALUATIONS_ONLY, lowering an organization from it restarts events writes and- leaves a gap in the events table.+ An organization above `mode` stays where it is unless `allow_downgrade` is set. Lowering an+ organization from FLAG_EVALUATIONS_ONLY restarts events writes and leaves a gap in the events+ table.Opens no transaction. A caller that writes several organizations wraps its own loop."""@@ -108,6 +112,7 @@ def set_organization_flag_evaluations_mode(organization_name=organization.name,organization_created_at=organization.created_at,team_count=Team.objects.filter(organization_id=organization.id).count(),+ running_experiments_on_feature_flag_called=count_running_experiments_on_feature_flag_called(organization.id),current_mode=current_mode,target_mode=mode,changed=changed,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 e16403ee61a7..8fa5a81d333b 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@@ -92,6 +92,7 @@ class Command(BaseCommand):self.stdout.write(f"{verb} mode {mode.value} ({mode.label}) on {len(organizations)} organization(s).")changed_count = 0left_above_count = 0+ stopped_experiments_count = 0with transaction.atomic():for organization in organizations:change = set_organization_flag_evaluations_mode(@@ -99,6 +100,8 @@ class Command(BaseCommand):)changed_count += change.changedleft_above_count += change.left_above_mode+ if change.changed and mode == FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY:+ stopped_experiments_count += change.running_experiments_on_feature_flag_calledoutcome = (f"mode {change.current_mode} -> {change.target_mode}"if change.changed@@ -106,7 +109,8 @@ class Command(BaseCommand):)self.stdout.write(f" organization {change.organization_id} (created {change.organization_created_at:%Y-%m-%d}, "- f"{change.team_count} team(s)): {outcome}"+ f"{change.team_count} team(s), "+ f"{change.running_experiments_on_feature_flag_called} experiment(s) on $feature_flag_called): {outcome}")self.stdout.write(f"{verb} mode {mode.value} on {changed_count} organization(s).")@@ -115,3 +119,8 @@ class Command(BaseCommand):f"Left {left_above_count} organization(s) above mode {mode.value}. ""Pass --allow-downgrade to lower them.")+ if stopped_experiments_count:+ self.stdout.write(+ f"{stopped_experiments_count} running experiment(s) count exposures on $feature_flag_called. "+ "On teams in the ingestion allowlist, those exposures stop on this mode."+ )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 b49c2ea8da1f..75a1751ccaed 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@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom io import StringIOfrom typing import Any@@ -15,12 +15,14 @@ from parameterized import parameterizedfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.organization import Organization+from products.experiments.backend.models.experiment import Experimentfrom 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 (OrganizationModeChange,set_organization_flag_evaluations_mode,)+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig@@ -59,6 +61,22 @@ class TestSetFlagEvaluationsMode(BaseTest):self.assertIn("Would set mode 1 on 1 organization(s).", output)self.assertIsNone(self._stored_mode(self.organization))+ @parameterized.expand([("flag_evaluations_only", "2", True), ("read_flag_evaluations", "1", False)])+ def test_warns_only_when_the_mode_stops_experiments_on_feature_flag_called(+ self, _name: str, mode: str, expects_warning: bool+ ) -> None:+ Experiment.objects.create(+ team=self.team,+ name="Started before the cutoff",+ feature_flag=FeatureFlag.objects.create(team=self.team, key="experiment-flag", created_by=self.user),+ start_date=datetime(2026, 8, 1, tzinfo=UTC),+ )++ output = self._run("--mode", mode, "--organization-id", str(self.organization.id), "--dry-run")++ self.assertIn("1 experiment(s) on $feature_flag_called", output)+ self.assertEqual("1 running experiment(s) count exposures on $feature_flag_called" in output, expects_warning)+@time_machine.travel("2026-09-01T12:00:00Z", tick=False)def test_created_after_selects_only_newer_organizations(self) -> None:cutoff = timezone.now() - timedelta(minutes=5)diff --git a/products/feature_flags/backend/test/test_staff_team_config_api.py b/products/feature_flags/backend/test/test_staff_team_config_api.pyindex c2a1ff09c743..aaf3043548fc 100644--- a/products/feature_flags/backend/test/test_staff_team_config_api.py+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py@@ -1,3 +1,4 @@+from datetime import UTC, datetimefrom uuid import UUIDfrom posthog.test.base import APIBaseTest@@ -12,6 +13,7 @@ from posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.team.extensions import get_or_create_team_extension+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend import flag_evaluations_modefrom products.feature_flags.backend.api.staff_team_config import (MAX_IDS_PER_MODE_WRITE,@@ -414,6 +416,12 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):above_organization = Organization.objects.create(name="Above")above_team = Team.objects.create(organization=above_organization, name="Above team")self._store_mode(above_organization, FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)+ Experiment.objects.create(+ team=sibling,+ name="Started before the cutoff",+ feature_flag=FeatureFlag.objects.create(team=sibling, key="experiment-flag", created_by=self.user),+ start_date=datetime(2026, 8, 1, tzinfo=UTC),+ )response = self.client.post(SET_FLAG_EVALUATIONS_MODE_URL,@@ -438,6 +446,7 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):"organization_id": str(self.organization.id),"organization_name": self.organization.name,"team_count": 3,+ "running_experiments_on_feature_flag_called": 1,"current_mode": FlagEvaluationsMode.EVENTS,"target_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,"changed": expected_changed[0],@@ -447,6 +456,7 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):"organization_id": str(above_organization.id),"organization_name": above_organization.name,"team_count": 1,+ "running_experiments_on_feature_flag_called": 0,"current_mode": FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,"target_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,"changed": expected_changed[1],diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex ceb7bdb81f13..6006e8111d87 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 and 2 read flag_evaluations. 2 is reserved for ingestion to stop writing $feature_flag_called to events. Ingestion ignores 2 until that support deploys, so 2 acts as 1 until then. 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 and 2 read flag_evaluations. 2 also stops ingestion 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.** * `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, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.+ /** Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops ingestion writing $feature_flag_called to events for the teams it writes to flag_evaluations.** * `0` - Events* * `1` - Read flag evaluations@@ -281,6 +281,8 @@ export interface StaffOrganizationModeChangeApi {organization_name: string/** Teams of the organization. They all read the organization's mode. */team_count: number+ /** Running experiments of the organization that count exposures on $feature_flag_called. On teams in the ingestion allowlist, mode 2 stops those exposures. */+ running_experiments_on_feature_flag_called: number/** True when the write moved the organization to the target mode, or would on a dry run. */changed: boolean/** True when the organization is above the target mode and stays there, because allow_downgrade is not set. */diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex d871b32c8a9a..627a5c35e551 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, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.\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, 2 also 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'),team_ids: zod.array(zod.number())diff --git a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsxindex 0914b01d009a..71a365b4932c 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 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.',+ 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. For teams in the ingestion allowlist, ingestion also stops writing $feature_flag_called to the events table.',}export function StaffFlagEvaluationsModeModal(): JSX.Element {@@ -43,6 +43,7 @@ export function StaffFlagEvaluationsModeModal(): JSX.Element {const columns: LemonTableColumns<StaffOrganizationModeChangeApi> = [{ title: 'Organization', dataIndex: 'organization_name' },{ title: 'Teams', dataIndex: 'team_count' },+ { title: 'Experiments on $feature_flag_called', dataIndex: 'running_experiments_on_feature_flag_called' },{title: 'Current mode',key: 'current_mode',@@ -116,8 +117,9 @@ export function StaffFlagEvaluationsModeModal(): JSX.Element {{mode === FlagEvaluationsModeEnumApi.Number2 && (<LemonBanner type="warning">- Ingestion doesn't act on this mode yet, so it still writes $feature_flag_called to the events- table for organizations on it. Once ingestion supports this mode, it stops those writes.+ For teams in the ingestion allowlist, ingestion writes $feature_flag_called only to+ flag_evaluations, so a failed write there loses the event. Other teams still write to the events+ table, and so does every team while INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED is on.</LemonBanner>)}@@ -147,6 +149,22 @@ export function StaffFlagEvaluationsModeModal(): JSX.Element {columns={columns}rowKey="organization_id"/>+ {summary.experimentsLosingExposures > 0 && (+ <LemonBanner type="warning">+ These organizations run {pluralize(summary.experimentsLosingExposures, 'experiment')}{' '}+ whose exposures come from $feature_flag_called. On teams in the ingestion allowlist,+ those exposures stop once the organization moves to{' '}+ {FLAG_EVALUATIONS_MODE_LABELS[FlagEvaluationsModeEnumApi.Number2]}.+ </LemonBanner>+ )}+ {summary.organizationsLoweredFromFlagEvaluationsOnly > 0 && (+ <LemonBanner type="warning">+ Lowering{' '}+ {pluralize(summary.organizationsLoweredFromFlagEvaluationsOnly, 'organization')} from{' '}+ {FLAG_EVALUATIONS_MODE_LABELS[FlagEvaluationsModeEnumApi.Number2]} restarts any events+ writes ingestion stopped for them, but the events table keeps a gap for that time.+ </LemonBanner>+ )}{summary.organizationsLeftAboveMode > 0 && (<p className="text-secondary mb-0">{pluralize(summary.organizationsLeftAboveMode, 'organization')} above this mode willdiff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.tsindex 3b1bc3102e86..b1314c1da294 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts@@ -480,20 +480,23 @@ describe('featureFlagsStaffToolsLogic', () => {it('previews the request as a dry run, then applies the same request', async () => {const bodies: StaffFlagEvaluationsModeMutationApi[] = []- // Three organizations move, one stays above the mode, and one is already on it. A summary- // that reads the wrong field, or counts every unchanged organization as left above, fails.+ // Four organizations move, one of them down from mode 2. One stays above the mode on mode 2,+ // and one is already on it. A summary that reads the wrong field, or counts every unchanged+ // organization as left above or lowered, or counts an unchanged organization's experiments, fails.const organizations: StaffOrganizationModeChangeApi[] = ([- [0, true, false],- [0, true, false],- [0, true, false],- [2, false, true],- [1, false, false],+ [0, true, false, 2],+ [0, true, false, 0],+ [0, true, false, 0],+ [2, true, false, 0],+ [2, false, true, 3],+ [1, false, false, 0],] as const- ).map(([currentMode, changed, leftAboveMode], index) => ({+ ).map(([currentMode, changed, leftAboveMode, experimentsOnFlagCalled], index) => ({organization_id: `org-${index}`,organization_name: `Org ${index}`,team_count: 2,+ running_experiments_on_feature_flag_called: experimentsOnFlagCalled,current_mode: currentMode,target_mode: 1,changed,@@ -504,7 +507,10 @@ describe('featureFlagsStaffToolsLogic', () => {[MODE_URL]: async ({ request }: { request: Request }) => {const body: StaffFlagEvaluationsModeMutationApi = await request.json()bodies.push(body)- return [200, { flag_evaluations_mode: 1, dry_run: body.dry_run, organizations }]+ return [+ 200,+ { flag_evaluations_mode: body.flag_evaluations_mode, dry_run: body.dry_run, organizations },+ ]},},})@@ -516,14 +522,18 @@ describe('featureFlagsStaffToolsLogic', () => {logic.actions.openFlagEvaluationsModeModal()await expectLogic(logic).toDispatchActions(['loadFlagEvaluationsModePreviewSuccess'])+ // Only a move to mode 2 stops these experiments, so the mode 1 preview warns about none.+ expect(logic.values.flagEvaluationsModePreviewSummary?.experimentsLosingExposures).toBe(0)logic.actions.setFlagEvaluationsModeRequest({ mode: 2 })// A preview of the previous request must not stay on screen next to an Apply button// that sends the new one.expect(logic.values.flagEvaluationsModePreview).toBeNull()await expectLogic(logic).toDispatchActions(['loadFlagEvaluationsModePreviewSuccess'])expect(logic.values.flagEvaluationsModePreviewSummary).toMatchObject({- organizationsChanged: 3,+ organizationsChanged: 4,organizationsLeftAboveMode: 1,+ organizationsLoweredFromFlagEvaluationsOnly: 1,+ experimentsLosingExposures: 2,})// A selection change after the preview must not widen the write past what the preview showed.diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.tsindex 8230e64e0362..21ec9bb812ae 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts@@ -18,9 +18,9 @@ import {featureFlagsStaffCacheWarmRunRetrieve,featureFlagsStaffTeamsList,} from '../generated/api'+import { FlagEvaluationsModeEnumApi } from '../generated/api.schemas'import type {FeatureFlagsStaffCacheEntryRetrieveCache,- FlagEvaluationsModeEnumApi,StaffCacheEntryResponseApi,StaffCacheKindEnumApi,StaffCacheMutationResponseApi,@@ -69,6 +69,8 @@ export interface FlagEvaluationsModePreviewSummary {organizations: StaffOrganizationModeChangeApi[]organizationsChanged: numberorganizationsLeftAboveMode: number+ organizationsLoweredFromFlagEvaluationsOnly: number+ experimentsLosingExposures: number}const DEFAULT_FLAG_EVALUATIONS_MODE_REQUEST: FlagEvaluationsModeRequest = {@@ -664,6 +666,20 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(organizationsLeftAboveMode: preview.response.organizations.filter((organization) => organization.left_above_mode).length,+ organizationsLoweredFromFlagEvaluationsOnly: preview.response.organizations.filter(+ (organization) =>+ organization.changed && organization.current_mode === FlagEvaluationsModeEnumApi.Number2+ ).length,+ experimentsLosingExposures:+ preview.response.flag_evaluations_mode === FlagEvaluationsModeEnumApi.Number2+ ? preview.response.organizations+ .filter((organization) => organization.changed)+ .reduce(+ (total, organization) =>+ total + organization.running_experiments_on_feature_flag_called,+ 0+ )+ : 0,},],}),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8cf0af7eba18..31c210d14587 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -100060,7 +100060,7 @@ export namespace Schemas {}export interface StaffFlagEvaluationsModeMutation {- /** Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.+ /** Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops ingestion writing $feature_flag_called to events for the teams it writes to flag_evaluations.** * `0` - Events* * `1` - Read flag evaluations@@ -100097,6 +100097,8 @@ export namespace Schemas {organization_name: string;/** Teams of the organization. They all read the organization's mode. */team_count: number;+ /** Running experiments of the organization that count exposures on $feature_flag_called. On teams in the ingestion allowlist, mode 2 stops those exposures. */+ running_experiments_on_feature_flag_called: number;/** True when the write moved the organization to the target mode, or would on a dry run. */changed: boolean;/** True when the organization is above the target mode and stays there, because allow_downgrade is not set. */@@ -100140,7 +100142,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 and 2 read flag_evaluations. 2 is reserved for ingestion to stop writing $feature_flag_called to events. Ingestion ignores 2 until that support deploys, so 2 acts as 1 until then. 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 and 2 read flag_evaluations. 2 also stops ingestion 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.** * `0` - Events* * `1` - Read flag evaluations