: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): fork flag calls on every ingestion lane (#111128)
Phil Haackc5e2e6cff97a
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 7737344e2621..5922a6730bf8 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,3 @@-import { IngestionLane } from '~/ingestion/config'import { FlagEvaluationsMode } from '~/types'import { FlagEvaluationsEnvConfig, createFlagEvaluationsService } from './flag-evaluations-service'@@ -8,10 +7,8 @@ describe('FlagEvaluationsService', () => {mode: string,teams = '*',excludedTeams = '',- topic = 'clickhouse_flag_evaluations',- lane: IngestionLane | null = 'main'+ topic = 'clickhouse_flag_evaluations'): FlagEvaluationsEnvConfig => ({- INGESTION_LANE: lane,INGESTION_FLAG_EVALUATIONS_MODE: mode,INGESTION_FLAG_EVALUATIONS_TEAMS: teams,INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS: excludedTeams,@@ -29,12 +26,6 @@ describe('FlagEvaluationsService', () => {['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)diff --git a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.tsindex c0aba0d79900..5ca0a9d67fe7 100644--- a/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts+++ b/nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts@@ -1,12 +1,7 @@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 { IngestionConsumerConfig, IngestionOutputsConfig } from '~/ingestion/config'import { FlagEvaluationsMode, Team, ValueMatcher } from '~/types'export interface FlagEvaluationsConfig {@@ -57,7 +52,6 @@ export class FlagEvaluationsService {export type FlagEvaluationsEnvConfig = Pick<IngestionConsumerConfig,- | 'INGESTION_LANE'| 'INGESTION_FLAG_EVALUATIONS_MODE'| 'INGESTION_FLAG_EVALUATIONS_TEAMS'| 'INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS'@@ -65,18 +59,6 @@ export type FlagEvaluationsEnvConfig = Pick<> &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.@@ -97,12 +79,6 @@ export function createFlagEvaluationsService(envConfig: FlagEvaluationsEnvConfig)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.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 f7dc8fe8d65e..b6bbf19ccdb0 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@@ -36,7 +36,7 @@ const createProcessedEvent = (overrides: Partial<ProcessedEvent> = {}): Processeuuid: '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,+ timestamp: DateTime.utc().minus({ hours: 1 }).toISO() as ISOTimestamp,team_id: 7,project_id: 7 as ProjectId,distinct_id: 'distinct-1',@@ -173,6 +173,32 @@ describe('createForkFlagEvaluationsStep', () => {})})+ describe('flag_evaluations retention', () => {+ afterEach(() => {+ jest.useRealTimers()+ })++ it.each([+ // 2026-07-05 is the oldest UTC day a 90-day TTL keeps on 2026-10-02.+ { timestamp: '2026-07-04T23:59:59.999Z', forked: false, outcome: 'continued_past_retention' },+ { timestamp: '2026-07-05T00:00:00.000Z', forked: true, outcome: 'dual_written' },+ ])('forks a call dated $timestamp -> $forked', async ({ timestamp, forked, outcome }) => {+ jest.useFakeTimers({ now: new Date('2026-10-02T15:00:00.000Z') })+ const { step, outputs } = createStep(enabledService())++ const result = await step(createInput([createProcessedEvent({ timestamp: timestamp as ISOTimestamp })]))++ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ await Promise.all(result.sideEffects)+ }+ expect(outputs.queueMessages).toHaveBeenCalledTimes(forked ? 1 : 0)+ expect((await flagEvaluationsEventsTotal.get()).values).toEqual([+ expect.objectContaining({ labels: { outcome }, value: 1 }),+ ])+ })+ })+describe('mapping/produce failure isolation', () => {it('settles the ack rather than rejecting when the produce fails asynchronously', async () => {const { step, outputs } = createStep(enabledService())@@ -350,7 +376,13 @@ describe('createForkFlagEvaluationsStep', () => {name: 'the flag key is missing',mode: FlagEvaluationsMode.FlagEvaluationsOnly,buildService: () => enabledService(),- flagCalledProperties: { $feature_flag_response: true },+ flagCalledOverrides: { properties: { $feature_flag_response: true } },+ },+ {+ name: 'the call is past the flag_evaluations retention',+ mode: FlagEvaluationsMode.FlagEvaluationsOnly,+ buildService: () => enabledService(),+ flagCalledOverrides: { timestamp: DateTime.utc().minus({ days: 91 }).toISO() as ISOTimestamp },},{name: 'queueing the row throws',@@ -363,16 +395,10 @@ describe('createForkFlagEvaluationsStep', () => {},])('keeps the $feature_flag_called event in eventsToEmit when $name',- async ({ mode, buildService, flagCalledProperties, arrange }) => {+ async ({ mode, buildService, flagCalledOverrides, arrange }) => {const deps = createStep(buildService())arrange?.(deps)- const input = createInput(- [- createProcessedEvent(flagCalledProperties && { properties: flagCalledProperties }),- createExposureDuplicate(),- ],- mode- )+ const input = createInput([createProcessedEvent(flagCalledOverrides), createExposureDuplicate()], mode)const result = await deps.step(input)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 a153315e100c..c96fbc43e39e 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@@ -51,6 +51,21 @@ const hasFlagKey = ({ event }: EventToEmit<string>): boolean => {return typeof flagKey === 'string' && flagKey !== ''}+// Mirrors FLAG_EVALUATIONS_TTL_DAYS in posthog/models/flag_evaluations/sql.py. Change both together.+const FLAG_EVALUATIONS_TTL_DAYS = 90+const DAY_MS = 24 * 60 * 60 * 1000++// The table's TTL expires a row dated D at the start of day D + FLAG_EVALUATIONS_TTL_DAYS.+// The day FLAG_EVALUATIONS_TTL_DAYS back has already expired when today starts.+// This function returns the start of the UTC day FLAG_EVALUATIONS_TTL_DAYS - 1 days back, the oldest day the+// table keeps. ClickHouse can drop an older row at any merge. For a FLAG_EVALUATIONS_ONLY team the row is the+// only copy of the call. The fork skips a call this old and leaves it in the events table.+const retentionStartMs = (nowMs: number): number =>+ Math.floor(nowMs / DAY_MS) * DAY_MS - (FLAG_EVALUATIONS_TTL_DAYS - 1) * DAY_MS++const isPastRetention = ({ event }: EventToEmit<string>, retentionStart: number): boolean =>+ Date.parse(event.timestamp) < retentionStart+export interface ForkFlagEvaluationsStepInput {eventsToEmit: EventToEmit<string>[]teamId: number@@ -97,12 +112,18 @@ export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepIif (invalidFlagKeys > 0) {flagEvaluationsEventsTotal.labels('continued_invalid_flag_key').inc(invalidFlagKeys)}- if (mappableEvents.length === 0) {+ const retentionStart = retentionStartMs(Date.now())+ const eventsToFork = mappableEvents.filter((toEmit) => !isPastRetention(toEmit, retentionStart))+ const pastRetention = mappableEvents.length - eventsToFork.length+ if (pastRetention > 0) {+ flagEvaluationsEventsTotal.labels('continued_past_retention').inc(pastRetention)+ }+ if (eventsToFork.length === 0) {return Promise.resolve(ok(input))}const stopsEventsWrites = flagEvaluationsService.stopsEventsWritesFor(input.team)try {- const messages: IngestionOutputMessage[] = mappableEvents.map(({ event }) => {+ const messages: IngestionOutputMessage[] = eventsToFork.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.@@ -149,7 +170,7 @@ export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepI// warning for an oversized event. No events row exists here, so this// step sends that warning.return Promise.all(- mappableEvents.map(({ event }) =>+ eventsToFork.map(({ event }) =>emitIngestionWarning(outputs,event.team_id,@@ -169,15 +190,15 @@ export function createForkFlagEvaluationsStep<T extends ForkFlagEvaluationsStepI// 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))+ // call without a flag key or past the retention window in eventsToEmit.+ const eventsToEmit = input.eventsToEmit.filter((toEmit) => !eventsToFork.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,error,})- flagEvaluationsEventsTotal.labels('continued_fork_error').inc(mappableEvents.length)+ flagEvaluationsEventsTotal.labels('continued_fork_error').inc(eventsToFork.length)return Promise.resolve(ok(input))}}diff --git a/posthog/models/flag_evaluations/PARITY_CHECK.md b/posthog/models/flag_evaluations/PARITY_CHECK.mdindex 805c5618709b..d222bf927fc4 100644--- a/posthog/models/flag_evaluations/PARITY_CHECK.md+++ b/posthog/models/flag_evaluations/PARITY_CHECK.md@@ -10,7 +10,7 @@ See [`sql.py`](./sql.py) for the table family and the schema this compares againTwo inputs, both explicit.-**The day.** One completed UTC day, as `YYYY-MM-DD`. Not today: a partial day reads as a deficit for every event that has not been written yet.+**The day.** One completed UTC day, as `YYYY-MM-DD`. Not today: a partial day reads as a deficit for every event that has not been written yet. Pick a day inside the table's 90-day retention, because the table holds no older calls.**The team ids being widened to.** The allowlist lives only in the Node deployment env config (`INGESTION_FLAG_EVALUATIONS_TEAMS`, `INGESTION_FLAG_EVALUATIONS_EXCLUDED_TEAMS`, `INGESTION_FLAG_EVALUATIONS_MODE`), and nothing in ClickHouse records it. A team that is enabled but writing nothing at all looks identical to a team that was never enabled, so the check cannot derive its own team list. Pass the ids you intend to switch on.@@ -102,13 +102,11 @@ This runs on the cluster that serves customer queries. The group-by state growsIf a batch reaches a ceiling, shrink the batch. Do not raise the ceiling.-### Delayed lanes never fork+### A lane forks only when its deployment config turns the fork on-The fork runs only on the real-time lanes, and that is enforced in code rather than left to deployment config. `createFlagEvaluationsService` in `nodejs/src/ingestion/common/flag-evaluations/flag-evaluations-service.ts` returns `undefined` for any lane outside `REALTIME_INGESTION_LANES`, and the pipeline composes the fork step out entirely when it does. Setting the env vars on the `historical` or `async` lane does not switch it on. The reason for the gate is that a backfill owns this table's history, so a delayed lane that also forked would write rows the backfill already covers.+Every analytics ingestion lane can run the fork step, the delayed `historical` and `async` lanes included. A lane forks only when its deployment config sets `INGESTION_FLAG_EVALUATIONS_MODE` and `INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC`. A lane without them writes the team's calls to the events table and not to `flag_evaluations`, which reads as a deficit for a team whose fork is healthy.-The deficit this produces is therefore narrow. It is not a lane that should have forked and didn't. It is an event that arrives on a real-time lane, gets rerouted to a delayed lane, and reaches the events table with no fork row, which reads as a deficit for a team whose fork is healthy.--Check it first on a deficit that names a team with no other sign of trouble.+On a deficit that names a team with no other sign of trouble, check whether the missing calls came through a lane whose deployment config does not turn the fork on. While the `historical` lane does not fork, start there. It carries `/batch/` requests sent with `historical_migration: true` and managed batch imports, so the events rows it wrote have `historical_migration = 1`. Add `AND historical_migration = 0` to the `events` half of the `UNION ALL`. If the deficit disappears, the missing calls came through the historical lane.## Why this is not a scheduled jobdiff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.pyindex ad8dfce832c0..b3b41ecfedf7 100644--- a/posthog/models/flag_evaluations/sql.py+++ b/posthog/models/flag_evaluations/sql.py@@ -32,6 +32,7 @@ FLAG_EVALUATIONS_WRITABLE_TABLE = f"writable_{FLAG_EVALUATIONS_TABLE}"KAFKA_FLAG_EVALUATIONS_TABLE = f"kafka_{FLAG_EVALUATIONS_TABLE}"FLAG_EVALUATIONS_MV_TABLE = f"{FLAG_EVALUATIONS_TABLE}_mv"+# The Node fork step mirrors this value in fork-flag-evaluations-step.ts. Change both together.FLAG_EVALUATIONS_TTL_DAYS = 90# The only event this table stores. posthog/models/deletion_targets.py uses it to skip this tablediff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 4c297f0f709d..4678b6a1e176 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -51,8 +51,10 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS: int = max(1,get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS", 6, type_cast=int),)-# Use "flag_evaluations" only where ingestion forks every team's flag calls into that table. The historical-# and async ingestion lanes never fork, so calls ingested on them do not move last_called_at with this source.+# Use "flag_evaluations" only where every analytics ingestion lane forks every team's flag calls into that table.+# This source moves last_called_at only for calls that the fork writes. A lane forks only when its deployment+# config sets INGESTION_FLAG_EVALUATIONS_MODE and INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC. The fork also skips a+# call dated past the table's TTL.# Disabling the fork also stops last_called_at with this source, and the checkpoint keeps moving past the missed# calls. Switch this back to "events" before disabling the fork.FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE: str = get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE", "events")