: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): shadow-route $feature_flag_called into flag_evaluations (#86291)
Phil Haack9c095aaf9e9c
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex f7440166ff6c..b42edb374310 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -67,6 +67,8 @@ export const KAFKA_PERFORMANCE_EVENTS = `${prefix}clickhouse_performance_events$export const KAFKA_CLICKHOUSE_HEATMAP_EVENTS = `${prefix}clickhouse_heatmap_events${suffix}`// write AI events to ClickHouseexport const KAFKA_CLICKHOUSE_AI_EVENTS_JSON = `${prefix}clickhouse_ai_events_json${suffix}`+// write flag evaluations ($feature_flag_called telemetry) to ClickHouse+export const KAFKA_CLICKHOUSE_FLAG_EVALUATIONS = `${prefix}clickhouse_flag_evaluations${suffix}`// log entries for ingestion into ClickHouseexport const KAFKA_LOG_ENTRIES = `${prefix}log_entries${suffix}`diff --git a/nodejs/src/common/outputs/index.ts b/nodejs/src/common/outputs/index.tsindex e6e46d30421d..31bbdf7af718 100644--- a/nodejs/src/common/outputs/index.ts+++ b/nodejs/src/common/outputs/index.ts@@ -8,6 +8,9 @@ export type EventOutput = typeof EVENTS_OUTPUTexport const AI_EVENTS_OUTPUT = 'ai_events' as constexport type AiEventOutput = typeof AI_EVENTS_OUTPUT+export const FLAG_EVALUATIONS_OUTPUT = 'flag_evaluations' as const+export type FlagEvaluationsOutput = typeof FLAG_EVALUATIONS_OUTPUT+export const ASYNC_OUTPUT = 'async' as constexport type AsyncOutput = typeof ASYNC_OUTPUTdiff --git a/nodejs/src/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service.ts b/nodejs/src/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service.tsindex be43683672e3..e17ade21f993 100644--- a/nodejs/src/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service.ts+++ b/nodejs/src/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service.ts@@ -4,8 +4,9 @@ import { Redis } from 'ioredis'import { timeoutGuard } from '~/common/utils/db/utils'import { parseTeamsList } from '~/common/utils/env-utils'import { logger } from '~/common/utils/logger'+import { buildTeamGate } from '~/ingestion/common/team-gate'import { IngestionConsumerConfig, IngestionLane, REALTIME_INGESTION_LANES } from '~/ingestion/config'-import { RedisPool } from '~/types'+import { RedisPool, ValueMatcher } from '~/types'import { featureFlagCalledDedupRedisLatency, featureFlagCalledDedupRedisOpsTotal } from './metrics'@@ -48,8 +49,7 @@ export function parseFeatureFlagCalledDedupConfig(}const excluded = parseTeamsList(excludedTeams)if (excluded === '*') {- // An operator reaching for '*' as an exclude-everyone switch means "off";- // the escape hatch on a data-dropping feature must not fail toward dropping.+ // The escape hatch on a data-dropping feature must not fail toward dropping.logger.warn('INGESTION_FEATURE_FLAG_CALLED_DEDUP_EXCLUDED_TEAMS is "*", disabling dedup')parsedMode = 'disabled'}@@ -207,14 +207,12 @@ export function createFeatureFlagCalledDedupService(export class RedisFeatureFlagCalledDedupService implements FeatureFlagCalledDedupService {private redisPool: RedisPoolprivate config: FeatureFlagCalledDedupConfig- private teams: Set<number> | '*'- private excludedTeams: Set<number>+ private isEnabled: ValueMatcher<number>constructor(options: RedisFeatureFlagCalledDedupServiceOptions) {this.redisPool = options.redisPoolthis.config = options.config- this.teams = options.config.teams === '*' ? '*' : new Set(options.config.teams)- this.excludedTeams = new Set(options.config.excludedTeams)+ this.isEnabled = buildTeamGate(options.config.teams, options.config.excludedTeams)}get mode(): FeatureFlagCalledDedupMode {@@ -222,10 +220,7 @@ export class RedisFeatureFlagCalledDedupService implements FeatureFlagCalledDedu}isEnabledForTeam(teamId: number): boolean {- if (this.excludedTeams.has(teamId)) {- return false- }- return this.teams === '*' || this.teams.has(teamId)+ return this.isEnabled(teamId)}async claimKeys(claims: FeatureFlagCalledDedupClaim[]): Promise<boolean[]> {diff --git a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.test.ts b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.test.tsnew file mode 100644index 000000000000..22e6a410af6f--- /dev/null+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.test.ts@@ -0,0 +1,65 @@+import { DateTime } from 'luxon'++import { parseJSON } from '~/common/utils/json-parse'+import { serializeEvent } from '~/ingestion/common/steps/event-processing/emit-event-step'+import { ISOTimestamp, ProcessedEvent, ProjectId } from '~/types'++import { mapProcessedEventToFlagEvaluationRow } from './flag-evaluation-row'++describe('mapProcessedEventToFlagEvaluationRow', () => {+ const processedEvent: ProcessedEvent = {+ uuid: 'event-uuid-1',+ event: '$feature_flag_called',+ properties: { $feature_flag: 'my-flag', $feature_flag_response: true, $group_0: 'org-1' },+ timestamp: '2024-01-15T10:30:00.123Z' as ISOTimestamp,+ team_id: 42,+ project_id: 7 as ProjectId,+ distinct_id: 'distinct-1',+ elements_chain: '',+ created_at: DateTime.fromISO('2024-01-15T10:31:00.456Z'),+ captured_at: null,+ person_id: 'person-uuid-1',+ person_properties: { email: '[email protected]' },+ person_created_at: DateTime.fromISO('2023-01-01T00:00:00.000Z'),+ person_mode: 'full',+ }++ it('narrows the events wire format to the flag_evaluations columns, byte-identical on shared fields', () => {+ const row = mapProcessedEventToFlagEvaluationRow(processedEvent)+ const eventsRow = serializeEvent(processedEvent)++ expect(row.uuid).toBe('event-uuid-1')+ expect(row.event).toBe('$feature_flag_called')+ expect(row.team_id).toBe(42)+ expect(row.distinct_id).toBe('distinct-1')+ expect(row.person_id).toBe('person-uuid-1')+ expect(row.timestamp).toBe('2024-01-15 10:30:00.123')+ expect(row.properties).toBe(eventsRow.properties)+ expect(row.person_properties).toBe(eventsRow.person_properties)+ // Both rows derive created_at from the event, so they agree. Reading the+ // wall clock per serialization instead would stamp two different values.+ expect(row.created_at).toBe(eventsRow.created_at)+ expect(row.created_at).toBe('2024-01-15 10:31:00.456')+ expect(parseJSON(row.properties!).$feature_flag).toBe('my-flag')+ expect(parseJSON(row.person_properties!).email).toBe('[email protected]')+ })++ it('emits exactly the kafka_flag_evaluations column set', () => {+ // An extra key (elements_chain, person_mode, a materialized column name)+ // is not a column on the Kafka table; keep the wire format in lockstep+ // with posthog/models/flag_evaluations/sql.py.+ const row = mapProcessedEventToFlagEvaluationRow(processedEvent)++ expect(Object.keys(row).sort()).toEqual([+ 'created_at',+ 'distinct_id',+ 'event',+ 'person_id',+ 'person_properties',+ 'properties',+ 'team_id',+ 'timestamp',+ 'uuid',+ ])+ })+})diff --git a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.ts b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.tsnew file mode 100644index 000000000000..9a123db7726f--- /dev/null+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluation-row.ts@@ -0,0 +1,51 @@+import { serializeEvent } from '~/ingestion/common/steps/event-processing/emit-event-step'+import { ProcessedEvent, RawKafkaEvent } from '~/types'++/**+ * One row for the kafka_flag_evaluations ClickHouse table (JSONEachRow).+ * Keep in sync with posthog/models/flag_evaluations/sql.py.+ *+ * The table mirrors the events schema, so the row is the events wire format+ * narrowed to exactly the columns the Kafka engine table declares. Going+ * through serializeEvent keeps every shared field byte-identical to what the+ * events table receives for the same event, rather than a second hand-rolled+ * mapping that could drift from it.+ *+ * Deliberately not sent:+ * - `inserted_at`: omitted keys zero-fill in ClickHouse, and the MV treats the+ * epoch sentinel as "absent" and stamps the Kafka message timestamp instead.+ * - `group0..group4_properties`: the events producer does not send them either+ * (they are not in RawKafkaEvent); they zero-fill empty in both tables.+ * - `flag_key`, `response`, `session_id`, `request_id`, `$group_0..4`: the Kafka+ * table does not declare these, and the shard computes them from `properties`+ * as DEFAULT columns. A DEFAULT only fills when the insert omits the column,+ * so naming one here would store the sent value even where it contradicts+ * `properties`. This row type must never grow them.+ */+export type FlagEvaluationRow = Pick<+ RawKafkaEvent,+ | 'uuid'+ | 'event'+ | 'properties'+ | 'timestamp'+ | 'team_id'+ | 'distinct_id'+ | 'created_at'+ | 'person_id'+ | 'person_properties'+>++export function mapProcessedEventToFlagEvaluationRow(event: ProcessedEvent): FlagEvaluationRow {+ const serialized = serializeEvent(event)+ return {+ uuid: serialized.uuid,+ event: serialized.event,+ properties: serialized.properties,+ timestamp: serialized.timestamp,+ team_id: serialized.team_id,+ distinct_id: serialized.distinct_id,+ created_at: serialized.created_at,+ person_id: serialized.person_id,+ person_properties: serialized.person_properties,+ }+}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.tsnew file mode 100644index 000000000000..8f75c7e31d6d--- /dev/null+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.test.ts@@ -0,0 +1,55 @@+import { IngestionLane } from '~/ingestion/config'++import { FlagEvaluationsEnvConfig, createFlagEvaluationsService } from './flag-evaluations-service'++describe('FlagEvaluationsService', () => {+ const envConfig = (+ mode: string,+ teams = '*',+ excludedTeams = '',+ topic = 'clickhouse_flag_evaluations',+ lane: IngestionLane | null = 'main'+ ): FlagEvaluationsEnvConfig => ({+ INGESTION_LANE: lane,+ INGESTION_FLAG_EVALUATIONS_MODE: mode,+ INGESTION_FLAG_EVALUATIONS_TEAMS: teams,+ INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: excludedTeams,+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: topic,+ })++ describe('createFlagEvaluationsService', () => {+ // The wildcard-exclusion case is the escape hatch: it must fail toward the+ // events table, not toward excluding everyone from being excluded. The+ // empty-topic case guards the fork from producing into a nameless topic.+ it.each([+ ['mode is disabled', envConfig('disabled'), false],+ ['mode is invalid', envConfig('garbage'), false],+ ['the output topic is empty', envConfig('dual_write', '*', '', ''), false],+ ['excluded teams is the wildcard', envConfig('dual_write', '*', '*'), false],+ ['mode is dual_write', envConfig('dual_write'), true],+ // The backfill owns history, so a delayed lane must never fork even+ // when the env vars say dual_write.+ ['the lane is historical', envConfig('dual_write', '*', '', 'topic', 'historical'), false],+ ['the lane is async', envConfig('dual_write', '*', '', 'topic', 'async'), false],+ ['the lane is overflow', envConfig('dual_write', '*', '', 'topic', 'overflow'), true],+ ['no lane is set (local dev)', envConfig('dual_write', '*', '', 'topic', null), true],+ ['the teams allowlist is empty', envConfig('dual_write', ''), false],+ ])('builds a service when %s -> %s', (_name, config, expected) => {+ expect(createFlagEvaluationsService(config) !== undefined).toBe(expected)+ })+ })++ describe('isEnabledForTeam', () => {+ it.each([+ ['*', '', 5, true],+ ['*', '5', 5, false],+ ['1,2', '', 2, true],+ ['1,2', '', 3, false],+ ['1,2', '2', 2, false],+ ])('teams=%s excluded=%s team=%i -> %s', (teams, excluded, teamId, expected) => {+ const service = createFlagEvaluationsService(envConfig('dual_write', teams, excluded))++ expect(service?.isEnabledForTeam(teamId)).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.tsnew file mode 100644index 000000000000..24158854f487--- /dev/null+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts@@ -0,0 +1,108 @@+import { parseTeamsList } from '~/common/utils/env-utils'+import { logger } from '~/common/utils/logger'+import { buildTeamGate } from '~/ingestion/common/team-gate'+import {+ IngestionConsumerConfig,+ IngestionLane,+ IngestionOutputsConfig,+ REALTIME_INGESTION_LANES,+} from '~/ingestion/config'+import { 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[]+}++/**+ * 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.+ *+ * The shadow write is never load-bearing for an individual 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.+ *+ * Shedding that dependency during an incident takes BOTH env vars, not just the+ * mode: the mode stops a running consumer from forking, but startup topic+ * verification is driven by the output registration, which the mode does not+ * touch. A pod that restarts with INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC still+ * set fails to start at all while the topic is unreachable. Clear the topic too.+ */+export class FlagEvaluationsService {+ private isEnabled: ValueMatcher<number>++ constructor(config: FlagEvaluationsConfig) {+ this.isEnabled = buildTeamGate(config.teams, config.excludedTeams)+ }++ isEnabledForTeam(teamId: number): boolean {+ return this.isEnabled(teamId)+ }+}++export type FlagEvaluationsEnvConfig = Pick<+ IngestionConsumerConfig,+ | 'INGESTION_LANE'+ | 'INGESTION_FLAG_EVALUATIONS_MODE'+ | 'INGESTION_FLAG_EVALUATIONS_TEAMS'+ | 'INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS'+> &+ Pick<IngestionOutputsConfig, 'INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC'>++/**+ * Lanes that may fork: the real-time lanes plus `null` for local dev, where no+ * lane is set. Derived from REALTIME_INGESTION_LANES so a new real-time lane is+ * covered automatically; delayed lanes are excluded by construction.+ *+ * The backfill owns history for this table, so a delayed lane that also forked+ * would write rows the backfill already covers, double-counting the per-flag+ * usage the table exists to answer. The gate holds even if the env vars leak+ * into a config shared across lanes.+ */+const FLAG_EVALUATIONS_ALLOWED_LANES: readonly (IngestionLane | null)[] = [...REALTIME_INGESTION_LANES, null]++/**+ * Builds the flag evaluations service, or undefined when the fork is off. The+ * pipeline composes the fork step out entirely when this returns undefined.+ */+export function createFlagEvaluationsService(envConfig: FlagEvaluationsEnvConfig): FlagEvaluationsService | undefined {+ const mode = envConfig.INGESTION_FLAG_EVALUATIONS_MODE+ if (mode !== 'dual_write') {+ if (mode !== 'disabled') {+ logger.warn('Invalid INGESTION_FLAG_EVALUATIONS_MODE, falling back to disabled', { mode })+ }+ return undefined+ }+ if (!envConfig.INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC) {+ // An empty topic also skips the startup topic-existence check, so producing+ // here would fail at runtime instead. See the enable ordering in config.ts.+ logger.warn(+ 'INGESTION_FLAG_EVALUATIONS_MODE is set but INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC is empty, not forking'+ )+ return undefined+ }+ if (!FLAG_EVALUATIONS_ALLOWED_LANES.includes(envConfig.INGESTION_LANE)) {+ logger.warn('Flag evaluations fork is not supported on this ingestion lane, disabling', {+ lane: envConfig.INGESTION_LANE,+ })+ return undefined+ }+ const excludedTeams = parseTeamsList(envConfig.INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS)+ if (excludedTeams === '*') {+ // An operator's '*' exclusion means "off": the escape hatch fails toward not forking.+ logger.warn('INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS is "*", disabling the flag evaluations fork')+ return undefined+ }+ const teams = parseTeamsList(envConfig.INGESTION_FLAG_EVALUATIONS_TEAMS)+ if (teams !== '*' && teams.length === 0) {+ // Same shape as the empty-topic case: an allowlist naming nobody is off, so+ // compose the step out rather than paying it per event to gate every team away.+ logger.warn('INGESTION_FLAG_EVALUATIONS_MODE is set but INGESTION_FLAG_EVALUATIONS_TEAMS is empty, not forking')+ return undefined+ }+ return new FlagEvaluationsService({ teams, excludedTeams })+}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 b00fc3c7132a..f6dd20684ad1 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@@ -253,7 +253,7 @@ describe('create-event-step', () => {if (isOkResult(result)) {const event = result.value.eventsToEmit[0].eventexpect(event.timestamp).toBeTruthy()- expect(event.created_at).toBeNull()+ expect(event.created_at).toBeTruthy()expect(event.person_created_at).toBeTruthy()}})diff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event.tsindex 0524c99b9bce..9bda07434534 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event.ts@@ -1,3 +1,4 @@+import { DateTime } from 'luxon'import { Counter } from 'prom-client'import { MAX_GROUP_TYPES_PER_TEAM } from '~/common/groups/group-type-manager'@@ -98,7 +99,7 @@ export function createEvent(project_id: projectId,distinct_id: distinctId,elements_chain: elementsChain,- created_at: null,+ created_at: DateTime.utc(),captured_at: capturedAt,person_id: personId,person_properties: eventPersonProperties,diff --git a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.test.tsindex 0cba986074cf..416e60175d8d 100644--- a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.test.ts@@ -62,7 +62,7 @@ describe('emit-event-step', () => {project_id: 1 as ProjectId,distinct_id: 'test-distinct-id',elements_chain: '',- created_at: null,+ created_at: DateTime.fromISO('2023-01-01T00:01:00.000Z'),captured_at: null,person_id: 'person-uuid',person_properties: {},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 7011986ba8cb..816a4e61375d 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@@ -138,7 +138,7 @@ export function serializeEvent(event: ProcessedEvent): RawKafkaEvent {project_id: event.project_id,distinct_id: safeClickhouseString(event.distinct_id),elements_chain: safeClickhouseString(event.elements_chain),- created_at: castTimestampOrNow(null, TimestampFormat.ClickHouse),+ created_at: castTimestampOrNow(event.created_at, TimestampFormat.ClickHouse),captured_at:event.captured_at !== null? castTimestampToClickhouseFormat(DateTime.fromJSDate(event.captured_at), TimestampFormat.ClickHouse)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.tsnew file mode 100644index 000000000000..128b36cb5440--- /dev/null+++ b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.test.ts@@ -0,0 +1,266 @@+import { DateTime } from 'luxon'++import { FlagEvaluationsOutput } 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 { EventToEmit } from './emit-event-step'+import {+ ForkFlagEvaluationsStepInput,+ createForkFlagEvaluationsStep,+ flagEvaluationsEventsTotal,+ flagEvaluationsPendingAcks,+ flagEvaluationsSetPropsTotal,+} from './fork-flag-evaluations-step'++// 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 createStep = (service: FlagEvaluationsService) => {+ const outputs = createMockIngestionOutputs<FlagEvaluationsOutput>()+ const step = createForkFlagEvaluationsStep<ForkFlagEvaluationsStepInput>(outputs, service)+ return { step, outputs }+}++const createProcessedEvent = (overrides: Partial<ProcessedEvent> = {}): ProcessedEvent => ({+ uuid: 'event-uuid-1',+ event: '$feature_flag_called',+ properties: { $feature_flag: 'my-flag', $feature_flag_response: true },+ timestamp: '2024-01-15T10:30:00.000Z' as ISOTimestamp,+ team_id: 7,+ project_id: 7 as ProjectId,+ distinct_id: 'distinct-1',+ elements_chain: '',+ created_at: DateTime.fromISO('2024-01-15T10:31:00.000Z'),+ captured_at: null,+ person_id: 'person-uuid-1',+ person_properties: {},+ person_created_at: DateTime.fromISO('2023-01-01T00:00:00.000Z'),+ person_mode: 'full',+ ...overrides,+})++const createInput = (events: ProcessedEvent[] = [createProcessedEvent()]): ForkFlagEvaluationsStepInput => ({+ eventsToEmit: events.map((event): EventToEmit<string> => ({ event, output: 'events' })),+ teamId: 7,+})++describe('createForkFlagEvaluationsStep', () => {+ beforeEach(() => {+ flagEvaluationsEventsTotal.reset()+ flagEvaluationsSetPropsTotal.reset()+ flagEvaluationsPendingAcks.reset()+ })++ it.each([+ {+ name: 'no event is $feature_flag_called',+ buildService: () => enabledService(),+ buildInput: () => createInput([createProcessedEvent({ event: '$pageview' })]),+ },+ {+ name: 'the team is not enabled',+ buildService: () => teamExcludedService(),+ buildInput: () => createInput(),+ },+ ])('passes through without producing when $name', async ({ buildService, buildInput }) => {+ const { step, outputs } = createStep(buildService())+ const input = buildInput()++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value).toBe(input)+ }+ expect(outputs.queueMessages).not.toHaveBeenCalled()+ })++ describe('missing or invalid $feature_flag', () => {+ it.each([+ ['absent', undefined],+ ['a number', 42],+ ['an empty string', ''],+ ['null', null],+ ['an object', { nested: true }],+ ])('passes through without producing when $feature_flag is %s', async (_label, flagKey) => {+ const { step, outputs } = createStep(enabledService())+ const properties: Record<string, unknown> = { $feature_flag_response: true }+ if (flagKey !== undefined) {+ properties.$feature_flag = flagKey+ }+ const input = createInput([createProcessedEvent({ properties })])++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ expect(outputs.queueMessages).not.toHaveBeenCalled()+ })+ })++ describe('happy path', () => {+ it('produces exactly one flag_evaluations message with the narrowed events row', async () => {+ const { step, outputs } = createStep(enabledService())+ const input = createInput([+ createProcessedEvent({+ properties: { $feature_flag: 'my-flag', $feature_flag_response: true, $set: { plan: 'pro' } },+ }),+ ])++ const result = await step(input)++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ // The event continues to the events table untouched, and the ack+ // rides along so the batch's offset commit waits on the produce.+ expect(result.value).toBe(input)+ expect(result.sideEffects).toHaveLength(1)+ await result.sideEffects[0]+ }+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)+ const [outputName, messages] = outputs.queueMessages.mock.calls[0]+ expect(outputName).toBe('flag_evaluations')+ expect(messages).toHaveLength(1)+ expect(messages[0].key).toBe('event-uuid-1')+ expect(messages[0].teamId).toBe(7)++ const row = parseJSON(messages[0].value!.toString())+ expect(row.event).toBe('$feature_flag_called')+ expect(row.team_id).toBe(7)+ expect(row.uuid).toBe('event-uuid-1')+ expect(row.person_id).toBe('person-uuid-1')+ expect(parseJSON(row.properties).$feature_flag).toBe('my-flag')++ // dual_written counts on the ack, not the enqueue, so it is only+ // visible after the side effect above settles.+ expect((await flagEvaluationsEventsTotal.get()).values).toContainEqual(+ expect.objectContaining({ labels: { outcome: 'dual_written' }, value: 1 })+ )+ expect((await flagEvaluationsSetPropsTotal.get()).values).toContainEqual(+ expect.objectContaining({ value: 1 })+ )+ })++ 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])++ await step(input)++ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)+ const [, messages] = outputs.queueMessages.mock.calls[0]+ expect(messages).toHaveLength(1)+ expect(messages[0].key).toBe('event-uuid-1')+ })+ })++ describe('mapping/produce failure isolation', () => {+ it('settles the ack rather than rejecting when the produce fails asynchronously', async () => {+ const { step, outputs } = createStep(enabledService())+ outputs.queueMessages.mockRejectedValue(new Error('produce failed'))+ const input = createInput()++ const result = await step(input)++ // A failed shadow produce must never reach the batch as a rejection.+ // See createForkFlagEvaluationsStep for why.+ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value).toBe(input)+ expect(result.sideEffects).toHaveLength(1)+ await expect(result.sideEffects[0]).resolves.toBeUndefined()+ }+ // A failed produce must never report as dual-written, and must be+ // counted rather than dropped silently.+ expect((await flagEvaluationsEventsTotal.get()).values).not.toContainEqual(+ expect.objectContaining({ labels: { outcome: 'dual_written' } })+ )+ expect((await flagEvaluationsEventsTotal.get()).values).toContainEqual(+ expect.objectContaining({ labels: { outcome: 'produce_failed' }, value: 1 })+ )+ // Settled either way, so the stall gauge must be back to zero.+ expect((await flagEvaluationsPendingAcks.get()).values[0].value).toBe(0)+ })++ it('holds the pending-acks gauge above zero while the ack has not settled', async () => {+ const { step, outputs } = createStep(enabledService())+ let settle: (() => void) | undefined+ outputs.queueMessages.mockReturnValue(+ new Promise<void>((resolve) => {+ settle = resolve+ })+ )++ const result = await step(createInput())++ // This is the stall: the ack is neither resolved nor rejected, so no+ // outcome counter moves and only the gauge shows the fork is holding on.+ expect((await flagEvaluationsPendingAcks.get()).values[0].value).toBe(1)+ expect((await flagEvaluationsEventsTotal.get()).values).toEqual([])++ settle!()+ if (isOkResult(result)) {+ await result.sideEffects[0]+ }+ 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()+ }+ 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())+ outputs.queueMessages.mockImplementation(() => {+ throw new Error('sync produce failure')+ })+ const input = createInput([+ createProcessedEvent({ uuid: 'event-uuid-1' }),+ createProcessedEvent({ uuid: 'event-uuid-2', properties: { $feature_flag_response: true } }),+ ])++ const result = await step(input)++ // The fork must never block the events path: a failure here is+ // swallowed, not surfaced as a DLQ/drop result.+ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value).toBe(input)+ expect(result.sideEffects).toHaveLength(0)+ }+ // One outcome per event: the invalid-key event is already counted, so+ // continued_fork_error covers only the remaining one.+ expect((await flagEvaluationsEventsTotal.get()).values).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ labels: { outcome: 'continued_invalid_flag_key' }, value: 1 }),+ expect.objectContaining({ labels: { outcome: 'continued_fork_error' }, value: 1 }),+ ])+ )+ })+ })+})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.tsnew file mode 100644index 000000000000..c7aaac343960--- /dev/null+++ b/nodejs/src/ingestion/common/steps/event-processing/fork-flag-evaluations-step.ts@@ -0,0 +1,144 @@+import { Counter, Gauge } from 'prom-client'++import { FLAG_EVALUATIONS_OUTPUT, FlagEvaluationsOutput } 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 { ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { EventToEmit } from './emit-event-step'++export const flagEvaluationsEventsTotal = new Counter({+ name: 'ingestion_flag_evaluations_events_total',+ help: '$feature_flag_called events seen by the flag-evaluations fork, by outcome',+ labelNames: ['outcome'],+})++/**+ * Produces queued but not yet acknowledged. The ack rides in the batch's side+ * effects, so an unwritable topic leaves it pending and the consumer stops+ * committing offsets. Neither ack arm has run at that point, so no outcome+ * counter moves and this gauge is the only thing that names the fork as the+ * cause.+ *+ * Once the wait passes CONSUMER_BACKGROUND_TASK_TIMEOUT_MS, v1 logs a timeout+ * warning and keeps waiting, and v2 fails the batch with+ * background_task_timeout_after_<ms>ms. Neither one names the fork.+ */+export const flagEvaluationsPendingAcks = new Gauge({+ name: 'ingestion_flag_evaluations_pending_acks',+ help: 'flag_evaluations produces queued but not yet acknowledged; sustained non-zero means the fork is holding up batches',+})++export const flagEvaluationsSetPropsTotal = new Counter({+ name: 'ingestion_flag_evaluations_set_props_total',+ help: '$feature_flag_called events carrying $set/$set_once, which a dedicated flag lane bypassing person processing would lose',+})++const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'++const isFlagCalledEvent = ({ event }: EventToEmit<string>): boolean => event.event === FEATURE_FLAG_CALLED_EVENT++// flag_key is materialized into the table's sort key, so a row without it is junk.+const hasFlagKey = ({ event }: EventToEmit<string>): boolean => {+ const flagKey = event.properties['$feature_flag']+ return typeof flagKey === 'string' && flagKey !== ''+}++export interface ForkFlagEvaluationsStepInput {+ eventsToEmit: EventToEmit<string>[]+ teamId: number+}++/**+ * 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.+ *+ * Sits between create-event and emit-event, where the fully assembled+ * ProcessedEvent exists: person_id and person_properties from person+ * processing, and final properties (including the $group_N keys the groups+ * step resolves, which the storage table materializes). Matching on the event+ * 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+ * 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>,+ flagEvaluationsService: FlagEvaluationsService+): ProcessingStep<T, T> {+ return function forkFlagEvaluationsStep(input) {+ const flagCalledEvents = input.eventsToEmit.filter(isFlagCalledEvent)+ if (flagCalledEvents.length === 0) {+ return Promise.resolve(ok(input))+ }+ if (!flagEvaluationsService.isEnabledForTeam(input.teamId)) {+ flagEvaluationsEventsTotal.labels('continued_team_not_enabled').inc(flagCalledEvents.length)+ return Promise.resolve(ok(input))+ }+ const mappableEvents = flagCalledEvents.filter(hasFlagKey)+ const invalidFlagKeys = flagCalledEvents.length - mappableEvents.length+ if (invalidFlagKeys > 0) {+ flagEvaluationsEventsTotal.labels('continued_invalid_flag_key').inc(invalidFlagKeys)+ }+ if (mappableEvents.length === 0) {+ return Promise.resolve(ok(input))+ }+ try {+ const messages: IngestionOutputMessage[] = mappableEvents.map(({ event }) => {+ if (event.properties['$set'] || event.properties['$set_once']) {+ // Sizes the person-property loss a dedicated flag lane that+ // bypasses person processing would cause.+ flagEvaluationsSetPropsTotal.inc()+ }+ const row = mapProcessedEventToFlagEvaluationRow(event)+ return { key: row.uuid, value: Buffer.from(JSON.stringify(row)), teamId: row.team_id }+ })+ const 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.+ //+ // 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.+ const settled = ack.then(+ () => {+ flagEvaluationsPendingAcks.dec(messages.length)+ flagEvaluationsEventsTotal.labels('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+ }+ flagEvaluationsEventsTotal.labels('produce_failed').inc(messages.length)+ }+ )+ return Promise.resolve(ok(input, [settled]))+ } catch (error) {+ logger.warn('Failed to fork $feature_flag_called event to flag_evaluations, continuing', {+ teamId: input.teamId,+ error,+ })+ flagEvaluationsEventsTotal.labels('continued_fork_error').inc(mappableEvents.length)+ return Promise.resolve(ok(input))+ }+ }+}diff --git a/nodejs/src/ingestion/common/team-gate.ts b/nodejs/src/ingestion/common/team-gate.tsnew file mode 100644index 000000000000..4747afb53828--- /dev/null+++ b/nodejs/src/ingestion/common/team-gate.ts@@ -0,0 +1,11 @@+import { ValueMatcher } from '~/types'++/**+ * The rollout gate those features share: an allowlist ('*' or explicit team+ * IDs) minus an exclusion list, where exclusion always wins.+ */+export function buildTeamGate(teams: number[] | '*', excludedTeams: number[]): ValueMatcher<number> {+ const allowed = teams === '*' ? '*' : new Set(teams)+ const excluded = new Set(excludedTeams)+ return (teamId) => !excluded.has(teamId) && (allowed === '*' || allowed.has(teamId))+}diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 0d198bef8538..e1d26ec4554a 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -238,6 +238,14 @@ export type IngestionConsumerConfig = {/** Teams whose multivariate $feature_flag_called events are duplicated as $experiment_exposure: '*' for all, '' to disable, or comma-separated team IDs */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) */+ 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+// $feature_flag_called keep-first dedup config/** 'disabled' | 'shadow' (claim + count, never drop) | 'drop' */INGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: string@@ -386,6 +394,18 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: '',+ // $feature_flag_called fork into the flag_evaluations ClickHouse table.+ // Teams default empty so flipping the mode alone forks nobody; ramp by+ // naming teams (or '*') in INGESTION_FLAG_EVALUATIONS_TEAMS.+ //+ // On a split lane the fork runs in the Node processor pool, not in the+ // Rust consumer that dispatches to it, so these belong on the lane's base+ // values.yaml, which both roles inherit. Setting them on the consumer+ // release alone does nothing.+ INGESTION_FLAG_EVALUATIONS_MODE: 'disabled',+ INGESTION_FLAG_EVALUATIONS_TEAMS: '',+ INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: '',+// $feature_flag_called keep-first dedup configINGESTION_FEATURE_FLAG_CALLED_DEDUP_MODE: 'disabled',@@ -456,6 +476,9 @@ export type IngestionOutputsConfig = {INGESTION_OUTPUT_AI_EVENTS_TOPIC: stringINGESTION_OUTPUT_AI_EVENTS_PRODUCER: ProducerName+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: string+ INGESTION_OUTPUT_FLAG_EVALUATIONS_PRODUCER: ProducerName+INGESTION_OUTPUT_HEATMAPS_TOPIC: stringINGESTION_OUTPUT_HEATMAPS_PRODUCER: ProducerName@@ -499,6 +522,14 @@ export function getDefaultIngestionOutputsConfig(): IngestionOutputsConfig {INGESTION_OUTPUT_EVENTS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,INGESTION_OUTPUT_AI_EVENTS_TOPIC: KAFKA_CLICKHOUSE_AI_EVENTS_JSON,INGESTION_OUTPUT_AI_EVENTS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,+ // Empty topic skips the startup topic-existence check, so deploying this dark cannot+ // crash-loop a fleet whose broker lacks the topic. Enable ordering: (1) create the+ // clickhouse_flag_evaluations topic, (2) set INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC+ // (startup topic verification is then fatal by design), (3) set+ // INGESTION_FLAG_EVALUATIONS_MODE. Mode without topic is a no-op; see+ // createFlagEvaluationsService.+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: '',+ INGESTION_OUTPUT_FLAG_EVALUATIONS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,INGESTION_OUTPUT_HEATMAPS_TOPIC: KAFKA_CLICKHOUSE_HEATMAP_EVENTS,INGESTION_OUTPUT_HEATMAPS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC: KAFKA_INGESTION_WARNINGS,diff --git a/nodejs/src/ingestion/framework/pipeline.interface.ts b/nodejs/src/ingestion/framework/pipeline.interface.tsindex ff93929c6190..166b386e4e4b 100644--- a/nodejs/src/ingestion/framework/pipeline.interface.ts+++ b/nodejs/src/ingestion/framework/pipeline.interface.ts@@ -57,6 +57,14 @@ export type PipelineContext<C = { message: Message }> = C & {* `C` narrows the type via its own `debugContext` declaration.*/debugContext?: unknown+ /**+ * Work that outlives the step, drained with the batch. A side effect must+ * not reject. What a rejection does depends on the host: consumer-v2+ * latches a fatal and holds the offset, consumer-v1 stores the offset from+ * a `.finally` and then stops the process on the unhandled rejection,+ * ingestion-api-server stops the pod, and the gRPC driver fails every open+ * stream. Settle the promise inside the step and record the failure there.+ */sideEffects: Promise<unknown>[]warnings: PipelineWarning[]}diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex d5d46309d6e6..a9b9201bde46 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -18,6 +18,7 @@ import {import {AsyncOutput,EventOutput,+ FlagEvaluationsOutput,PersonDistinctIdsOutput,PersonMergeEventsOutput,PersonsOutput,@@ -58,6 +59,10 @@ import {FeatureFlagCalledDedupService,createFeatureFlagCalledDedupService,} from './common/feature-flag-called-dedup/feature-flag-called-dedup-service'+import {+ FlagEvaluationsService,+ createFlagEvaluationsService,+} from './common/flag-evaluations/flag-evaluations-service'import { MainLaneOverflowRedirect } from './common/overflow-redirect/main-lane-overflow-redirect'import { OverflowLaneOverflowRedirect } from './common/overflow-redirect/overflow-lane-overflow-redirect'import { OverflowRedirectService } from './common/overflow-redirect/overflow-redirect-service'@@ -69,8 +74,12 @@ export type IngestionConsumerFullConfig = IngestionConsumerConfig &UsageIngestionConfig &Pick<CommonConfig, 'KAFKA_CLIENT_RACK'> &// The general server builds the consumer from a config that includes IngestionOutputsConfig; the- // merge-events gate reads the topic, so surface it here rather than relying on the runtime shape.- Pick<IngestionOutputsConfig, 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC'>+ // merge-events gate and the flag-evaluations fork read their topics, so surface them here rather+ // than relying on the runtime shape.+ Pick<+ IngestionOutputsConfig,+ 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC' | 'INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC'+ >export interface IngestionConsumerDeps {postgres: PostgresRouter@@ -79,6 +88,7 @@ export interface IngestionConsumerDeps {featureFlagCalledDedupRedisPool?: RedisPooloutputs: IngestionOutputs<| EventOutput+ | FlagEvaluationsOutput| IngestionWarningsOutput| DlqOutput| OverflowOutput@@ -123,6 +133,7 @@ export class IngestionConsumer {private overflowRedirectService?: OverflowRedirectServiceprivate overflowLaneTTLRefreshService?: OverflowRedirectServiceprivate featureFlagCalledDedupService?: FeatureFlagCalledDedupService+ private flagEvaluationsService?: FlagEvaluationsServiceprivate tokenDistinctIdsToDrop: string[] = []private tokenDistinctIdsToSkipPersons: string[] = []private tokenDistinctIdsToForceOverflow: string[] = []@@ -217,6 +228,8 @@ export class IngestionConsumer {this.config)+ this.flagEvaluationsService = createFlagEvaluationsService(this.config)+this.hogTransformer = deps.hogTransformerthis.personsStore = new BatchWritingPersonsStore(this.deps.personRepository, this.deps.outputs, {@@ -314,6 +327,7 @@ export class IngestionConsumer {overflowRedirectService: this.overflowRedirectService,overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,featureFlagCalledDedupService: this.featureFlagCalledDedupService,+ flagEvaluationsService: this.flagEvaluationsService,teamManager: this.deps.teamManager,cookielessManager: this.deps.cookielessManager,groupTypeManager: this.deps.groupTypeManager,diff --git a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.tsindex 14b588baeaa3..8bc6c8d88375 100644--- a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.test.ts@@ -1,3 +1,5 @@+import { DateTime } from 'luxon'+import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT } from '~/common/outputs'import { isOkResult } from '~/ingestion/framework/results'import { ISOTimestamp, ProcessedEvent, ProjectId } from '~/types'@@ -15,7 +17,7 @@ function createProcessedEvent(project_id: 1 as ProjectId,distinct_id: 'user-1',timestamp: '2023-01-01T00:00:00.000Z' as ISOTimestamp,- created_at: null,+ created_at: DateTime.fromISO('2023-01-01T00:01:00.000Z'),captured_at: null,elements_chain: '',person_id: 'person-uuid',diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.tsindex 97b2afd1bc0c..1b4cd4980973 100644--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts@@ -6,12 +6,14 @@ import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { TeamManager } from '~/common/utils/team-manager'+import { FlagEvaluationsService } from '~/ingestion/common/flag-evaluations/flag-evaluations-service'import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'import { WithMergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'+import { createForkFlagEvaluationsStep } from '~/ingestion/common/steps/event-processing/fork-flag-evaluations-step'import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'import { createNormalizeProcessPersonFlagStep } from '~/ingestion/common/steps/event-processing/normalize-process-person-flag-step'@@ -35,6 +37,7 @@ import {AsyncOutput,EVENTS_OUTPUT,EventOutput,+ FlagEvaluationsOutput,PersonDistinctIdsOutput,PersonMergeEventsOutput,PersonsOutput,@@ -64,12 +67,18 @@ export interface EventSubpipelineInput {export interface EventSubpipelineConfig {options: EventPipelineRunnerOptionsoutputs: IngestionOutputs<- EventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput | PersonMergeEventsOutput+ | EventOutput+ | FlagEvaluationsOutput+ | IngestionWarningsOutput+ | PersonsOutput+ | PersonDistinctIdsOutput+ | PersonMergeEventsOutput>teamManager: TeamManagergroupTypeManager: GroupTypeManagerhogTransformer: HogTransformertopHog: TopHogWrapper+ flagEvaluationsService?: FlagEvaluationsService}// The WithMergeFoldDecision constraint (not a field on EventSubpipelineInput) is deliberate: the@@ -79,9 +88,9 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wibuilder: StartPipelineBuilder<TInput, TContext>,config: EventSubpipelineConfig): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {- const { options, outputs, teamManager, groupTypeManager, hogTransformer, topHog } = config+ const { options, outputs, teamManager, groupTypeManager, hogTransformer, topHog, flagEvaluationsService } = config- return builder+ let pipeline = builder.pipe(createNormalizeProcessPersonFlagStep()).pipe(topHog(createHogTransformEventStep(hogTransformer), [@@ -159,6 +168,16 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi).pipe(createRecordEventUsageStep(resolveAnalyticsUsageKey)).pipe(createCreateEventStep(EVENTS_OUTPUT, options.EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS))++ // 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.+ if (flagEvaluationsService) {+ pipeline = pipeline.pipe(createForkFlagEvaluationsStep(outputs, flagEvaluationsService))+ }++ return pipeline.pipe(topHog(createEmitEventStep({diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex 54c167b34188..eb2d53e847f3 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -13,6 +13,7 @@ import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'import { EventFilterManager } from '~/ingestion/common/event-filters'import { FeatureFlagCalledDedupService } from '~/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'+import { FlagEvaluationsService } from '~/ingestion/common/flag-evaluations/flag-evaluations-service'import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { createMergeFoldPlanningStep } from '~/ingestion/common/persons/person-merge-fold'@@ -41,7 +42,14 @@ import { IngestionOverflowMode } from '~/ingestion/config'import { TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'import { EventSubpipelineConfig, EventSubpipelineInput, createEventSubpipeline } from './event-subpipeline'-import { AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from './outputs'+import {+ AsyncOutput,+ EventOutput,+ FlagEvaluationsOutput,+ PersonDistinctIdsOutput,+ PersonMergeEventsOutput,+ PersonsOutput,+} from './outputs'import {PostTeamPreprocessingSubpipelineConfig,createPostTeamPreprocessingSubpipeline,@@ -55,6 +63,7 @@ export interface JoinedIngestionPipelineConfig {groupsPrefetchEnabled: booleanoutputs: IngestionOutputs<| EventOutput+ | FlagEvaluationsOutput| IngestionWarningsOutput| DlqOutput| OverflowOutput@@ -88,6 +97,7 @@ export interface JoinedIngestionPipelineDeps {overflowRedirectService?: OverflowRedirectServiceoverflowLaneTTLRefreshService?: OverflowRedirectServicefeatureFlagCalledDedupService?: FeatureFlagCalledDedupService+ flagEvaluationsService?: FlagEvaluationsServiceteamManager: TeamManagercookielessManager: CookielessManagergroupTypeManager: GroupTypeManager@@ -136,6 +146,7 @@ export function createJoinedIngestionPipeline<overflowRedirectService,overflowLaneTTLRefreshService,featureFlagCalledDedupService,+ flagEvaluationsService,teamManager,cookielessManager,groupTypeManager,@@ -166,6 +177,7 @@ export function createJoinedIngestionPipeline<groupTypeManager,hogTransformer,topHog: topHogWrapper,+ flagEvaluationsService,}const mergeFoldPlanningStep = createMergeFoldPlanningStep<EventSubpipelineInput>(perDistinctIdOptions)diff --git a/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts b/nodejs/src/ingestion/pipelines/analytics/outputs/registry.tsindex 4ab95c713ff5..60cacf908fcd 100644--- a/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts+++ b/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts@@ -1,4 +1,11 @@-import { ASYNC_OUTPUT, EVENTS_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '.'+import {+ ASYNC_OUTPUT,+ EVENTS_OUTPUT,+ FLAG_EVALUATIONS_OUTPUT,+ PERSONS_OUTPUT,+ PERSON_DISTINCT_IDS_OUTPUT,+ PERSON_MERGE_EVENTS_OUTPUT,+} from '.'import {APP_METRICS_OUTPUT,@@ -19,6 +26,10 @@ export function createOutputsRegistry() {topicKey: 'INGESTION_OUTPUT_EVENTS_TOPIC',producerKey: 'INGESTION_OUTPUT_EVENTS_PRODUCER',})+ .register(FLAG_EVALUATIONS_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC',+ producerKey: 'INGESTION_OUTPUT_FLAG_EVALUATIONS_PRODUCER',+ }).register(INGESTION_WARNINGS_OUTPUT, {topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex de64ad15241f..00d4123835c3 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -76,6 +76,7 @@ import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converteimport { IngestBatchRequest, IngestBatchResponse } from '../ingestion/api/types'import { EventFilterManagerComponent } from '../ingestion/common/event-filters'import { createFeatureFlagCalledDedupService } from '../ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'+import { createFlagEvaluationsService } from '../ingestion/common/flag-evaluations/flag-evaluations-service'import { MainLaneOverflowRedirect } from '../ingestion/common/overflow-redirect/main-lane-overflow-redirect'import { OverflowLaneOverflowRedirect } from '../ingestion/common/overflow-redirect/overflow-lane-overflow-redirect'import { OverflowRedirectService } from '../ingestion/common/overflow-redirect/overflow-redirect-service'@@ -485,6 +486,7 @@ export class IngestionApiServer implements NodeServer {this.featureFlagCalledDedupRedisPool,this.config)+ const flagEvaluationsService = createFlagEvaluationsService(this.config)const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore,@@ -501,6 +503,7 @@ export class IngestionApiServer implements NodeServer {overflowRedirectService,overflowLaneTTLRefreshService,featureFlagCalledDedupService,+ flagEvaluationsService,teamManager,cookielessManager: this.cookielessManager,groupTypeManager,diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex d420507a41d1..4789e1aca2f1 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -378,7 +378,12 @@ export interface ProcessedEvent {project_id: ProjectIddistinct_id: stringelements_chain: string- created_at: null+ /**+ * Stamped once when create-event assembles the event, so every table this+ * event is written to agrees on it. Serializing twice would otherwise read+ * the wall clock twice and stamp two different values.+ */+ created_at: DateTimecaptured_at: Date | nullperson_id: stringperson_properties: Record<string, unknown>diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.tsindex 2d0159ae2793..919c6dbead39 100644--- a/nodejs/tests/helpers/ingestion-e2e.ts+++ b/nodejs/tests/helpers/ingestion-e2e.ts@@ -315,6 +315,21 @@ export async function fetchEvents(clickhouse: Clickhouse, teamId: number) {return queryResult.map(parseRawClickHouseEvent)}+export async function fetchFlagEvaluations(clickhouse: Clickhouse, teamId: number) {+ return (await retryClickHouseOperation(+ () =>+ clickhouse.query(`+ SELECT *+ FROM flag_evaluations+ WHERE team_id = ${teamId}+ ORDER BY timestamp ASC+ `),+ 'fetchFlagEvaluations query',+ 3,+ true+ )) as any[]+}+export async function fetchIngestionWarnings(clickhouse: Clickhouse, teamId: number) {const queryResult = (await retryClickHouseOperation(() =>diff --git a/nodejs/tests/helpers/ingestion-outputs.ts b/nodejs/tests/helpers/ingestion-outputs.tsindex 15a97e1fa445..23e28e324323 100644--- a/nodejs/tests/helpers/ingestion-outputs.ts+++ b/nodejs/tests/helpers/ingestion-outputs.ts@@ -1,6 +1,7 @@import {KAFKA_APP_METRICS_2,KAFKA_CLICKHOUSE_AI_EVENTS_JSON,+ KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,KAFKA_CLICKHOUSE_HEATMAP_EVENTS,KAFKA_CLICKHOUSE_TOPHOG,KAFKA_EVENTS_JSON,@@ -28,6 +29,7 @@ import {AI_EVENTS_OUTPUT,ASYNC_OUTPUT,EVENTS_OUTPUT,+ FLAG_EVALUATIONS_OUTPUT,PERSONS_OUTPUT,PERSON_DISTINCT_IDS_OUTPUT,PERSON_MERGE_EVENTS_OUTPUT,@@ -51,6 +53,11 @@ export function createTestIngestionOutputs(kafkaProducer: KafkaProducerWrapper)return new IngestionOutputs({[EVENTS_OUTPUT]: testOutput(EVENTS_OUTPUT, KAFKA_EVENTS_JSON, kafkaProducer),[AI_EVENTS_OUTPUT]: testOutput(AI_EVENTS_OUTPUT, KAFKA_CLICKHOUSE_AI_EVENTS_JSON, kafkaProducer),+ [FLAG_EVALUATIONS_OUTPUT]: testOutput(+ FLAG_EVALUATIONS_OUTPUT,+ KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,+ kafkaProducer+ ),[HEATMAPS_OUTPUT]: testOutput(HEATMAPS_OUTPUT, KAFKA_CLICKHOUSE_HEATMAP_EVENTS, kafkaProducer),[INGESTION_WARNINGS_OUTPUT]: testOutput(INGESTION_WARNINGS_OUTPUT, KAFKA_INGESTION_WARNINGS, kafkaProducer),[DLQ_OUTPUT]: testOutput(DLQ_OUTPUT, KAFKA_EVENTS_PLUGIN_INGESTION_DLQ, kafkaProducer),diff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.tsindex 551b9b25fad0..eb7cbc5cd959 100644--- a/nodejs/tests/helpers/kafka.ts+++ b/nodejs/tests/helpers/kafka.ts@@ -6,6 +6,7 @@ import {KAFKA_BUFFER,KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES,KAFKA_CLICKHOUSE_AI_EVENTS_JSON,+ KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,KAFKA_CLICKHOUSE_HEATMAP_EVENTS,KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS,KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,@@ -72,6 +73,7 @@ async function createTopicsWithClient(client: ReturnType<typeof AdminClient.crea// recreated per test, so ClickHouse's Kafka consumers keep their partition assignments.export const TEST_KAFKA_TOPICS = [KAFKA_CLICKHOUSE_AI_EVENTS_JSON,+ KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,KAFKA_EVENTS_JSON,KAFKA_EVENTS_PLUGIN_INGESTION,KAFKA_BUFFER,diff --git a/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts b/nodejs/tests/ingestion/flag-evaluations-e2e.test.tsnew file mode 100644index 000000000000..de0e8b63f879--- /dev/null+++ b/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts@@ -0,0 +1,122 @@+// Pins the full flag-evaluations shadow-write path — config → fork step → output+// registration → Kafka topic → ClickHouse Kafka engine → MV → flag_evaluations+// table — which no unit test can: a topic-key typo, a row column ClickHouse can't+// parse (silently eaten by kafka_skip_broken_messages), or a broken MV projection+// all produce "row queued but never lands".+import { createHogTransformerService } from '~/cdp/hog-transformations/hog-transformer.service'+import { KAFKA_CLICKHOUSE_FLAG_EVALUATIONS } from '~/common/config/kafka-topics'+import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'+import { parseJSON } from '~/common/utils/json-parse'+import { createFlagEvaluationsService } from '~/ingestion/common/flag-evaluations/flag-evaluations-service'+import { getDefaultIngestionConsumerConfig, getDefaultIngestionOutputsConfig } from '~/ingestion/config'+import { IngestionConsumer } from '~/ingestion/ingestion-consumer'+import { Clickhouse } from '~/tests/helpers/clickhouse'+import { waitForExpect } from '~/tests/helpers/expectations'+import {+ EventBuilder,+ createKafkaMessages,+ createTestWithTeamIngester,+ fetchEvents,+ fetchFlagEvaluations,+ waitForClickHouseKafkaConsumer,+ waitForKafkaMessages,+} from '~/tests/helpers/ingestion-e2e'+import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'+import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'+import { resetTestDatabase } from '~/tests/helpers/sql'++jest.mock('~/common/utils/logger')++describe('Flag evaluations shadow-routing E2E', () => {+ const testWithTeamIngester = createTestWithTeamIngester({}, (infra, kafkaProducer) => {+ const outputs = createTestIngestionOutputs(kafkaProducer)+ return new IngestionConsumer(infra.config, {+ ...infra,+ hogTransformer: createHogTransformerService(infra.config, {+ ...infra,+ monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),+ }),+ outputs,+ clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),+ })+ })++ let clickhouse: Clickhouse++ beforeAll(async () => {+ clickhouse = Clickhouse.create()+ await ensureKafkaTopics(TEST_KAFKA_TOPICS)+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ await waitForClickHouseKafkaConsumer(clickhouse)+ })++ afterAll(async () => {+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ clickhouse.close()+ })++ testWithTeamIngester(+ 'dual_write mode: a $feature_flag_called event lands in both flag_evaluations and events',+ {+ pluginServerConfig: {+ INGESTION_FLAG_EVALUATIONS_MODE: 'dual_write',+ INGESTION_FLAG_EVALUATIONS_TEAMS: '*',+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,+ },+ },+ async ({ ingester, team, kafkaProducer, token }) => {+ const event = new EventBuilder(team)+ .withEvent('$feature_flag_called')+ .withProperties({+ $feature_flag: 'my-flag',+ $feature_flag_response: true,+ })+ .build()++ await ingester.handleKafkaBatch(createKafkaMessages([event], token))+ await waitForKafkaMessages(kafkaProducer)++ const flagEvaluations = await waitForExpect(async () => {+ const rows = await fetchFlagEvaluations(clickhouse, team.id)+ expect(rows.length).toBe(1)+ return rows+ }, 30_000)++ // The two rows do not necessarily arrive on the same Kafka flush, and the+ // events row is usually the later of the two, so this read is polled too.+ const events = await waitForExpect(async () => {+ const rows = await fetchEvents(clickhouse, team.id)+ expect(rows.length).toBe(1)+ return rows+ }, 30_000)+ expect(events[0].event).toBe('$feature_flag_called')+ expect(events[0].properties.$feature_flag).toBe('my-flag')++ expect(flagEvaluations[0].event).toBe('$feature_flag_called')+ expect(flagEvaluations[0].uuid).toBe(event.uuid)+ expect(parseJSON(flagEvaluations[0].properties).$feature_flag).toBe('my-flag')+ // The shard materializes these out of properties; reading them+ // through the flag_evaluations proxy proves that wiring.+ expect(flagEvaluations[0].flag_key).toBe('my-flag')+ expect(flagEvaluations[0].response).toBe('true')+ // person_id must match what the events table stamped for the same+ // event — the parity per-flag uniques depend on.+ expect(flagEvaluations[0].person_id).not.toBe('00000000-0000-0000-0000-000000000000')+ expect(flagEvaluations[0].person_id).toBe(events[0].person_id)+ // The producer omits inserted_at; the MV fallback must fill it.+ expect(flagEvaluations[0].inserted_at).not.toMatch(/^1970/)+ }+ )++ it('ships disabled by default', () => {+ // The only thing the round trip above would add for the disabled case:+ // that nothing flipped the fleet default. createFlagEvaluationsService+ // returning undefined is what keeps the step out of the pipeline.+ const config = { ...getDefaultIngestionConsumerConfig(), ...getDefaultIngestionOutputsConfig() }++ expect(config.INGESTION_FLAG_EVALUATIONS_MODE).toBe('disabled')+ expect(createFlagEvaluationsService(config)).toBeUndefined()+ })+})