Skip to content

: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.

perf(ingestion): batch $feature_flag_called personless inserts (#63865)

Phil Haack51070b9005fd
diff --git a/nodejs/src/ingestion/common/flag-called-personless.test.ts b/nodejs/src/ingestion/common/flag-called-personless.test.ts
new file mode 100644
index 000000000000..862f7c50325f
--- /dev/null
+++ b/nodejs/src/ingestion/common/flag-called-personless.test.ts
@@ -0,0 +1,56 @@
+import { PluginEvent } from '~/plugin-scaffold'
+
+import { eventHasGroups, isFlagCalledPersonlessCandidate } from './flag-called-personless'
+
+describe('flag-called-personless', () => {
+ const enabledForAll = (): boolean => true
+ const enabledForNone = (): boolean => false
+
+ const event = (
+ overrides: Partial<Pick<PluginEvent, 'event' | 'properties'>> = {}
+ ): Pick<PluginEvent, 'event' | 'properties'> => ({
+ event: '$feature_flag_called',
+ properties: {},
+ ...overrides,
+ })
+
+ describe('eventHasGroups', () => {
+ it.each([
+ [undefined, false],
+ [{}, false],
+ [{ $groups: {} }, false],
+ [{ $groups: { org: 'acme' } }, true],
+ ])('properties %j -> %s', (properties, expected) => {
+ expect(eventHasGroups(properties as PluginEvent['properties'])).toBe(expected)
+ })
+ })
+
+ describe('isFlagCalledPersonlessCandidate', () => {
+ it('is a candidate for a flag-called event on an enabled team', () => {
+ expect(isFlagCalledPersonlessCandidate(event(), 1, false, enabledForAll)).toBe(true)
+ })
+
+ it('is not a candidate for non-flag-called events', () => {
+ expect(isFlagCalledPersonlessCandidate(event({ event: '$pageview' }), 1, false, enabledForAll)).toBe(false)
+ })
+
+ it('is not a candidate when person processing is explicitly true', () => {
+ expect(isFlagCalledPersonlessCandidate(event(), 1, true, enabledForAll)).toBe(false)
+ })
+
+ it('is not a candidate when the event carries group keys', () => {
+ expect(
+ isFlagCalledPersonlessCandidate(
+ event({ properties: { $groups: { org: 'acme' } } }),
+ 1,
+ false,
+ enabledForAll
+ )
+ ).toBe(false)
+ })
+
+ it('is not a candidate when the team is not enabled', () => {
+ expect(isFlagCalledPersonlessCandidate(event(), 1, false, enabledForNone)).toBe(false)
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/common/flag-called-personless.ts b/nodejs/src/ingestion/common/flag-called-personless.ts
new file mode 100644
index 000000000000..2a9eb681fbf3
--- /dev/null
+++ b/nodejs/src/ingestion/common/flag-called-personless.ts
@@ -0,0 +1,55 @@
+import { buildIntegerMatcher } from '~/config/config'
+import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '~/ingestion/config'
+import { PluginEvent } from '~/plugin-scaffold'
+
+export const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
+
+/**
+ * Builds the team matcher for the $feature_flag_called personless default. The per-event step
+ * and the batch step both gate on team eligibility and must agree, so they share this one
+ * construction site — a divergent trim/star/default here would desync the two phases (the
+ * batch step would insert rows the per-event step never claims, or vice versa).
+ */
+export function buildFlagCalledPersonlessMatcher(
+ flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS
+): (teamId: number) => boolean {
+ return buildIntegerMatcher(flagCalledPersonlessDefaultTeams.trim(), true)
+}
+
+/**
+ * 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.
+ */
+export function eventHasGroups(properties: PluginEvent['properties']): boolean {
+ const groups = properties?.$groups
+ return typeof groups === 'object' && groups !== null && !Array.isArray(groups) && Object.keys(groups).length > 0
+}
+
+/**
+ * Whether a $feature_flag_called event should default to personless so server-side flag
+ * evaluation does not create orphan person profiles (see #60581). Shared by the per-event
+ * step that makes the final decision and the batch step that pre-inserts the
+ * posthog_personlessdistinctid rows.
+ *
+ * `processPersonExplicitlyTrue` must be supplied by the caller because the per-event step
+ * runs after normalizeProcessPerson has stripped $process_person_profile, while the batch
+ * step reads it from the raw event — each reads the signal from the source valid in its
+ * pipeline phase.
+ */
+export function isFlagCalledPersonlessCandidate(
+ event: Pick<PluginEvent, 'event' | 'properties'>,
+ teamId: number,
+ processPersonExplicitlyTrue: boolean,
+ flagCalledDefaultEnabledForTeam: (teamId: number) => boolean
+): boolean {
+ return (
+ event.event === FEATURE_FLAG_CALLED_EVENT &&
+ !processPersonExplicitlyTrue &&
+ !eventHasGroups(event.properties) &&
+ flagCalledDefaultEnabledForTeam(teamId)
+ )
+}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
index 9c483f59b1f4..dda973016c95 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
@@ -1,6 +1,9 @@
import { DateTime } from 'luxon'
-import { buildIntegerMatcher } from '~/config/config'
+import {
+ buildFlagCalledPersonlessMatcher,
+ isFlagCalledPersonlessCandidate,
+} from '~/ingestion/common/flag-called-personless'
import { uuidFromDistinctId } from '~/ingestion/common/person-uuid'
import {
hasInsertedPersonlessDistinctId,
@@ -29,21 +32,6 @@ 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.
*
@@ -61,17 +49,18 @@ function eventHasGroups(properties: PluginEvent['properties']): boolean {
export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(
flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS
): ProcessingStep<TInput, TInput & ProcessPersonlessOutput> {
- const flagCalledDefaultEnabledForTeam = buildIntegerMatcher(flagCalledPersonlessDefaultTeams.trim(), true)
+ const flagCalledDefaultEnabledForTeam = buildFlagCalledPersonlessMatcher(flagCalledPersonlessDefaultTeams)
return async function processPersonlessStep(
input: TInput
): Promise<PipelineResult<TInput & ProcessPersonlessOutput>> {
if (input.processPerson) {
- const mayDefaultFlagCalledToPersonless =
- input.normalizedEvent.event === FEATURE_FLAG_CALLED_EVENT &&
- !input.processPersonExplicitlyTrue &&
- !eventHasGroups(input.normalizedEvent.properties) &&
- flagCalledDefaultEnabledForTeam(input.team.id)
+ const mayDefaultFlagCalledToPersonless = isFlagCalledPersonlessCandidate(
+ input.normalizedEvent,
+ input.team.id,
+ input.processPersonExplicitlyTrue,
+ flagCalledDefaultEnabledForTeam
+ )
if (!mayDefaultFlagCalledToPersonless) {
return ok(input)
@@ -153,10 +142,10 @@ async function applyFeatureFlagCalledPersonlessDefault<TInput extends ProcessPer
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.
+ // The batch step (processPersonlessDistinctIdsBatchStep) pre-inserts flag_called
+ // rows when enabled, but it may be disabled or this distinct ID may be first-seen,
+ // so record it here when the LRU shows no prior insert. 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)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index a4b0f6bbb08a..138cfb6d7fc8 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -188,6 +188,7 @@ export function createJoinedIngestionPipeline<
overflowLaneTTLRefreshService,
featureFlagCalledDedupService,
personsPrefetchEnabled,
+ flagCalledPersonlessDefaultTeams: perDistinctIdOptions.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
hogTransformer,
cdpHogWatcherSampleRate,
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index 45b9b39bcd1f..af744c8f629a 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -48,6 +48,7 @@ export interface PostTeamPreprocessingSubpipelineConfig {
overflowLaneTTLRefreshService?: OverflowRedirectService
featureFlagCalledDedupService?: FeatureFlagCalledDedupService
personsPrefetchEnabled: boolean
+ flagCalledPersonlessDefaultTeams: string
hogTransformer: HogTransformer
cdpHogWatcherSampleRate: number
}
@@ -67,6 +68,7 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
overflowLaneTTLRefreshService,
featureFlagCalledDedupService,
personsPrefetchEnabled,
+ flagCalledPersonlessDefaultTeams,
hogTransformer,
cdpHogWatcherSampleRate,
} = config
@@ -110,11 +112,14 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
// Batch insert personless distinct IDs after prefetch (uses prefetch cache).
// This step awaits its DB write, so retry transient persons-Postgres failures
// (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.
- .pipeBatchWithRetry(processPersonlessDistinctIdsBatchStep(personsPrefetchEnabled), {
- tries: 5,
- sleepMs: 100,
- name: 'personless_distinct_ids',
- })
+ .pipeBatchWithRetry(
+ processPersonlessDistinctIdsBatchStep(personsPrefetchEnabled, flagCalledPersonlessDefaultTeams),
+ {
+ tries: 5,
+ sleepMs: 100,
+ name: 'personless_distinct_ids',
+ }
+ )
// Prefetch hog functions for all teams in the batch
.pipeBatch(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))
)
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts
new file mode 100644
index 000000000000..676d141fef07
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts
@@ -0,0 +1,97 @@
+import { DateTime } from 'luxon'
+
+import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
+import { isOkResult } from '~/ingestion/framework/results'
+import { PluginEvent } from '~/plugin-scaffold'
+import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
+import { createTestTeam } from '~/tests/helpers/team'
+import { Team } from '~/types'
+
+// The batch step (processPersonlessDistinctIdsBatchStep) and the per-event step
+// (processPersonlessStep) are coupled through the module-level LRU in
+// personless-distinct-id-cache: the batch step pre-inserts the posthog_personlessdistinctid
+// row and marks the LRU, so the per-event step finds a hit and skips its own single-row
+// insert. Both steps are dynamically imported after resetModules so they share one fresh LRU.
+describe('flag-called personless batching: batch step → per-event step', () => {
+ let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>
+ let team: Team
+ let processPersonlessDistinctIdsBatchStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep
+ let createProcessPersonlessStep: typeof import('~/ingestion/common/steps/event-processing/process-personless-step').createProcessPersonlessStep
+
+ beforeEach(async () => {
+ jest.resetModules()
+ processPersonlessDistinctIdsBatchStep = (
+ await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.js')
+ ).processPersonlessDistinctIdsBatchStep
+ createProcessPersonlessStep = (
+ await import('~/ingestion/common/steps/event-processing/process-personless-step.js')
+ ).createProcessPersonlessStep
+
+ team = createTestTeam()
+
+ mockPersonsStore = {
+ // No real person exists for the distinct ID under test.
+ fetchForChecking: jest.fn().mockResolvedValue(null),
+ fetchForUpdate: jest.fn().mockResolvedValue(null),
+ getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),
+ addPersonlessDistinctId: jest.fn().mockResolvedValue(false),
+ processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<PersonsStoreForBatch>
+ })
+
+ const flagCalledEvent = (distinctId: string): PluginEvent =>
+ createTestPluginEvent({
+ distinct_id: distinctId,
+ team_id: team.id,
+ event: '$feature_flag_called',
+ properties: {},
+ uuid: `uuid-${distinctId}`,
+ })
+
+ const perEventInput = (event: PluginEvent) => ({
+ normalizedEvent: event,
+ team,
+ timestamp: DateTime.utc(),
+ processPerson: true,
+ processPersonExplicitlyTrue: false,
+ forceDisablePersonProcessing: false,
+ personsStoreForBatch: mockPersonsStore,
+ })
+
+ it('per-event step skips its single-row insert because the batch step already inserted the row', async () => {
+ const event = flagCalledEvent('user-1')
+
+ // Batch step inserts the personless distinct ID and marks the shared LRU.
+ await processPersonlessDistinctIdsBatchStep(
+ true,
+ '*'
+ )([{ event, team, personsStoreForBatch: mockPersonsStore }])
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ ])
+
+ // Per-event step now sees the LRU hit and must NOT do its own single-row insert.
+ const result = await createProcessPersonlessStep('*')(perEventInput(event))
+
+ expect(mockPersonsStore.addPersonlessDistinctId).not.toHaveBeenCalled()
+ expect(isOkResult(result)).toBe(true)
+ if (isOkResult(result)) {
+ // Still defaulted to personless.
+ expect(result.value.processPerson).toBe(false)
+ }
+ })
+
+ it('per-event step falls back to its single-row insert when the batch step did not run', async () => {
+ const event = flagCalledEvent('user-1')
+
+ // No batch step this time, so the LRU is cold.
+ const result = await createProcessPersonlessStep('*')(perEventInput(event))
+
+ expect(mockPersonsStore.addPersonlessDistinctId).toHaveBeenCalledTimes(1)
+ expect(mockPersonsStore.addPersonlessDistinctId).toHaveBeenCalledWith(team.id, 'user-1')
+ expect(isOkResult(result)).toBe(true)
+ if (isOkResult(result)) {
+ expect(result.value.processPerson).toBe(false)
+ }
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.ts
new file mode 100644
index 000000000000..f48cffb9c4a7
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.ts
@@ -0,0 +1,282 @@
+import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { PluginEvent } from '~/plugin-scaffold'
+import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
+import { createTestTeam } from '~/tests/helpers/team'
+import { Team } from '~/types'
+
+describe('processPersonlessDistinctIdsBatchStep', () => {
+ let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>
+ let team: Team
+ let processPersonlessDistinctIdsBatchStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep
+ let personlessDistinctIdCacheOperationsCounter: typeof import('~/ingestion/common/persons/personless-distinct-id-cache').personlessDistinctIdCacheOperationsCounter
+
+ // Reads the freshly-imported counter the step writes to (resetModules gives each test its own).
+ const counterValue = async (operation: string, source: string): Promise<number> => {
+ const metric = await personlessDistinctIdCacheOperationsCounter.get()
+ return metric.values.find((v) => v.labels.operation === operation && v.labels.source === source)?.value ?? 0
+ }
+
+ beforeEach(async () => {
+ // Reset modules to get a fresh LRU cache for each test
+ jest.resetModules()
+ const module = await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.js')
+ processPersonlessDistinctIdsBatchStep = module.processPersonlessDistinctIdsBatchStep
+ // Import the cache module from the same fresh graph so the counter is the one the step increments.
+ personlessDistinctIdCacheOperationsCounter = (
+ await import('~/ingestion/common/persons/personless-distinct-id-cache.js')
+ ).personlessDistinctIdCacheOperationsCounter
+
+ team = createTestTeam()
+
+ mockPersonsStore = {
+ processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),
+ getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),
+ } as unknown as jest.Mocked<PersonsStoreForBatch>
+ })
+
+ const createInput = (
+ distinctId: string,
+ processPerson: boolean | undefined = undefined,
+ overrides: Partial<PluginEvent> = {},
+ eventTeam: Team = team
+ ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } => ({
+ event: createTestPluginEvent({
+ distinct_id: distinctId,
+ team_id: eventTeam.id,
+ properties: processPerson === undefined ? {} : { $process_person_profile: processPerson },
+ uuid: `uuid-${distinctId}`,
+ ...overrides,
+ }),
+ team: eventTeam,
+ personsStoreForBatch: mockPersonsStore,
+ })
+
+ const createFlagCalledInput = (
+ distinctId: string,
+ properties: PluginEvent['properties'] = {},
+ eventTeam: Team = team
+ ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } =>
+ createInput(distinctId, undefined, { event: '$feature_flag_called', properties }, eventTeam)
+
+ describe('when enabled', () => {
+ it('should process personless events and call batch insert', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true)
+ const events = [createInput('user-1', false), createInput('user-2', false), createInput('user-3', false)]
+
+ const results = await step(events)
+
+ expect(results).toHaveLength(3)
+ expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ { teamId: team.id, distinctId: 'user-2' },
+ { teamId: team.id, distinctId: 'user-3' },
+ ])
+ })
+
+ it('should skip non-personless events', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true)
+ const events = [
+ createInput('user-1', true), // processPerson=true
+ createInput('user-2', false), // processPerson=false (personless)
+ createInput('user-3'), // processPerson=undefined (default, not personless)
+ ]
+
+ const results = await step(events)
+
+ expect(results).toHaveLength(3)
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-2' },
+ ])
+ })
+
+ it('should not call batch insert when no personless events', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true)
+ const events = [createInput('user-1', true), createInput('user-2')]
+
+ const results = await step(events)
+
+ expect(results).toHaveLength(2)
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+
+ it('should return all events as OK even if batch insert fails', async () => {
+ mockPersonsStore.processPersonlessDistinctIdsBatch.mockRejectedValue(new Error('DB error'))
+
+ const step = processPersonlessDistinctIdsBatchStep(true)
+ const events = [createInput('user-1', false)]
+
+ // The step should throw since we don't handle errors gracefully
+ await expect(step(events)).rejects.toThrow('DB error')
+ })
+ })
+
+ describe('when disabled', () => {
+ it('should not process any events', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(false)
+ const events = [createInput('user-1', false), createInput('user-2', false)]
+
+ const results = await step(events)
+
+ expect(results).toHaveLength(2)
+ expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('LRU cache behavior', () => {
+ it('should deduplicate entries within same batch before hitting cache', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true)
+ const events = [
+ createInput('user-1', false),
+ createInput('user-1', false), // Duplicate - deduped before cache/insert
+ createInput('user-2', false),
+ ]
+
+ await step(events)
+
+ // Duplicates are removed before batch insert
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ { teamId: team.id, distinctId: 'user-2' },
+ ])
+ })
+
+ it('should use cache to skip already-inserted distinct IDs across batches', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true)
+
+ // First batch
+ await step([createInput('user-1', false)])
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ ])
+
+ mockPersonsStore.processPersonlessDistinctIdsBatch.mockClear()
+
+ // Second batch - user-1 should be cached, only user-2 should be inserted
+ await step([createInput('user-1', false), createInput('user-2', false)])
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-2' },
+ ])
+ })
+ })
+
+ describe('$feature_flag_called batching', () => {
+ it('should batch insert flag-called candidates for enabled teams', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, String(team.id))
+ const events = [createFlagCalledInput('user-1'), createFlagCalledInput('user-2')]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ { teamId: team.id, distinctId: 'user-2' },
+ ])
+ })
+
+ it('should not insert flag-called events when the team is not enabled', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '') // no enabled teams
+ const events = [createFlagCalledInput('user-1')]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+
+ it('should only insert flag-called candidates from teams in the matcher, not others in the same batch', async () => {
+ const otherTeam = createTestTeam({ id: team.id + 1 })
+ const step = processPersonlessDistinctIdsBatchStep(true, String(team.id)) // only `team` enabled
+
+ const events = [
+ createFlagCalledInput('enabled-user'),
+ createFlagCalledInput('other-team-user', {}, otherTeam),
+ ]
+
+ const results = await step(events)
+
+ expect(results).toHaveLength(2)
+ expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
+ // Only the enabled team's distinct ID is inserted; the other team's flag-called event is skipped.
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'enabled-user' },
+ ])
+ })
+
+ it('should support "*" to enable flag-called batching for all teams', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '*')
+ const events = [createFlagCalledInput('user-1')]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ ])
+ })
+
+ it('should skip flag-called events that explicitly set $process_person_profile=true', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '*')
+ const events = [createFlagCalledInput('user-1', { $process_person_profile: true })]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+
+ it('should skip flag-called events carrying group keys', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '*')
+ const events = [createFlagCalledInput('user-1', { $groups: { org: 'acme' } })]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+
+ it('should treat a flag-called event with $process_person_profile=false as explicit-personless', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '') // flag-called batching off
+ const events = [createFlagCalledInput('user-1', { $process_person_profile: false })]
+
+ await step(events)
+
+ // Still inserted via the explicit-personless branch, independent of flag-called enablement.
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ ])
+ })
+
+ it('should batch explicit-personless and flag-called candidates together', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '*')
+ const events = [createInput('user-1', false), createFlagCalledInput('user-2')]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
+ { teamId: team.id, distinctId: 'user-1' },
+ { teamId: team.id, distinctId: 'user-2' },
+ ])
+ })
+
+ it('should not insert flag-called candidates when disabled', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(false, '*')
+ const events = [createFlagCalledInput('user-1')]
+
+ await step(events)
+
+ expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
+ })
+
+ it('should count hits and misses per source on the cache counter', async () => {
+ const step = processPersonlessDistinctIdsBatchStep(true, '*')
+
+ // First batch: one flag-called and one explicit-personless distinct ID, both cold -> one miss each.
+ await step([createFlagCalledInput('ff-1'), createInput('batch-1', false)])
+ // Second batch: ff-1 is warm in the LRU now -> one flag_called hit, no new insert.
+ await step([createFlagCalledInput('ff-1')])
+
+ expect(await counterValue('miss', 'flag_called')).toBe(1)
+ expect(await counterValue('miss', 'batch')).toBe(1)
+ expect(await counterValue('hit', 'flag_called')).toBe(1)
+ expect(await counterValue('hit', 'batch')).toBe(0)
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts
index dafb9e4500c3..ccd4a22dd1aa 100644
--- a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts
@@ -1,9 +1,14 @@
+import {
+ buildFlagCalledPersonlessMatcher,
+ isFlagCalledPersonlessCandidate,
+} from '~/ingestion/common/flag-called-personless'
import {
hasInsertedPersonlessDistinctId,
markPersonlessDistinctIdInserted,
personlessDistinctIdCacheOperationsCounter,
} from '~/ingestion/common/persons/personless-distinct-id-cache'
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
+import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '~/ingestion/config'
import { PipelineResult, ok } from '~/ingestion/framework/results'
import { PipelineEvent, Team } from '~/types'
@@ -13,17 +18,34 @@ type ProcessPersonlessDistinctIdsBatchStepInput = {
personsStoreForBatch: PersonsStoreForBatch
}
+type PersonlessSource = 'batch' | 'flag_called'
+
/**
- * 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
- * is already populated.
+ * Batch step that inserts personless distinct IDs into posthog_personlessdistinctid. This
+ * runs after prefetchPersonsStep (which fires off person-existence fetches in the background)
+ * and before the per-event processPersonlessStep, which awaits those fetches via fetchForChecking
+ * and reads the is_merged results stored here.
+ *
+ * Two kinds of events are inserted, both via the same UNNEST batch insert:
+ * - "batch": events explicitly marked personless ($process_person_profile === false).
+ * - "flag_called": $feature_flag_called events that default to personless for enabled teams
+ * (see #60581). Batching these here avoids one single-row insert per first-seen distinct
+ * ID in processPersonlessStep, which contends on the table's incrementing-integer PK at
+ * high volume. The per-event step still makes the final personless/personful decision; it
+ * just finds the row already inserted (LRU hit) and skips its own insert. The single-row
+ * insert remains the fallback when this step is disabled.
*
- * The batch insert results (is_merged flags) are stored in the personsStore cache
- * and consumed by processPersonlessStep to determine force_upgrade.
+ * Inserting a row for a flag_called distinct ID that turns out to have a real person is
+ * harmless: the explicit-personless path already inserts unconditionally, every reader is
+ * gated on the absence of a real person, and coexistence is the normal post-merge state. So
+ * this step does not need a per-row person check.
*/
export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonlessDistinctIdsBatchStepInput>(
- enabled: boolean
+ enabled: boolean,
+ flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS
) {
+ const flagCalledDefaultEnabledForTeam = buildFlagCalledPersonlessMatcher(flagCalledPersonlessDefaultTeams)
+
return async function processPersonlessDistinctIdsBatchStep(events: T[]): Promise<PipelineResult<T>[]> {
if (enabled) {
// Events in a chunk may come from different Kafka batches (due to the feed primitive).
@@ -31,10 +53,12 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles
// cache. Deduplicate per batch to avoid redundant DB calls within the same batch.
type StoreData = { seenInBatch: Set<string>; entries: { teamId: number; distinctId: string }[] }
const entriesByStore = new Map<PersonsStoreForBatch, StoreData>()
- let cacheHits = 0
+ const cacheHits: Record<PersonlessSource, number> = { batch: 0, flag_called: 0 }
+ const cacheMisses: Record<PersonlessSource, number> = { batch: 0, flag_called: 0 }
for (const e of events) {
- if (e.event.properties?.$process_person_profile !== false) {
+ const source = personlessSource(e, flagCalledDefaultEnabledForTeam)
+ if (source === null) {
continue
}
const cacheKey = `${e.team.id}|${e.event.distinct_id}`
@@ -51,22 +75,25 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles
storeData.seenInBatch.add(cacheKey)
if (hasInsertedPersonlessDistinctId(e.team.id, e.event.distinct_id)) {
- cacheHits++
+ cacheHits[source]++
} else {
+ cacheMisses[source]++
storeData.entries.push({ teamId: e.team.id, distinctId: e.event.distinct_id })
}
}
- if (cacheHits > 0) {
- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source: 'batch' }, cacheHits)
+ for (const source of ['batch', 'flag_called'] as const) {
+ if (cacheHits[source] > 0) {
+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source }, cacheHits[source])
+ }
+ if (cacheMisses[source] > 0) {
+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source }, cacheMisses[source])
+ }
}
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', source: 'batch' }, totalMisses)
-
await Promise.all(
storeCalls.map(async ([store, { entries }]) => {
await store.processPersonlessDistinctIdsBatch(entries)
@@ -80,3 +107,27 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles
return events.map((event) => ok(event))
}
}
+
+function personlessSource(
+ e: ProcessPersonlessDistinctIdsBatchStepInput,
+ flagCalledDefaultEnabledForTeam: (teamId: number) => boolean
+): PersonlessSource | null {
+ const processPersonProfile = e.event.properties?.$process_person_profile
+ if (processPersonProfile === false) {
+ return 'batch'
+ }
+ // The per-event step uses the captured processPersonExplicitlyTrue; this step runs before
+ // normalizeProcessPerson strips the property, so reading it from the raw event is valid.
+ const processPersonExplicitlyTrue = processPersonProfile === true
+ if (
+ isFlagCalledPersonlessCandidate(
+ e.event,
+ e.team.id,
+ processPersonExplicitlyTrue,
+ flagCalledDefaultEnabledForTeam
+ )
+ ) {
+ return 'flag_called'
+ }
+ return null
+}
diff --git a/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts b/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts
deleted file mode 100644
index e8b5ee764a21..000000000000
--- a/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
-import { PipelineResultType } from '~/ingestion/framework/results'
-import { PluginEvent } from '~/plugin-scaffold'
-import { Team } from '~/types'
-
-import { createTestPluginEvent } from '../../../helpers/plugin-event'
-import { createTestTeam } from '../../../helpers/team'
-
-describe('processPersonlessDistinctIdsBatchStep', () => {
- let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>
- let team: Team
- let processPersonlessDistinctIdsBatchStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep
-
- beforeEach(async () => {
- // Reset modules to get a fresh LRU cache for each test
- jest.resetModules()
- const module = await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.js')
- processPersonlessDistinctIdsBatchStep = module.processPersonlessDistinctIdsBatchStep
-
- team = createTestTeam()
-
- mockPersonsStore = {
- processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),
- getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),
- } as unknown as jest.Mocked<PersonsStoreForBatch>
- })
-
- const createInput = (
- distinctId: string,
- processPerson: boolean | undefined = undefined
- ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } => ({
- event: createTestPluginEvent({
- distinct_id: distinctId,
- team_id: team.id,
- properties: processPerson === undefined ? {} : { $process_person_profile: processPerson },
- uuid: `uuid-${distinctId}`,
- }),
- team,
- personsStoreForBatch: mockPersonsStore,
- })
-
- describe('when enabled', () => {
- it('should process personless events and call batch insert', async () => {
- const step = processPersonlessDistinctIdsBatchStep(true)
- const events = [createInput('user-1', false), createInput('user-2', false), createInput('user-3', false)]
-
- const results = await step(events)
-
- expect(results).toHaveLength(3)
- expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- { teamId: team.id, distinctId: 'user-3' },
- ])
- })
-
- it('should skip non-personless events', async () => {
- const step = processPersonlessDistinctIdsBatchStep(true)
- const events = [
- createInput('user-1', true), // processPerson=true
- createInput('user-2', false), // processPerson=false (personless)
- createInput('user-3'), // processPerson=undefined (default, not personless)
- ]
-
- const results = await step(events)
-
- expect(results).toHaveLength(3)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should not call batch insert when no personless events', async () => {
- const step = processPersonlessDistinctIdsBatchStep(true)
- const events = [createInput('user-1', true), createInput('user-2')]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should return all events as OK even if batch insert fails', async () => {
- mockPersonsStore.processPersonlessDistinctIdsBatch.mockRejectedValue(new Error('DB error'))
-
- const step = processPersonlessDistinctIdsBatchStep(true)
- const events = [createInput('user-1', false)]
-
- // The step should throw since we don't handle errors gracefully
- await expect(step(events)).rejects.toThrow('DB error')
- })
- })
-
- describe('when disabled', () => {
- it('should not process any events', async () => {
- const step = processPersonlessDistinctIdsBatchStep(false)
- const events = [createInput('user-1', false), createInput('user-2', false)]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
- })
-
- describe('LRU cache behavior', () => {
- it('should deduplicate entries within same batch before hitting cache', async () => {
- const step = processPersonlessDistinctIdsBatchStep(true)
- const events = [
- createInput('user-1', false),
- createInput('user-1', false), // Duplicate - deduped before cache/insert
- createInput('user-2', false),
- ]
-
- await step(events)
-
- // Duplicates are removed before batch insert
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should use cache to skip already-inserted distinct IDs across batches', async () => {
- const step = processPersonlessDistinctIdsBatchStep(true)
-
- // First batch
- await step([createInput('user-1', false)])
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- ])
-
- mockPersonsStore.processPersonlessDistinctIdsBatch.mockClear()
-
- // Second batch - user-1 should be cached, only user-2 should be inserted
- await step([createInput('user-1', false), createInput('user-2', false)])
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
- })
-})