: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
fix(flags): stop $feature_flag_called creating orphan person profiles (#62816)
Phil Haack35f3ffb8cfa7
diff --git a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.tsindex f918522610b0..cd20d0db89b9 100644--- a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts+++ b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts@@ -87,6 +87,7 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})PERSON_MERGE_SYNC_BATCH_SIZE: 0,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,PERSON_PROPERTIES_UPDATE_ALL: false,+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',},outputs: mockOutputs,teamManager: {diff --git a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.tsindex 346802613b57..25b1ec72ef58 100644--- a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts+++ b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts@@ -91,7 +91,7 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,).pipe(createNormalizeEventStep()).pipe(createProcessAiEventStep())- .pipe(createProcessPersonlessStep())+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS)).pipe(topHog(createProcessPersonsStep(options, outputs), [timer('process_persons_time', (input) => ({diff --git a/nodejs/src/ingestion/analytics/event-subpipeline.ts b/nodejs/src/ingestion/analytics/event-subpipeline.tsindex af3429d9eaff..43705724989f 100644--- a/nodejs/src/ingestion/analytics/event-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/event-subpipeline.ts@@ -83,7 +83,7 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo])).pipe(createNormalizeEventStep())- .pipe(createProcessPersonlessStep())+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS)).pipe(topHog(createProcessPersonsStep(options, outputs), [timer('process_persons_time', (input) => ({diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex ee87eedac09c..d6c5a7fab72f 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -19,6 +19,9 @@ import type { PostgresRouterConfig } from '../utils/db/postgres'import { isDevEnv, isProdEnv } from '../utils/env-utils'import { INGESTION_DOWNSTREAM_PRODUCER, INGESTION_UPSTREAM_PRODUCER, type ProducerName } from './common/outputs'+/** Default for FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '' disables the personless default so it is opt-in per team via config. */+export const DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS = ''+// =============================================================================// Infrastructure sub-config types// These group CommonConfig keys by infrastructure concern for use in server@@ -160,6 +163,8 @@ export type IngestionConsumerConfig = {SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: booleanEVENT_SCHEMA_ENFORCEMENT_ENABLED: booleanKAFKA_BATCH_START_LOGGING_ENABLED: boolean+ /** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: string// AI event splitting configINGESTION_AI_EVENT_SPLITTING_ENABLED: boolean@@ -271,6 +276,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: false,EVENT_SCHEMA_ENFORCEMENT_ENABLED: true,KAFKA_BATCH_START_LOGGING_ENABLED: false,+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,// AI event splitting configINGESTION_AI_EVENT_SPLITTING_ENABLED: false,diff --git a/nodejs/src/ingestion/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/event-processing/event-pipeline-options.tsindex 9d97721c55b4..d652fb54d6d4 100644--- a/nodejs/src/ingestion/event-processing/event-pipeline-options.ts+++ b/nodejs/src/ingestion/event-processing/event-pipeline-options.ts@@ -5,4 +5,6 @@ export interface EventPipelineRunnerOptions {PERSON_MERGE_SYNC_BATCH_SIZE: numberPERSON_JSONB_SIZE_ESTIMATE_ENABLE: numberPERSON_PROPERTIES_UPDATE_ALL: boolean+ /** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: string}diff --git a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.tsindex 73bb76b24a5b..926e687759d8 100644--- a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts+++ b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts@@ -70,6 +70,7 @@ describe('normalizeProcessPersonFlagStep', () => {expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {expect(result.value.processPerson).toBe(false)+ expect(result.value.processPersonExplicitlyTrue).toBe(false)expect(result.value.forceDisablePersonProcessing).toBe(false)}})@@ -147,6 +148,8 @@ describe('normalizeProcessPersonFlagStep', () => {expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {expect(result.value.processPerson).toBe(false)+ // The explicit-true capture happens before the header override.+ expect(result.value.processPersonExplicitlyTrue).toBe(true)expect(result.value.forceDisablePersonProcessing).toBe(true)}})@@ -182,16 +185,22 @@ describe('normalizeProcessPersonFlagStep', () => {expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {expect(result.value.processPerson).toBe(true)+ expect(result.value.processPersonExplicitlyTrue).toBe(false)expect(result.value.forceDisablePersonProcessing).toBe(false)}})- it('keeps processPerson=true when $process_person_profile=true explicitly', async () => {+ it('leaves $feature_flag_called events personful when no $process_person_profile property is set', async () => {const input: StepInput = {...baseInput,event: {...baseEvent,- properties: { $process_person_profile: true },+ event: '$feature_flag_called',+ properties: {+ $feature_flag: 'new-homepage',+ $feature_flag_response: 'test',+ $set: { email: '[email protected]' },+ },},}@@ -200,8 +209,34 @@ describe('normalizeProcessPersonFlagStep', () => {expect(result.type).toBe(PipelineResultType.OK)if (result.type === PipelineResultType.OK) {expect(result.value.processPerson).toBe(true)+ expect(result.value.processPersonExplicitlyTrue).toBe(false)expect(result.value.forceDisablePersonProcessing).toBe(false)+ expect(result.value.event.properties?.$process_person_profile).toBeUndefined()+ expect(result.value.event.properties?.$set).toEqual({ email: '[email protected]' })}})++ it.each(['$pageview', '$feature_flag_called'])(+ 'keeps %s personful when $process_person_profile=true explicitly',+ async (eventName) => {+ const input: StepInput = {+ ...baseInput,+ event: {+ ...baseEvent,+ event: eventName,+ properties: { $process_person_profile: true },+ },+ }++ const result = await normalizeStep(input)++ expect(result.type).toBe(PipelineResultType.OK)+ if (result.type === PipelineResultType.OK) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.processPersonExplicitlyTrue).toBe(true)+ expect(result.value.forceDisablePersonProcessing).toBe(false)+ }+ }+ )})})diff --git a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.ts b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.tsindex 67c43a3d226f..d5d06203284f 100644--- a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.ts+++ b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.ts@@ -13,6 +13,7 @@ type NormalizeProcessPersonFlagInput = {type NormalizeProcessPersonFlagOutput = {processPerson: boolean+ processPersonExplicitlyTrue: booleanforceDisablePersonProcessing: boolean}@@ -28,6 +29,9 @@ export function createNormalizeProcessPersonFlagStep<TInput extends NormalizeProconst forceDisablePersonProcessing = input.headers.force_disable_person_processing === truelet processPerson = true // The default.let normalizedEvent = event+ // Captured here because normalizeProcessPerson later deletes the property for+ // personful events, and downstream steps need to know it was explicitly set.+ const processPersonExplicitlyTrue = event.properties?.$process_person_profile === true// Check if force_disable_person_processing header is set to trueif (forceDisablePersonProcessing) {@@ -83,6 +87,7 @@ export function createNormalizeProcessPersonFlagStep<TInput extends NormalizePro...input,event: normalizedEvent,processPerson,+ processPersonExplicitlyTrue,forceDisablePersonProcessing,},[],diff --git a/nodejs/src/ingestion/event-processing/process-personless-step.test.ts b/nodejs/src/ingestion/event-processing/process-personless-step.test.tsindex 734ea1e523e0..abf9cbd148df 100644--- a/nodejs/src/ingestion/event-processing/process-personless-step.test.ts+++ b/nodejs/src/ingestion/event-processing/process-personless-step.test.ts@@ -8,15 +8,18 @@ import { BatchWritingPersonsStore } from '~/worker/ingestion/persons/batch-writiimport { BatchBoundPersonsStore } from '~/worker/ingestion/persons/persons-store-for-batch'import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'+import { createTestEventHeaders } from '../../../tests/helpers/event-headers'import { createOrganization, createTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'import { KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '../../config/kafka-topics'-import { Hub, InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '../../types'+import { EventHeaders, Hub, InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'import { UUIDT } from '../../utils/utils'import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '../analytics/outputs'import { INGESTION_WARNINGS_OUTPUT } from '../common/outputs'import { IngestionOutputs } from '../outputs/ingestion-outputs'import { SingleIngestionOutput } from '../outputs/single-ingestion-output'+import { createNormalizeEventStep } from './normalize-event-step'+import { createNormalizeProcessPersonFlagStep } from './normalize-process-person-flag-step'import { ProcessPersonlessInput, createProcessPersonlessStep } from './process-personless-step'function createPersonOutputs(_hub: Hub) {@@ -121,13 +124,18 @@ describe('createProcessPersonlessStep', () => {team,timestamp,processPerson: false,+ processPersonExplicitlyTrue: false,forceDisablePersonProcessing: false,personsStoreForBatch: new BatchBoundPersonsStore(personsStore, 0),...overrides,})+ // Builds the step with the flag-called personless default enabled for all teams. The+ // production default is '' (opt-in per team), so tests opt in explicitly here.+ const buildStep = () => createProcessPersonlessStep('*')+it('passes through when processPerson is true', async () => {- const step = createProcessPersonlessStep()+ const step = buildStep()const input = createInput({ processPerson: true })const result = await step(input)@@ -138,9 +146,271 @@ describe('createProcessPersonlessStep', () => {}})+ describe('$feature_flag_called personless default', () => {+ const flagCalledEvent = (properties: Properties = {}): PluginEvent => ({+ ...pluginEvent,+ event: '$feature_flag_called',+ properties: { $feature_flag: 'new-homepage', $feature_flag_response: 'test', ...properties },+ })++ it('keeps the event personful when a person already exists', async () => {+ const personUuid = new UUIDT().toString()++ await createPerson(hub, timestamp, { name: 'John' }, {}, {}, teamId, null, false, personUuid, {+ distinctId: pluginEvent.distinct_id,+ })++ const step = buildStep()+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ })++ it('keeps the event personful when it carries group keys', async () => {+ const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')++ const step = buildStep()+ const result = await step(+ createInput({+ processPerson: true,+ normalizedEvent: flagCalledEvent({ $groups: { organization: 'org-1' } }),+ })+ )++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ expect(fetchForCheckingSpy).not.toHaveBeenCalled()+ })++ it('still defaults to personless when $groups is empty', async () => {+ const step = buildStep()+ const result = await step(+ createInput({ processPerson: true, normalizedEvent: flagCalledEvent({ $groups: {} }) })+ )++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ }+ })++ it('keeps the event personful when the default is disabled via config', async () => {+ const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')++ const step = createProcessPersonlessStep('')+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ expect(fetchForCheckingSpy).not.toHaveBeenCalled()+ })++ it('applies the default when the team is in the configured team list', async () => {+ const step = createProcessPersonlessStep(`${teamId}`)+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ }+ })++ it('keeps the event personful when $process_person_profile was explicitly true', async () => {+ const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')++ const step = buildStep()+ const result = await step(+ createInput({+ processPerson: true,+ processPersonExplicitlyTrue: true,+ normalizedEvent: flagCalledEvent(),+ })+ )++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ expect(fetchForCheckingSpy).not.toHaveBeenCalled()+ })++ it('defaults to personless and records the distinct ID when no person exists', async () => {+ const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')++ const step = buildStep()+ const result = await step(+ createInput({+ processPerson: true,+ normalizedEvent: flagCalledEvent({ $set: { email: '[email protected]' } }),+ })+ )++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ expect(result.value.personlessPerson!.properties).toEqual({})+ // The event is re-normalized as personless: $set stripped, personless stamp added.+ expect(result.value.normalizedEvent.properties?.$set).toBeUndefined()+ expect(result.value.normalizedEvent.properties?.$process_person_profile).toBe(false)+ }+ expect(addPersonlessDistinctIdSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)+ })++ it('skips the personless distinct ID insert when the batch already has a result', async () => {+ jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(false)+ const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')++ const step = buildStep()+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ }+ expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()+ })++ it('keeps the event personful when the distinct ID turns out to be merged', async () => {+ const personUuid = new UUIDT().toString()+ const person = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, personUuid, {+ distinctId: 'merge-target',+ })++ jest.spyOn(personsStore, 'fetchForChecking').mockResolvedValue(null)+ jest.spyOn(personsStore, 'addPersonlessDistinctId').mockResolvedValue(true)+ const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)++ const step = buildStep()+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ expect(fetchForUpdateSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)+ })++ it('defaults to personless when the merged person cannot be fetched from the leader', async () => {+ jest.spyOn(personsStore, 'fetchForChecking').mockResolvedValue(null)+ jest.spyOn(personsStore, 'addPersonlessDistinctId').mockResolvedValue(true)+ jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(null)++ const step = buildStep()+ const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ }+ })++ it('takes the generic personless path, not the defaulting branch, when already force-disabled', async () => {+ const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')+ const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')++ const step = buildStep()+ const result = await step(+ createInput({ normalizedEvent: flagCalledEvent(), forceDisablePersonProcessing: true })+ )++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.personlessPerson).toBeDefined()+ }+ expect(fetchForCheckingSpy).not.toHaveBeenCalled()+ expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()+ })++ // Pipes an event through the same normalization steps that precede the personless+ // step in the real subpipeline, so these tests cover the boundary where+ // normalizeProcessPerson strips the explicit $process_person_profile property.+ const runThroughNormalization = async (event: PluginEvent): Promise<ProcessPersonlessInput> => {+ const normalizeFlagStep = createNormalizeProcessPersonFlagStep<{+ event: PluginEvent+ headers: EventHeaders+ team: Team+ }>()+ const flagResult = await normalizeFlagStep({ event, team, headers: createTestEventHeaders() })+ if (!isOkResult(flagResult)) {+ throw new Error('expected normalize flag step to return ok')+ }++ const normalizeEventStep = createNormalizeEventStep<typeof flagResult.value>()+ const normalizeResult = await normalizeEventStep(flagResult.value)+ if (!isOkResult(normalizeResult)) {+ throw new Error('expected normalize event step to return ok')+ }+ return { ...normalizeResult.value, personsStoreForBatch: new BatchBoundPersonsStore(personsStore, 0) }+ }++ it('keeps an explicit-true event personful after normalization strips the property', async () => {+ const personlessStep = buildStep()+ const normalized = await runThroughNormalization(flagCalledEvent({ $process_person_profile: true }))++ // Normalization removes the explicit-true property for personful events, so the+ // personless step must rely on the captured processPersonExplicitlyTrue flag.+ expect(normalized.normalizedEvent.properties?.$process_person_profile).toBeUndefined()++ const result = await personlessStep(normalized)++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(true)+ expect(result.value.personlessPerson).toBeUndefined()+ }+ })++ it('defaults an event without the property to personless through normalization', async () => {+ const personlessStep = buildStep()+ const normalized = await runThroughNormalization(flagCalledEvent())++ const result = await personlessStep(normalized)++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ expect(result.value.normalizedEvent.properties?.$process_person_profile).toBe(false)+ }+ })++ it('skips the defaulting branch for explicit $process_person_profile=false events', async () => {+ const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')++ const personlessStep = buildStep()+ const normalized = await runThroughNormalization(flagCalledEvent({ $process_person_profile: false }))++ const result = await personlessStep(normalized)++ expect(result.type).toBe(PipelineResultType.OK)+ if (isOkResult(result)) {+ expect(result.value.processPerson).toBe(false)+ expect(result.value.personlessPerson).toBeDefined()+ }+ // The plain personless path leaves the insert to the batch step.+ expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()+ })+ })+describe('basic personless functionality', () => {it('returns fake person when no existing person found', async () => {- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -161,7 +431,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -176,7 +446,7 @@ describe('createProcessPersonlessStep', () => {it('checks batch result for personless distinct ID when no person exists', async () => {const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')- const step = createProcessPersonlessStep()+ const step = buildStep()await step(createInput())expect(getPersonlessBatchResultSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id)@@ -185,7 +455,7 @@ describe('createProcessPersonlessStep', () => {it('returns fake person when batch result indicates no merge', async () => {jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(false)- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -205,7 +475,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -224,7 +494,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -245,7 +515,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -279,7 +549,7 @@ describe('createProcessPersonlessStep', () => {jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(true)const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -292,7 +562,7 @@ describe('createProcessPersonlessStep', () => {const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')- const step = createProcessPersonlessStep()+ const step = buildStep()const result = await step(createInput({ forceDisablePersonProcessing: true }))expect(result.type).toBe(PipelineResultType.OK)@@ -310,7 +580,7 @@ describe('createProcessPersonlessStep', () => {it('performs normal processing when false', async () => {const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')- const step = createProcessPersonlessStep()+ const step = buildStep()await step(createInput())expect(fetchForCheckingSpy).toHaveBeenCalled()@@ -318,7 +588,7 @@ describe('createProcessPersonlessStep', () => {it('works with different distinct IDs', async () => {const distinctIds = ['user-1', 'user-2', 'user-3']- const step = createProcessPersonlessStep()+ const step = buildStep()for (const distinctId of distinctIds) {const result = await step(diff --git a/nodejs/src/ingestion/event-processing/process-personless-step.ts b/nodejs/src/ingestion/event-processing/process-personless-step.tsindex 632b53216a1e..b2f4ff4f50a1 100644--- a/nodejs/src/ingestion/event-processing/process-personless-step.ts+++ b/nodejs/src/ingestion/event-processing/process-personless-step.ts@@ -2,9 +2,17 @@ import { DateTime } from 'luxon'import { PluginEvent } from '~/plugin-scaffold'+import { buildIntegerMatcher } from '../../config/config'import { Person, Team } from '../../types'+import { normalizeProcessPerson } from '../../utils/event'import { uuidFromDistinctId } from '../../worker/ingestion/person-uuid'+import {+ hasInsertedPersonlessDistinctId,+ markPersonlessDistinctIdInserted,+ personlessDistinctIdCacheOperationsCounter,+} from '../../worker/ingestion/persons/personless-distinct-id-cache'import { PersonsStoreForBatch } from '../../worker/ingestion/persons/persons-store-for-batch'+import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '../config'import { PipelineResult, ok } from '../pipelines/results'import { ProcessingStep } from '../pipelines/steps'@@ -13,6 +21,7 @@ export type ProcessPersonlessInput = {team: Teamtimestamp: DateTimeprocessPerson: boolean+ processPersonExplicitlyTrue: booleanforceDisablePersonProcessing: booleanpersonsStoreForBatch: PersonsStoreForBatch}@@ -21,24 +30,55 @@ export type ProcessPersonlessOutput = {personlessPerson?: Person}+const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'++/**+ * Group-keyed experiment exposure queries read the $group_N columns from the exposure+ * event, and createEvent strips those for personless events. Events carrying group keys+ * must stay personful or their exposures disappear from group-aggregated experiments.+ * Checking $groups alone is sufficient: SDKs only ever send group keys as $groups, and+ * $group_N is an internal representation the groups step derives from $groups (and only+ * when processPerson stays true), so it never arrives here pre-expanded from a client.+ */+function eventHasGroups(properties: PluginEvent['properties']): boolean {+ const groups = properties?.$groups+ return typeof groups === 'object' && groups !== null && !Array.isArray(groups) && Object.keys(groups).length > 0+}+/*** Pipeline step that handles personless event processing checks.*- * When processPerson=false, this step:+ * Runs when processPerson=false, and also for $feature_flag_called events that did not+ * explicitly set $process_person_profile=true — so server-side flag evaluation does not+ * create orphan person profiles (see #60581). Flag-called events that find an existing+ * person, or that carry group keys, stay personful; the rest are defaulted to personless.+ *+ * For personless events, this step:* 1. Fetches existing person from cache (populated by prefetchPersonsStep)* 2. Checks batch results for is_merged flag (populated by processPersonlessDistinctIdsBatchStep)* 3. Calculates force_upgrade flag* 4. Returns person (real or fake) with potential force_upgrade flag*/-export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(): ProcessingStep<- TInput,- TInput & ProcessPersonlessOutput-> {+export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(+ flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS+): ProcessingStep<TInput, TInput & ProcessPersonlessOutput> {+ const flagCalledDefaultEnabledForTeam = buildIntegerMatcher(flagCalledPersonlessDefaultTeams.trim(), true)+return async function processPersonlessStep(input: TInput): Promise<PipelineResult<TInput & ProcessPersonlessOutput>> {if (input.processPerson) {- return ok(input)+ const mayDefaultFlagCalledToPersonless =+ input.normalizedEvent.event === FEATURE_FLAG_CALLED_EVENT &&+ !input.processPersonExplicitlyTrue &&+ !eventHasGroups(input.normalizedEvent.properties) &&+ flagCalledDefaultEnabledForTeam(input.team.id)++ if (!mayDefaultFlagCalledToPersonless) {+ return ok(input)+ }++ return await applyFeatureFlagCalledPersonlessDefault(input, input.personsStoreForBatch)}const { normalizedEvent, team, timestamp, forceDisablePersonProcessing, personsStoreForBatch } = input@@ -90,6 +130,61 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpu}}+/**+ * Defaults a $feature_flag_called event to personless unless a person already exists for+ * its distinct ID, so server-side flag evaluation does not create orphan person profiles.+ */+async function applyFeatureFlagCalledPersonlessDefault<TInput extends ProcessPersonlessInput>(+ input: TInput,+ personsStore: PersonsStoreForBatch+): Promise<PipelineResult<TInput & ProcessPersonlessOutput>> {+ const { normalizedEvent, team } = input+ const distinctId = normalizedEvent.distinct_id++ let existingPerson = await personsStore.fetchForChecking(team.id, distinctId)++ if (!existingPerson) {+ let personIsMerged = personsStore.getPersonlessBatchResult(team.id, distinctId)++ if (personIsMerged === undefined) {+ if (hasInsertedPersonlessDistinctId(team.id, distinctId)) {+ // The LRU keeps repeat distinct IDs from re-inserting on every event; a stale+ // hit just means the event goes personless, the same trade-off the batch step+ // accepts.+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source: 'flag_called' })+ } else {+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source: 'flag_called' })+ // The batch step (processPersonlessDistinctIdsBatchStep) only inserts rows for+ // events with explicit $process_person_profile=false, so record this distinct ID+ // here. Without the row, a later identify/merge would never re-point these+ // events at the merged person.+ personIsMerged = await personsStore.addPersonlessDistinctId(team.id, distinctId)+ markPersonlessDistinctIdInserted(team.id, distinctId)+ }+ }++ if (personIsMerged) {+ // The posthog_personlessdistinctid row was updated by a merge, so fetch the+ // person again (using the leader) to associate this event with the merge target.+ existingPerson = await personsStore.fetchForUpdate(team.id, distinctId)+ }+ }++ if (existingPerson) {+ // A person already exists for this distinct ID, so keep the event personful.+ return ok(input)+ }++ return ok({+ ...input,+ // The event was normalized as personful upstream, so re-normalize it to strip+ // $set/$set_once and stamp $process_person_profile=false.+ normalizedEvent: normalizeProcessPerson(normalizedEvent, false),+ processPerson: false,+ personlessPerson: createFakePerson(team.id, distinctId),+ })+}+/*** Creates a deterministic fake person for personless events.*diff --git a/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts b/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.tsindex fa0973e2d337..8e604621c109 100644--- a/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts+++ b/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts@@ -47,6 +47,7 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_SYNC_BATCH_SIZE: 1,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,PERSON_PROPERTIES_UPDATE_ALL: false,+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',}beforeEach(async () => {diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 639b14cac0b5..803552aea647 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -276,6 +276,7 @@ export class IngestionConsumer {PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 91f501e4c820..f0f3400f7d36 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -348,6 +348,7 @@ export class IngestionApiServer implements NodeServer {PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,+ FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}diff --git a/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts b/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.tsindex ebac80394592..8cd89aae7e3c 100644--- a/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts+++ b/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts@@ -1,10 +1,11 @@-import { LRUCache } from 'lru-cache'-import { Counter } from 'prom-client'-import { PipelineResult, ok } from '~/ingestion/pipelines/results'import { PipelineEvent, Team } from '~/types'-import { ONE_HOUR } from '../../../config/constants'+import {+ hasInsertedPersonlessDistinctId,+ markPersonlessDistinctIdInserted,+ personlessDistinctIdCacheOperationsCounter,+} from '../persons/personless-distinct-id-cache'import { PersonsStoreForBatch } from '../persons/persons-store-for-batch'type ProcessPersonlessDistinctIdsBatchStepInput = {@@ -13,20 +14,6 @@ type ProcessPersonlessDistinctIdsBatchStepInput = {personsStoreForBatch: PersonsStoreForBatch}-export const personlessDistinctIdCacheOperationsCounter = new Counter({- name: 'personless_distinct_id_cache_operations_total',- help: 'Number of cache hits and misses for the personless distinct ID inserted cache',- labelNames: ['operation'],-})--// Tracks whether we know we've already inserted a `posthog_personlessdistinctid` for the given-// (team_id, distinct_id) pair. If we have, then we can skip the INSERT attempt.-const PERSONLESS_DISTINCT_ID_INSERTED_CACHE = new LRUCache<string, boolean>({- max: 100_000,- ttl: ONE_HOUR * 4,- updateAgeOnGet: true,-})-/*** Batch step that inserts personless distinct IDs for events where processPerson=false* and no person exists. This runs after prefetchPersonsStep so the person check cache@@ -64,7 +51,7 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles}storeData.seenInBatch.add(cacheKey)- if (PERSONLESS_DISTINCT_ID_INSERTED_CACHE.get(cacheKey)) {+ if (hasInsertedPersonlessDistinctId(e.team.id, e.event.distinct_id)) {cacheHits++} else {storeData.entries.push({ teamId: e.team.id, distinctId: e.event.distinct_id })@@ -72,20 +59,20 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles}if (cacheHits > 0) {- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit' }, cacheHits)+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source: 'batch' }, cacheHits)}const storeCalls = Array.from(entriesByStore.entries()).filter(([, { entries }]) => entries.length > 0)if (storeCalls.length > 0) {const totalMisses = storeCalls.reduce((sum, [, { entries }]) => sum + entries.length, 0)- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss' }, totalMisses)+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source: 'batch' }, totalMisses)await Promise.all(storeCalls.map(async ([store, { entries }]) => {await store.processPersonlessDistinctIdsBatch(entries)for (const entry of entries) {- PERSONLESS_DISTINCT_ID_INSERTED_CACHE.set(`${entry.teamId}|${entry.distinctId}`, true)+ markPersonlessDistinctIdInserted(entry.teamId, entry.distinctId)}}))diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.tsindex 89ee36437bd6..2a2ec6850c14 100644--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts@@ -1520,7 +1520,7 @@ describe('BatchWritingPersonStore', () => {const mockRepo = createMockRepository()const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)- const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct')+ const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct', 0)expect(mockRepo.addPersonlessDistinctId).toHaveBeenCalledWith(teamId, 'test-distinct')expect(result).toBe(true)@@ -1531,7 +1531,7 @@ describe('BatchWritingPersonStore', () => {mockRepo.addPersonlessDistinctId = jest.fn().mockResolvedValue(false)const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)- const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct')+ const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct', 0)expect(mockRepo.addPersonlessDistinctId).toHaveBeenCalledWith(teamId, 'test-distinct')expect(result).toBe(false)diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.tsindex 18dd074d6d85..a520ac086615 100644--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts@@ -1477,9 +1477,12 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreawait (tx || this.personRepository).updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID)}- async addPersonlessDistinctId(teamId: Team['id'], distinctId: string): Promise<boolean> {+ async addPersonlessDistinctId(teamId: Team['id'], distinctId: string, batchId: number): Promise<boolean> {this.incrementCount('addPersonlessDistinctId', distinctId)- return await this.personRepository.addPersonlessDistinctId(teamId, distinctId)+ const isMerged = await this.personRepository.addPersonlessDistinctId(teamId, distinctId)+ // Cache the result so later events for this distinct ID in the same batch skip the insert.+ this.personCache.obtainForBatchId(batchId).setPersonlessBatchResult(teamId, distinctId, isMerged)+ return isMerged}async addPersonlessDistinctIdForMerge(@@ -1517,6 +1520,10 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore}}+ // Returns the cached merge result for a distinct ID inserted earlier this batch:+ // true if the row was merged, false if addPersonlessDistinctId inserted it without a+ // merge, undefined if no insert was recorded. The batch and forMerge paths only cache+ // merged rows, so a non-merged insert from those paths also reads back as undefined.getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {return this.personCache.getPersonlessBatchResult(teamId, distinctId)}diff --git a/nodejs/src/worker/ingestion/persons/personless-distinct-id-cache.ts b/nodejs/src/worker/ingestion/persons/personless-distinct-id-cache.tsnew file mode 100644index 000000000000..0c65cd10394f--- /dev/null+++ b/nodejs/src/worker/ingestion/persons/personless-distinct-id-cache.ts@@ -0,0 +1,28 @@+import { LRUCache } from 'lru-cache'+import { Counter } from 'prom-client'++import { ONE_HOUR } from '../../../config/constants'++export const personlessDistinctIdCacheOperationsCounter = new Counter({+ name: 'personless_distinct_id_cache_operations_total',+ help: 'Number of cache hits and misses for the personless distinct ID inserted cache',+ // `source` separates the batched personless step from the per-event $feature_flag_called+ // path so a high-volume flag-called miss rate can be read on its own during rollout.+ labelNames: ['operation', 'source'],+})++// Tracks whether we know we've already inserted a `posthog_personlessdistinctid` for the given+// (team_id, distinct_id) pair. If we have, then we can skip the INSERT attempt.+const PERSONLESS_DISTINCT_ID_INSERTED_CACHE = new LRUCache<string, boolean>({+ max: 100_000,+ ttl: ONE_HOUR * 4,+ updateAgeOnGet: true,+})++export function hasInsertedPersonlessDistinctId(teamId: number, distinctId: string): boolean {+ return PERSONLESS_DISTINCT_ID_INSERTED_CACHE.get(`${teamId}|${distinctId}`) === true+}++export function markPersonlessDistinctIdInserted(teamId: number, distinctId: string): void {+ PERSONLESS_DISTINCT_ID_INSERTED_CACHE.set(`${teamId}|${distinctId}`, true)+}diff --git a/nodejs/src/worker/ingestion/persons/persons-store-for-batch.ts b/nodejs/src/worker/ingestion/persons/persons-store-for-batch.tsindex 045f5e414a9d..c9d76947424c 100644--- a/nodejs/src/worker/ingestion/persons/persons-store-for-batch.ts+++ b/nodejs/src/worker/ingestion/persons/persons-store-for-batch.ts@@ -78,6 +78,7 @@ export type PersonsStoreForBatch = Omit<| 'updatePersonWithPropertiesDiffForUpdate'| 'addDistinctId'| 'moveDistinctIds'+ | 'addPersonlessDistinctId'| 'addPersonlessDistinctIdForMerge'| 'prefetchPersons'| 'processPersonlessDistinctIdsBatch'@@ -115,6 +116,7 @@ export type PersonsStoreForBatch = Omit<tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]>addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>+ addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean>addPersonlessDistinctIdForMerge(teamId: number,distinctId: string,@@ -350,7 +352,7 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {}addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean> {- return this.store.addPersonlessDistinctId(teamId, distinctId)+ return this.store.addPersonlessDistinctId(teamId, distinctId, this.batchId)}addPersonlessDistinctIdForMerge(diff --git a/nodejs/src/worker/ingestion/persons/persons-store.ts b/nodejs/src/worker/ingestion/persons/persons-store.tsindex fa166733add9..1464d7af54a0 100644--- a/nodejs/src/worker/ingestion/persons/persons-store.ts+++ b/nodejs/src/worker/ingestion/persons/persons-store.ts@@ -121,7 +121,7 @@ export interface PersonsStore extends BatchWritingStore {/*** Adds a personless distinct ID*/- addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean>+ addPersonlessDistinctId(teamId: number, distinctId: string, batchId: number): Promise<boolean>/*** Adds a personless distinct ID during merge