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.

feat(ingestion): fold $identify merge storms into single transactions (#72823)

José Sequeira72cb85bf3675
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.ts
index a063c86f4473..7e03c88a1ba7 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.test.ts
@@ -74,7 +74,10 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {
fetchPerson: jest.fn(),
fetchPersonsByDistinctIds: jest.fn(),
fetchPersonsByPersonIds: jest.fn(),
+ fetchPersonsForUpdateByDistinctIds: jest.fn(),
fetchDistinctIdsForPersons: jest.fn(),
+ deletePersons: jest.fn(),
+ updateCohortsAndFeatureFlagsForMergeBatch: jest.fn(),
createPerson: jest.fn(),
updatePerson: jest.fn(),
updatePersonAssertVersion: jest.fn(),
diff --git a/nodejs/src/common/personhog/personhog-person-repository.ts b/nodejs/src/common/personhog/personhog-person-repository.ts
index 175eaf85aa7b..9e034becc4cd 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.ts
@@ -125,6 +125,15 @@ export class PersonHogPersonRepository implements PersonRepository {
}
}
+ fetchPersonsForUpdateByDistinctIds(
+ teamId: TeamId,
+ distinctIds: string[],
+ callerTag?: string
+ ): Promise<InternalPersonWithDistinctId[]> {
+ // Locking read — always Postgres, like fetchPerson({forUpdate: true}).
+ return this.postgres.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, callerTag)
+ }
+
async fetchDistinctIdsForPersons(
teamId: TeamId,
personIntIds: string[],
@@ -203,6 +212,10 @@ export class PersonHogPersonRepository implements PersonRepository {
return this.postgres.deletePerson(person)
}
+ deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]> {
+ return this.postgres.deletePersons(persons)
+ }
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return this.postgres.addDistinctId(person, distinctId, version)
}
@@ -223,6 +236,14 @@ export class PersonHogPersonRepository implements PersonRepository {
return this.postgres.personPropertiesSize(personId, teamId)
}
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id']
+ ): Promise<void> {
+ return this.postgres.updateCohortsAndFeatureFlagsForMergeBatch(teamID, sourcePersonIDs, targetPersonID)
+ }
+
updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
diff --git a/nodejs/src/common/persons/person-utils.ts b/nodejs/src/common/persons/person-utils.ts
new file mode 100644
index 000000000000..7409ea711d26
--- /dev/null
+++ b/nodejs/src/common/persons/person-utils.ts
@@ -0,0 +1,73 @@
+import { PluginEvent } from '~/plugin-scaffold'
+import { EventHeaders, PipelineEvent } from '~/types'
+
+export type ProcessPersonDecision =
+ /** Person processing enabled; `invalid` is set when $process_person_profile held a non-boolean value that was ignored. */
+ | { processPerson: true; invalid?: { value: unknown } }
+ /** Person processing disabled, by the capture-set force-disable header or an explicit `$process_person_profile: false` property. */
+ | { processPerson: false; reason: 'header' | 'property' }
+
+/**
+ * The single source of truth for whether an event gets person processing:
+ * the force-disable header wins outright, otherwise only a strict boolean
+ * `false` in $process_person_profile disables it; any other non-boolean
+ * value is invalid and falls back to the default (enabled).
+ */
+export function decideProcessPerson(event: PipelineEvent | PluginEvent, headers: EventHeaders): ProcessPersonDecision {
+ if (headers.force_disable_person_processing === true) {
+ return { processPerson: false, reason: 'header' }
+ }
+ if (event.properties && '$process_person_profile' in event.properties) {
+ const propValue = event.properties.$process_person_profile
+ if (propValue === false) {
+ return { processPerson: false, reason: 'property' }
+ }
+ if (propValue !== true) {
+ return { processPerson: true, invalid: { value: propValue } }
+ }
+ }
+ return { processPerson: true }
+}
+
+// used to prevent identify from being used with generic IDs
+// that we can safely assume stem from a bug or mistake
+const BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [
+ 'anonymous',
+ 'guest',
+ 'distinctid',
+ 'distinct_id',
+ 'id',
+ 'not_authenticated',
+ 'email',
+ 'undefined',
+ 'true',
+ 'false',
+]
+
+const BARE_CASE_SENSITIVE_ILLEGAL_IDS = ['[object Object]', 'NaN', 'None', 'none', 'null', '0', 'undefined']
+
+// we have seen illegal ids received but wrapped in double quotes
+// to protect ourselves from this we'll add the single- and double-quoted versions of the illegal ids
+const singleQuoteIds = (ids: string[]) => ids.map((id) => `'${id}'`)
+const doubleQuoteIds = (ids: string[]) => ids.map((id) => `"${id}"`)
+
+// some ids are illegal regardless of casing
+// while others are illegal only when cased
+// so, for example, we want to forbid `NaN` but not `nan`
+// but, we will forbid `uNdEfInEd` and `undefined`
+const CASE_INSENSITIVE_ILLEGAL_IDS = new Set(
+ BARE_CASE_INSENSITIVE_ILLEGAL_IDS.concat(singleQuoteIds(BARE_CASE_INSENSITIVE_ILLEGAL_IDS)).concat(
+ doubleQuoteIds(BARE_CASE_INSENSITIVE_ILLEGAL_IDS)
+ )
+)
+
+const CASE_SENSITIVE_ILLEGAL_IDS = new Set(
+ BARE_CASE_SENSITIVE_ILLEGAL_IDS.concat(singleQuoteIds(BARE_CASE_SENSITIVE_ILLEGAL_IDS)).concat(
+ doubleQuoteIds(BARE_CASE_SENSITIVE_ILLEGAL_IDS)
+ )
+)
+
+export const isDistinctIdIllegal = (id: string): boolean => {
+ const trimmed = id.trim()
+ return trimmed === '' || CASE_INSENSITIVE_ILLEGAL_IDS.has(id.toLowerCase()) || CASE_SENSITIVE_ILLEGAL_IDS.has(id)
+}
diff --git a/nodejs/src/common/persons/repositories/person-repository-transaction.ts b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
index aa1f27668034..b47d1bdde7f9 100644
--- a/nodejs/src/common/persons/repositories/person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
@@ -27,10 +27,19 @@ export interface PersonRepositoryTransaction {
deletePerson(person: InternalPerson): Promise<PersonMessage[]>
+ /** Batched deletePerson for folded merges; all persons must belong to one team. */
+ deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
moveDistinctIds(source: InternalPerson, target: InternalPerson, limit?: number): Promise<MoveDistinctIdsResult>
+ /** Batched unlimited moveDistinctIds for folded merges; zero moved rows for a source is not a failure. */
+ moveDistinctIdsFromPersons(sources: InternalPerson[], target: InternalPerson): Promise<MoveDistinctIdsResult>
+
+ /** Distinct-id counts per person id (single team), for the folded-merge limit pre-check. */
+ countDistinctIdsForPersons(teamId: Team['id'], personIds: InternalPerson['id'][]): Promise<Map<string, number>>
+
fetchPersonDistinctIds(person: InternalPerson, limit?: number): Promise<string[]>
addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string): Promise<boolean>
@@ -40,4 +49,10 @@ export interface PersonRepositoryTransaction {
sourcePersonID: InternalPerson['id'],
targetPersonID: InternalPerson['id']
): Promise<void>
+
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamId: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id']
+ ): Promise<void>
}
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index b2fb17af7f2b..f27022c6602b 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -86,6 +86,17 @@ export interface PersonRepository {
callerTag?: string
): Promise<InternalPerson[]>
+ /**
+ * Batched, row-locking variant of fetchPerson({forUpdate: true}) for folded
+ * merges: resolves and locks all persons behind the given distinct_ids in
+ * one statement, in deterministic (person id) lock order.
+ */
+ fetchPersonsForUpdateByDistinctIds(
+ teamId: TeamId,
+ distinctIds: string[],
+ callerTag?: string
+ ): Promise<InternalPersonWithDistinctId[]>
+
/**
* Fetch up to ``limitPerPerson`` distinct_ids for each given int person_id (single team).
* Returns a record keyed by int person_id as a string (matching InternalPerson.id).
@@ -132,6 +143,9 @@ export interface PersonRepository {
deletePerson(person: InternalPerson): Promise<PersonMessage[]>
+ /** Batched deletePerson for folded merges; all persons must belong to one team. */
+ deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
addPersonlessDistinctId(teamId: Team['id'], distinctId: string): Promise<boolean>
@@ -146,5 +160,11 @@ export interface PersonRepository {
targetPersonID: InternalPerson['id']
): Promise<void>
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id']
+ ): Promise<void>
+
inTransaction<T>(description: string, transaction: (tx: PersonRepositoryTransaction) => Promise<T>): Promise<T>
}
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
index 1774499d59a2..7741fceb5dc5 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
@@ -54,6 +54,10 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
return await this.repository.deletePerson(person, this.transaction)
}
+ async deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]> {
+ return await this.repository.deletePersons(persons, this.transaction)
+ }
+
async addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return await this.repository.addDistinctId(person, distinctId, version, this.transaction)
}
@@ -66,6 +70,20 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
return await this.repository.moveDistinctIds(source, target, limit, this.transaction)
}
+ async moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson
+ ): Promise<MoveDistinctIdsResult> {
+ return await this.repository.moveDistinctIdsFromPersons(sources, target, this.transaction)
+ }
+
+ async countDistinctIdsForPersons(
+ teamID: Team['id'],
+ personIds: InternalPerson['id'][]
+ ): Promise<Map<string, number>> {
+ return await this.repository.countDistinctIdsForPersons(teamID, personIds, this.transaction)
+ }
+
async fetchPersonDistinctIds(person: InternalPerson, limit?: number): Promise<string[]> {
return await this.repository.fetchPersonDistinctIds(person, limit, this.transaction)
}
@@ -86,4 +104,17 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
this.transaction
)
}
+
+ async updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id']
+ ): Promise<void> {
+ return await this.repository.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ this.transaction
+ )
+ }
}
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index 821a3e786817..19f5fc6dc3b3 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -2849,6 +2849,170 @@ describe('PostgresPersonRepository', () => {
expect(observeCalls).toHaveLength(3)
})
})
+
+ describe('fetchPersonsForUpdateByDistinctIds()', () => {
+ it('returns empty array for empty input', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ expect(await repository.fetchPersonsForUpdateByDistinctIds(team.id, [])).toEqual([])
+ })
+
+ it('resolves and locks multiple distinct ids in one query', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person1 = await createTestPerson(team.id, 'fold-anon-1', { name: 'One' })
+ const person2 = await createTestPerson(team.id, 'fold-anon-2', { name: 'Two' })
+ await repository.addDistinctId(person1, 'fold-anon-1b', 0)
+
+ const rows = await repository.fetchPersonsForUpdateByDistinctIds(team.id, [
+ 'fold-anon-1',
+ 'fold-anon-1b',
+ 'fold-anon-2',
+ 'fold-missing',
+ ])
+
+ expect(rows).toHaveLength(3)
+ const byDistinctId = Object.fromEntries(rows.map((row) => [row.distinct_id, row.uuid]))
+ expect(byDistinctId).toEqual({
+ 'fold-anon-1': person1.uuid,
+ 'fold-anon-1b': person1.uuid,
+ 'fold-anon-2': person2.uuid,
+ })
+ })
+ })
+
+ describe('moveDistinctIdsFromPersons()', () => {
+ it('moves all distinct ids from multiple sources to the target', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const source1 = await createTestPerson(team.id, 'fold-source-1', {})
+ const source2 = await createTestPerson(team.id, 'fold-source-2', {})
+ const target = await createTestPerson(team.id, 'fold-target', {})
+ await repository.addDistinctId(source1, 'fold-source-1b', 0)
+
+ const result = await repository.moveDistinctIdsFromPersons([source1, source2], target)
+
+ expect(result.success).toBe(true)
+ if (result.success) {
+ expect(result.distinctIdsMoved.sort()).toEqual(['fold-source-1', 'fold-source-1b', 'fold-source-2'])
+ for (const message of result.messages) {
+ const messageValue = parseJSON(message.value!.toString())
+ expect(messageValue).toMatchObject({ person_id: target.uuid, team_id: team.id, is_deleted: 0 })
+ }
+ }
+
+ const targetDistinctIds = await fetchDistinctIdValues(hub.postgres, target)
+ expect(targetDistinctIds.sort()).toEqual([
+ 'fold-source-1',
+ 'fold-source-1b',
+ 'fold-source-2',
+ 'fold-target',
+ ])
+ })
+
+ it('treats sources without distinct ids as satisfied rather than failing', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const source = await createTestPerson(team.id, 'fold-source-gone', {})
+ const target = await createTestPerson(team.id, 'fold-target-2', {})
+
+ // Simulate a concurrently completed merge: source's ids were already moved
+ await repository.moveDistinctIds(source, target, undefined)
+ const result = await repository.moveDistinctIdsFromPersons([source], target)
+
+ expect(result.success).toBe(true)
+ if (result.success) {
+ expect(result.distinctIdsMoved).toEqual([])
+ expect(result.messages).toEqual([])
+ }
+ })
+
+ it('returns success with no work for empty sources', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const target = await createTestPerson(team.id, 'fold-target-3', {})
+
+ const result = await repository.moveDistinctIdsFromPersons([], target)
+
+ expect(result).toEqual({ success: true, messages: [], distinctIdsMoved: [] })
+ })
+ })
+
+ describe('deletePersons()', () => {
+ it('deletes multiple persons and returns one deletion message each', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person1 = await createTestPerson(team.id, 'fold-delete-1', {})
+ const person2 = await createTestPerson(team.id, 'fold-delete-2', {})
+ // Distinct ids reference persons via FK; clear them before deletion
+ const target = await createTestPerson(team.id, 'fold-delete-target', {})
+ await repository.moveDistinctIdsFromPersons([person1, person2], target)
+
+ const messages = await repository.deletePersons([person1, person2])
+
+ expect(messages).toHaveLength(2)
+ const deletedUuids = messages.map((message) => parseJSON(message.value!.toString()).id).sort()
+ expect(deletedUuids).toEqual([person1.uuid, person2.uuid].sort())
+ expect(await fetchPersonByPersonId(hub, team.id, person1.id)).toBeUndefined()
+ expect(await fetchPersonByPersonId(hub, team.id, person2.id)).toBeUndefined()
+ })
+
+ it('returns no messages for already-deleted persons and empty input', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'fold-delete-3', {})
+ const target = await createTestPerson(team.id, 'fold-delete-target-2', {})
+ await repository.moveDistinctIdsFromPersons([person], target)
+ await repository.deletePerson(person)
+
+ expect(await repository.deletePersons([person])).toEqual([])
+ expect(await repository.deletePersons([])).toEqual([])
+ })
+ })
+
+ describe('updateCohortsAndFeatureFlagsForMergeBatch()', () => {
+ it('moves overrides from multiple sources, keeping target values on conflict', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const source1 = await createTestPerson(team.id, 'fold-ff-source-1', {})
+ const source2 = await createTestPerson(team.id, 'fold-ff-source-2', {})
+ const target = await createTestPerson(team.id, 'fold-ff-target', {})
+
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: source1.id,
+ feature_flag_key: 'aloha',
+ hash_key: 'source1_aloha',
+ })
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: source2.id,
+ feature_flag_key: 'beta-feature',
+ hash_key: 'source2_beta',
+ })
+ await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
+ team_id: team.id,
+ person_id: target.id,
+ feature_flag_key: 'beta-feature',
+ hash_key: 'target_beta',
+ })
+
+ await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [source1.id, source2.id], target.id)
+
+ const result = await hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride',
+ [],
+ ''
+ )
+ expect(result.rows).toEqual(
+ expect.arrayContaining([
+ { feature_flag_key: 'aloha', hash_key: 'source1_aloha', person_id: target.id },
+ { feature_flag_key: 'beta-feature', hash_key: 'target_beta', person_id: target.id },
+ ])
+ )
+ expect(result.rows).toHaveLength(2)
+ })
+
+ it('is a no-op for empty sources', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const target = await createTestPerson(team.id, 'fold-ff-target-2', {})
+
+ await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [], target.id)
+ })
+ })
})
// Helper function from the original test file
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index 60f384999940..824a59d1dcab 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -331,6 +331,58 @@ export class PostgresPersonRepository
}))
}
+ async fetchPersonsForUpdateByDistinctIds(
+ teamId: number,
+ distinctIds: string[],
+ callerTag?: string
+ ): Promise<InternalPersonWithDistinctId[]> {
+ if (distinctIds.length === 0) {
+ return []
+ }
+
+ const uniqueDistinctIds = [...new Set(distinctIds)]
+
+ // ORDER BY person id gives concurrent multi-row lockers a deterministic
+ // lock order, minimizing deadlocks between folded merges on overlapping
+ // persons.
+ const queryString = `SELECT
+ posthog_person.id,
+ posthog_person.uuid,
+ posthog_person.created_at,
+ posthog_person.team_id,
+ posthog_person.properties,
+ posthog_person.properties_last_updated_at,
+ posthog_person.properties_last_operation,
+ posthog_person.is_user_id,
+ posthog_person.version,
+ posthog_person.is_identified,
+ posthog_person.last_seen_at,
+ posthog_persondistinctid.distinct_id
+ FROM posthog_person
+ JOIN posthog_persondistinctid ON (
+ posthog_persondistinctid.person_id = posthog_person.id
+ AND posthog_persondistinctid.team_id = posthog_person.team_id
+ )
+ WHERE
+ posthog_person.team_id = $1
+ AND posthog_persondistinctid.team_id = $1
+ AND posthog_persondistinctid.distinct_id = ANY($2::text[])
+ ORDER BY posthog_person.id
+ FOR UPDATE`
+
+ const { rows } = await this.postgres.query<RawPerson & { distinct_id: string }>(
+ PostgresUse.PERSONS_WRITE,
+ queryString,
+ [teamId, uniqueDistinctIds],
+ queryTag('fetchPersonsForUpdateByDistinctIds', callerTag)
+ )
+
+ return rows.map((row) => ({
+ ...this.toPerson(row),
+ distinct_id: row.distinct_id,
+ }))
+ }
+
async fetchPersonsByPersonIds(
teamPersons: { teamId: TeamId; personId: string }[],
useReadReplica: boolean = true,
@@ -641,6 +693,49 @@ export class PostgresPersonRepository
return kafkaMessages
}
+ async deletePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]> {
+ if (persons.length === 0) {
+ return []
+ }
+
+ // All persons in a folded merge belong to one team.
+ const teamId = persons[0].team_id
+ const personById = new Map(persons.map((person) => [person.id, person]))
+ // Postgres acquires the row locks in index scan order (btree scans sort
+ // the id keys ascending), not in array-parameter order, so concurrent
+ // folds deleting overlapping persons lock in a consistent order either
+ // way; sorting here just keeps the parameter and logs deterministic.
+ const personIds = [...personById.keys()].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1))
+
+ let rows: { id: string; version: string }[] = []
+ try {
+ const result = await this.postgres.query<{ id: string; version: string }>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ 'DELETE FROM posthog_person WHERE team_id = $1 AND id = ANY($2::bigint[]) RETURNING id, version',
+ [teamId, personIds],
+ 'deletePersons'
+ )
+ rows = result.rows
+ } catch (error) {
+ if (error.code === '40P01') {
+ // Deadlock detected — assume someone else is deleting and skip.
+ logger.warn('🔒', 'Deadlock detected — assume someone else is deleting and skip.', {
+ team_id: teamId,
+ person_ids: personIds,
+ })
+ }
+ throw error
+ }
+
+ return rows.flatMap((row) => {
+ const person = personById.get(String(row.id))
+ if (!person) {
+ return []
+ }
+ return [generateKafkaPersonUpdateMessage({ ...person, version: Number(row.version || 0) }, true)]
+ })
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
@@ -776,6 +871,97 @@ export class PostgresPersonRepository
}
}
+ async countDistinctIdsForPersons(
+ teamId: number,
+ personIds: string[],
+ tx?: TransactionClient
+ ): Promise<Map<string, number>> {
+ if (personIds.length === 0) {
+ return new Map()
+ }
+ const { rows } = await this.postgres.query<{ person_id: string; count: string }>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `SELECT person_id, count(*) AS count
+ FROM posthog_persondistinctid
+ WHERE team_id = $1 AND person_id = ANY($2::bigint[])
+ GROUP BY person_id`,
+ [teamId, personIds],
+ 'countDistinctIdsForPersons'
+ )
+ return new Map(rows.map((row) => [String(row.person_id), Number(row.count)]))
+ }
+
+ async moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ tx?: TransactionClient
+ ): Promise<MoveDistinctIdsResult> {
+ if (sources.length === 0) {
+ return { success: true, messages: [], distinctIdsMoved: [] }
+ }
+
+ // Sorted ids keep the row-lock acquisition order deterministic across
+ // concurrent folded merges touching overlapping source persons.
+ const sourceIds = sources.map((source) => source.id).sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1))
+
+ let movedDistinctIdResult: QueryResult<any> | null = null
+ try {
+ movedDistinctIdResult = await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `UPDATE posthog_persondistinctid
+ SET person_id = $1, version = COALESCE(version, 0)::numeric + 1
+ WHERE person_id = ANY($2::bigint[])
+ AND team_id = $3
+ RETURNING *`,
+ [target.id, sourceIds, target.team_id],
+ 'updateDistinctIdPersonFold'
+ )
+ } catch (error) {
+ if (
+ (error as Error).message.includes(
+ 'insert or update on table "posthog_persondistinctid" violates foreign key constraint'
+ )
+ ) {
+ // Same race as moveDistinctIds: the target person was deleted
+ // between fetch and update; the caller retries with fresh data.
+ logger.warn('😵', 'Target person no longer exists', {
+ team_id: target.team_id,
+ person_id: target.id,
+ })
+ moveDistinctIdsCountHistogram.observe(0)
+ return {
+ success: false,
+ error: 'TargetNotFound',
+ }
+ }
+
+ throw error
+ }
+
+ // Unlike the single-source variant, zero moved rows for a source is not
+ // a failure here: a concurrently completed merge may have already moved
+ // it, which the folded merge treats as satisfied.
+ const kafkaMessages = []
+ for (const row of movedDistinctIdResult.rows) {
+ const { id, version: versionStr, ...usefulColumns } = row as PersonDistinctId
+ const version = Number(versionStr || 0)
+ kafkaMessages.push({
+ output: PERSON_DISTINCT_IDS_OUTPUT,
+ value: Buffer.from(
+ JSON.stringify({ ...usefulColumns, version, person_id: target.uuid, is_deleted: 0 })
+ ),
+ })
+ }
+
+ moveDistinctIdsCountHistogram.observe(movedDistinctIdResult.rows.length)
+
+ return {
+ success: true,
+ messages: kafkaMessages,
+ distinctIdsMoved: movedDistinctIdResult.rows.map((row) => row.distinct_id),
+ }
+ }
+
async fetchPersonDistinctIds(person: InternalPerson, limit?: number, tx?: TransactionClient): Promise<string[]> {
const hasLimit = limit !== undefined
const queryString = hasLimit
@@ -1287,6 +1473,40 @@ export class PostgresPersonRepository
)
}
+ async updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ tx?: TransactionClient
+ ): Promise<void> {
+ if (sourcePersonIDs.length === 0) {
+ return
+ }
+
+ // Multi-source variant of updateCohortsAndFeatureFlagsForMerge — same
+ // two operations, one round-trip for all folded source persons.
+ await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `WITH cohort_update AS (
+ UPDATE posthog_cohortpeople
+ SET person_id = $1
+ WHERE person_id = ANY($2::bigint[])
+ RETURNING person_id
+ ),
+ deletions AS (
+ DELETE FROM posthog_featureflaghashkeyoverride
+ WHERE team_id = $3 AND person_id = ANY($2::bigint[])
+ RETURNING team_id, person_id, feature_flag_key, hash_key
+ )
+ INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)
+ SELECT team_id, $1, feature_flag_key, hash_key
+ FROM deletions
+ ON CONFLICT DO NOTHING`,
+ [targetPersonID, sourcePersonIDs, teamID],
+ 'updateCohortAndFeatureFlagsPeopleBatch'
+ )
+ }
+
async inTransaction<T>(
description: string,
transaction: (tx: PersonRepositoryTransaction) => Promise<T>
diff --git a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
index 9ebea6737576..180e98996d6e 100644
--- a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
@@ -57,6 +57,9 @@ export interface RawPostgresPersonRepository {
deletePerson(person: InternalPerson, tx?: TransactionClient): Promise<PersonMessage[]>
+ /** Batched deletePerson for folded merges; all persons must belong to one team. */
+ deletePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]>
+
addDistinctId(
person: InternalPerson,
distinctId: string,
@@ -71,6 +74,20 @@ export interface RawPostgresPersonRepository {
tx?: TransactionClient
): Promise<MoveDistinctIdsResult>
+ /** Batched unlimited moveDistinctIds for folded merges; zero moved rows for a source is not a failure. */
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ tx?: TransactionClient
+ ): Promise<MoveDistinctIdsResult>
+
+ /** Distinct-id counts per person id (single team), for the folded-merge limit pre-check. */
+ countDistinctIdsForPersons(
+ teamId: number,
+ personIds: string[],
+ tx?: TransactionClient
+ ): Promise<Map<string, number>>
+
fetchPersonDistinctIds(person: InternalPerson, limit?: number, tx?: TransactionClient): Promise<string[]>
addPersonlessDistinctId(teamId: Team['id'], distinctId: string, tx?: TransactionClient): Promise<boolean>
addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string, tx?: TransactionClient): Promise<boolean>
@@ -84,5 +101,12 @@ export interface RawPostgresPersonRepository {
tx?: TransactionClient
): Promise<void>
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ tx?: TransactionClient
+ ): Promise<void>
+
inRawTransaction<T>(description: string, transaction: (tx: TransactionClient) => Promise<T>): Promise<T>
}
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
index 15b2c78c2685..28146a062feb 100644
--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
@@ -400,7 +400,7 @@ export class CommonTeamStage<
groupingFn: GroupingFunction<TCurrent, TKey>,
callback: (
group: GroupProcessingBuilder<TPost, TCurrent, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>
- ) => ChunkPipelineBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>,
+ ) => GroupProcessingBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>,
options?: { maxConcurrency?: number }
): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
const committed = this.chain.build()
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index be3b68d29c6c..9c9ecd4f762f 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -125,7 +125,10 @@ describe('BatchWritingPersonStore', () => {
fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),
fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),
fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),
+ fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),
fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
+ deletePersons: jest.fn().mockResolvedValue([]),
+ updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
createPerson: jest.fn().mockResolvedValue([person, []]),
updatePerson: jest.fn().mockResolvedValue([person, [], false]),
updatePersonAssertVersion: jest.fn().mockResolvedValue([person.version + 1, []]),
@@ -162,10 +165,16 @@ describe('BatchWritingPersonStore', () => {
createPerson: jest.fn().mockResolvedValue([person, []]),
updatePerson: jest.fn().mockResolvedValue([person, [], false]),
deletePerson: jest.fn().mockResolvedValue([]),
+ deletePersons: jest.fn().mockResolvedValue([]),
addDistinctId: jest.fn().mockResolvedValue([]),
moveDistinctIds: jest.fn().mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
+ moveDistinctIdsFromPersons: jest
+ .fn()
+ .mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
addPersonlessDistinctIdForMerge: jest.fn().mockResolvedValue(true),
updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),
+ updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
+ countDistinctIdsForPersons: jest.fn().mockResolvedValue(new Map()),
}
return mockTransaction
}
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index ca88df5b53cd..c556496b54d3 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -22,6 +22,7 @@ import {
import { isFilteredPersonUpdateProperty } from '~/common/persons/person-property-utils'
import { PersonUpdate, fromInternalPerson, toInternalPerson } from '~/common/persons/person-update-batch'
import {
+ InternalPersonWithDistinctId,
PersonMessage,
PersonPropertiesSizeViolationError,
PersonRepository,
@@ -52,10 +53,15 @@ type MethodName =
| 'updatePersonWithPropertiesDiffForUpdate'
| 'updatePersonForMerge'
| 'deletePerson'
+ | 'deletePersons'
| 'addDistinctId'
| 'moveDistinctIds'
+ | 'moveDistinctIdsFromPersons'
+ | 'fetchPersonsForUpdateByDistinctIds'
+ | 'countDistinctIdsForPersons'
| 'fetchPersonDistinctIds'
| 'updateCohortsAndFeatureFlagsForMerge'
+ | 'updateCohortsAndFeatureFlagsForMergeBatch'
| 'addPersonlessDistinctId'
| 'addPersonlessDistinctIdForMerge'
| 'addPersonUpdateToBatch'
@@ -1393,6 +1399,58 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return response
}
+ async fetchPersonsForUpdateByDistinctIds(
+ teamId: Team['id'],
+ distinctIds: string[],
+ batchId: number
+ ): Promise<InternalPersonWithDistinctId[]> {
+ if (distinctIds.length === 0) {
+ return []
+ }
+ this.incrementCount('fetchPersonsForUpdateByDistinctIds', distinctIds[0])
+ this.incrementDatabaseOperation('fetchPersonsForUpdateByDistinctIds', distinctIds[0])
+ const rows = await this.personRepository.fetchPersonsForUpdateByDistinctIds(
+ teamId,
+ distinctIds,
+ 'ingestion/merge-fold'
+ )
+
+ // Populate the per-batch update cache so later events for these
+ // distinct ids in the same batch skip their own fetch.
+ const cache = this.personCache.obtainForBatchId(batchId)
+ for (const row of rows) {
+ const { distinct_id, ...person } = row
+ cache.setCachedPersonForUpdate(teamId, distinct_id, fromInternalPerson(person, distinct_id))
+ }
+
+ return rows
+ }
+
+ async deletePersons(
+ persons: InternalPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ this.incrementCount('deletePersons', distinctId)
+ this.incrementDatabaseOperation('deletePersons', distinctId)
+ const start = performance.now()
+ const personsToDelete = persons.map((person) => {
+ const cachedPersonUpdate = this.getCachedPersonForUpdateByPersonId(person.team_id, person.id)
+ return cachedPersonUpdate ? toInternalPerson(cachedPersonUpdate) : person
+ })
+
+ const response = await (tx || this.personRepository).deletePersons(personsToDelete)
+ if (persons.length > 0) {
+ observeLatencyByVersion(persons[0], start, 'deletePersons')
+ }
+
+ for (const person of persons) {
+ this.clearAllCachesForPersonId(person.team_id, person.id)
+ }
+
+ return response
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
@@ -1447,6 +1505,51 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return response
}
+ async moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ tx: PersonRepositoryTransaction,
+ batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ this.incrementCount('moveDistinctIdsFromPersons', distinctId)
+ this.incrementDatabaseOperation('moveDistinctIdsFromPersons', distinctId)
+ const start = performance.now()
+ const response = await tx.moveDistinctIdsFromPersons(sources, target)
+ observeLatencyByVersion(target, start, 'moveDistinctIdsFromPersons')
+
+ for (const source of sources) {
+ this.clearAllCachesForPersonId(source.team_id, source.id)
+ }
+
+ // Mirror moveDistinctIds' target-cache handling for the triggering distinct id
+ const existingTargetCache = this.getCachedPersonForUpdateByPersonId(target.team_id, target.id)
+ if (existingTargetCache) {
+ const mergedPersonUpdate = { ...existingTargetCache, distinct_id: distinctId }
+ this.setCachedPersonForUpdate(target.team_id, distinctId, mergedPersonUpdate, batchId)
+ } else {
+ this.setCachedPersonForUpdate(target.team_id, distinctId, fromInternalPerson(target, distinctId), batchId)
+ }
+ if (response.success) {
+ for (const movedDistinctId of response.distinctIdsMoved) {
+ this.setDistinctIdToPersonId(target.team_id, movedDistinctId, target.id, batchId)
+ }
+ }
+
+ return response
+ }
+
+ async countDistinctIdsForPersons(
+ teamID: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<Map<string, number>> {
+ this.incrementCount('countDistinctIdsForPersons', distinctId)
+ this.incrementDatabaseOperation('countDistinctIdsForPersons', distinctId)
+ return await tx.countDistinctIdsForPersons(teamID, personIds)
+ }
+
async fetchPersonDistinctIds(
person: InternalPerson,
distinctId: string,
@@ -1473,6 +1576,21 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
await (tx || this.personRepository).updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID)
}
+ async updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ this.incrementCount('updateCohortsAndFeatureFlagsForMergeBatch', distinctId)
+ await (tx || this.personRepository).updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID
+ )
+ }
+
async addPersonlessDistinctId(teamId: Team['id'], distinctId: string, batchId: number): Promise<boolean> {
this.incrementCount('addPersonlessDistinctId', distinctId)
const isMerged = await this.personRepository.addPersonlessDistinctId(teamId, distinctId)
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index e9bd7cec57d0..5c88407b531b 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -15,6 +15,7 @@ import { PluginEvent, Properties } from '~/plugin-scaffold'
import { InternalPerson, Team, ValueMatcher } from '~/types'
import { buildPersonMergeEventMessage } from './person-merge-event'
+import type { MergeFoldPlan } from './person-merge-fold'
import { MergeMode } from './person-merge-types'
import { PersonsStoreForBatch } from './persons-store-for-batch'
@@ -62,7 +63,9 @@ export class PersonContext {
enabled: false,
partitionCount: 64,
isTeamEnabled: () => false,
- }
+ },
+ /** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */
+ public readonly mergeFoldPlan?: MergeFoldPlan
) {
this.eventProperties = event.properties!
}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts
new file mode 100644
index 000000000000..99a177abd999
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts
@@ -0,0 +1,207 @@
+import { isOkResult } from '~/ingestion/framework/results'
+import { PluginEvent } from '~/plugin-scaffold'
+import { EventHeaders, Team } from '~/types'
+
+import {
+ MergeFoldPlan,
+ MergeFoldScanItem,
+ WithMergeFoldDecision,
+ createMergeFoldPlanningStep,
+} from './person-merge-fold'
+
+describe('createMergeFoldPlanningStep', () => {
+ const team = { id: 7 } as Team
+
+ let uuidCounter: number
+
+ beforeEach(() => {
+ uuidCounter = 0
+ })
+
+ function identify(anonDistinctId: string, distinctId = 'user-1'): MergeFoldScanItem {
+ return event('$identify', distinctId, { $anon_distinct_id: anonDistinctId })
+ }
+
+ function event(
+ name: string,
+ distinctId = 'user-1',
+ properties: Record<string, unknown> = {},
+ headers: Partial<EventHeaders> = {}
+ ): MergeFoldScanItem {
+ return {
+ event: {
+ event: name,
+ distinct_id: distinctId,
+ uuid: `uuid-${uuidCounter++}`,
+ properties,
+ } as unknown as PluginEvent,
+ team,
+ headers: headers as EventHeaders,
+ }
+ }
+
+ function planOf(item: WithMergeFoldDecision): MergeFoldPlan | undefined {
+ return item.mergeFold.type === 'planned' ? item.mergeFold.plan : undefined
+ }
+
+ async function scan(
+ values: MergeFoldScanItem[],
+ options: { enabled?: boolean; allowlist?: string } = {}
+ ): Promise<(MergeFoldScanItem & WithMergeFoldDecision)[]> {
+ const step = createMergeFoldPlanningStep({
+ PERSON_MERGE_FOLD_ENABLED: options.enabled ?? true,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: options.allowlist ?? '*',
+ })
+ const results = await step(values)
+ expect(results).toHaveLength(values.length)
+ return results.map((result) => {
+ if (!isOkResult(result)) {
+ throw new Error('planning step must not fail values')
+ }
+ return result.value
+ })
+ }
+
+ it('emits every value as immediate when folding is disabled', async () => {
+ const inputs = [identify('anon-1'), identify('anon-2')]
+ const items = await scan(inputs, { enabled: false })
+
+ expect(items).toEqual(inputs.map((input) => ({ ...input, mergeFold: { type: 'immediate' } })))
+ })
+
+ it('plans one shared fold for a run of identifies with distinct anon ids', async () => {
+ const items = await scan([identify('anon-1'), identify('anon-2'), identify('anon-3')])
+
+ const plan = planOf(items[0])
+ expect(plan).toBeDefined()
+ expect(items.every((item) => planOf(item) === plan)).toBe(true)
+ expect(plan).toMatchObject({
+ targetDistinctId: 'user-1',
+ status: 'planned',
+ pairs: [
+ { anonDistinctId: 'anon-1', eventUuid: 'uuid-0' },
+ { anonDistinctId: 'anon-2', eventUuid: 'uuid-1' },
+ { anonDistinctId: 'anon-3', eventUuid: 'uuid-2' },
+ ],
+ })
+ })
+
+ it('decides via returned values without mutating the inputs', async () => {
+ const inputs = [identify('anon-1'), identify('anon-2'), event('$pageview')]
+ const items = await scan(inputs)
+
+ expect(inputs.every((input) => !('mergeFold' in input))).toBe(true)
+ expect(items[0].mergeFold.type).toBe('planned')
+ expect(items[2].mergeFold.type).toBe('immediate')
+ })
+
+ it('dedupes repeated pairs, keeping the first event uuid', async () => {
+ const items = await scan([identify('anon-1'), identify('anon-1'), identify('anon-2')])
+
+ expect(planOf(items[0])?.pairs).toEqual([
+ { anonDistinctId: 'anon-1', eventUuid: 'uuid-0' },
+ { anonDistinctId: 'anon-2', eventUuid: 'uuid-2' },
+ ])
+ expect(planOf(items[1])).toBe(planOf(items[0]))
+ })
+
+ it('does not plan a single merge event', async () => {
+ const items = await scan([identify('anon-1'), event('$pageview')])
+
+ expect(items.every((item) => item.mergeFold.type === 'immediate')).toBe(true)
+ })
+
+ it('splits runs on interleaved non-merge events', async () => {
+ const items = await scan([
+ identify('anon-1'),
+ identify('anon-2'),
+ event('$pageview'),
+ identify('anon-3'),
+ identify('anon-4'),
+ ])
+
+ const firstPlan = planOf(items[0])
+ const secondPlan = planOf(items[3])
+ expect(firstPlan?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1', 'anon-2'])
+ expect(secondPlan?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-3', 'anon-4'])
+ expect(firstPlan).not.toBe(secondPlan)
+ expect(items[2].mergeFold.type).toBe('immediate')
+ })
+
+ it.each([
+ ['$create_alias', { alias: 'anon-1' }],
+ ['$merge_dangerously', { alias: 'anon-1' }],
+ ['$identify', {}],
+ ])('does not treat %s as foldable', async (name, properties) => {
+ const items = await scan([event(name, 'user-1', properties), identify('anon-2'), identify('anon-3')])
+
+ expect(items[0].mergeFold.type).toBe('immediate')
+ expect(planOf(items[1])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-2', 'anon-3'])
+ })
+
+ it.each([
+ [
+ '$process_person_profile: false',
+ (anonDistinctId: string) =>
+ event('$identify', 'user-1', { $anon_distinct_id: anonDistinctId, $process_person_profile: false }),
+ ],
+ [
+ 'force_disable_person_processing header',
+ (anonDistinctId: string) =>
+ event(
+ '$identify',
+ 'user-1',
+ { $anon_distinct_id: anonDistinctId },
+ { force_disable_person_processing: true }
+ ),
+ ],
+ ])('does not fold an $identify with %s and splits the run on it', async (_name, disabledIdentify) => {
+ const items = await scan([
+ identify('anon-1'),
+ identify('anon-2'),
+ disabledIdentify('anon-3'),
+ identify('anon-4'),
+ ])
+
+ expect(planOf(items[0])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1', 'anon-2'])
+ expect(items[2].mergeFold.type).toBe('immediate')
+ // anon-4 is a lone identify after the split, so nothing to fold.
+ expect(items[3].mergeFold.type).toBe('immediate')
+ })
+
+ it('excludes illegal anon distinct ids from the plan without splitting the run', async () => {
+ const items = await scan([identify('anon-1'), identify('anonymous'), identify('anon-2')])
+
+ const plan = planOf(items[0])
+ expect(plan?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1', 'anon-2'])
+ expect(items[1].mergeFold.type).toBe('immediate')
+ expect(planOf(items[2])).toBe(plan)
+ })
+
+ it('skips planning when only illegal anon distinct ids are in the run', async () => {
+ const items = await scan([identify('anonymous'), identify('null')])
+
+ expect(items.every((item) => item.mergeFold.type === 'immediate')).toBe(true)
+ })
+
+ it('excludes self-merges from the plan', async () => {
+ const items = await scan([identify('user-1'), identify('anon-1'), identify('anon-2')])
+
+ expect(items[0].mergeFold.type).toBe('immediate')
+ expect(planOf(items[1])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1', 'anon-2'])
+ })
+
+ it('skips planning when only self-merges are in the run', async () => {
+ const items = await scan([identify('user-1'), identify('user-1')])
+
+ expect(items.every((item) => item.mergeFold.type === 'immediate')).toBe(true)
+ })
+
+ it('respects the team allowlist', async () => {
+ const planned = await scan([identify('anon-1'), identify('anon-2')], { allowlist: '7' })
+ expect(planned[0].mergeFold.type).toBe('planned')
+
+ const skipped = await scan([identify('anon-1'), identify('anon-2')], { allowlist: '8,9' })
+ expect(skipped.every((item) => item.mergeFold.type === 'immediate')).toBe(true)
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.ts
new file mode 100644
index 000000000000..6c4c926e4527
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.ts
@@ -0,0 +1,183 @@
+import { buildIntegerMatcher } from '~/common/config/config'
+import { decideProcessPerson, isDistinctIdIllegal } from '~/common/persons/person-utils'
+import type { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import { PipelineResult, ok } from '~/ingestion/framework/results'
+import type { ProcessingStep } from '~/ingestion/framework/steps'
+import { PluginEvent } from '~/plugin-scaffold'
+import { EventHeaders, InternalPerson, Team } from '~/types'
+
+/** One planned merge: an anon distinct_id to fold into the group's target distinct_id. */
+export interface MergeFoldPair {
+ anonDistinctId: string
+ /** UUID of the first event in the run that asked for this pair. */
+ eventUuid: string
+}
+
+/**
+ * A fold plan shared by a consecutive run of $identify events in one
+ * token:distinct_id group. The first event of the run executes all pairs in a
+ * single merge operation; later events in the run find their pair satisfied
+ * and skip the database entirely.
+ *
+ * - `planned`: not executed yet — the first merge event to reach the person
+ * step runs the folded merge.
+ * - `executed`: the folded merge committed; events whose anon id is in
+ * `pairs` short-circuit.
+ * - `abandoned`: the fold was skipped (limit pre-check) or failed after
+ * retries; every event processes individually through the sequential path.
+ */
+export interface MergeFoldPlan {
+ targetDistinctId: string
+ pairs: MergeFoldPair[]
+ status: 'planned' | 'executed' | 'abandoned'
+ /** The post-merge target person, set when the fold executes; later events in the run short-circuit to it. */
+ mergedPerson?: InternalPerson
+}
+
+export interface MergeFoldOptions {
+ PERSON_MERGE_FOLD_ENABLED: boolean
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
+}
+
+/** The fields of the pipeline item value the fold planning step reads. */
+export interface MergeFoldScanItem {
+ event: PluginEvent
+ team: Team
+ headers: EventHeaders
+}
+
+/**
+ * The planning step's decision for one value:
+ * - `planned`: the event is part of a fold run; the run's shared plan executes
+ * on its first event and the others short-circuit against it.
+ * - `immediate`: no fold applies; the event processes individually right away,
+ * exactly as it would without folding.
+ */
+export type MergeFoldDecision = { type: 'planned'; plan: MergeFoldPlan } | { type: 'immediate' }
+
+/** Attached to every value the planning step emits. */
+export interface WithMergeFoldDecision {
+ mergeFold: MergeFoldDecision
+}
+
+// Decisions carry no per-event state, so every immediate value shares one instance.
+const IMMEDIATE: MergeFoldDecision = { type: 'immediate' }
+
+/**
+ * Per-item step for lanes where no merges can occur, and so nothing can fold:
+ * decide `immediate` for every event so the person step's input is satisfied
+ * without the lane's callers having to supply a decision.
+ */
+export function createImmediateMergeFoldStep<T>(): ProcessingStep<T, T & WithMergeFoldDecision> {
+ return function immediateMergeFoldStep(value: T): Promise<PipelineResult<T & WithMergeFoldDecision>> {
+ return Promise.resolve(ok({ ...value, mergeFold: IMMEDIATE }))
+ }
+}
+
+// Only $identify runs are folded. $create_alias/$merge_dangerously have
+// different isMergeAllowed semantics per pair, and observed merge storms are
+// walls of $identify events for one distinct_id.
+function getFoldableAnonDistinctId(item: MergeFoldScanItem): string | null {
+ const event = item.event
+ if (event.event !== '$identify') {
+ return null
+ }
+ // A person-processing-disabled $identify never merges on the sequential
+ // path (property false drops it, the force-disable header makes it
+ // personless), so it must not contribute a pair to a fold either.
+ if (!decideProcessPerson(event, item.headers).processPerson) {
+ return null
+ }
+ const anonDistinctId = event.properties?.['$anon_distinct_id']
+ if (anonDistinctId === undefined || anonDistinctId === null) {
+ return null
+ }
+ return String(anonDistinctId)
+}
+
+/**
+ * Build the group chunk step that decides, per value, whether the event folds
+ * or processes immediately. The step is always wired; whether it plans
+ * anything is its own decision, gated on the enabled flag and the team
+ * allowlist, so disabled configurations emit every value as `immediate`.
+ *
+ * Scans a group's queued chunk for consecutive runs of two or more foldable
+ * $identify events (a single merge has nothing to fold). Each run gets one
+ * shared MergeFoldPlan, carried by the run's values as a `planned` decision,
+ * with the distinct anon ids as pairs (first event wins the pair's eventUuid;
+ * self-merges are excluded). Every other value gets the `immediate` decision.
+ * Fold size is naturally bounded by the batch size; pathological per-source
+ * distinct_id counts are handled by the merge-mode limit pre-check at
+ * execution time.
+ */
+export function createMergeFoldPlanningStep<T extends MergeFoldScanItem>(
+ options: MergeFoldOptions
+): ChunkProcessingStep<T, T & WithMergeFoldDecision> {
+ const isTeamEnabled = buildIntegerMatcher(options.PERSON_MERGE_FOLD_TEAM_ALLOWLIST, true)
+
+ // Deliberately await-free: the single wrapping promise is the only
+ // microtask this step adds to a group chunk.
+ return function planMergeFolds(values: T[]): Promise<PipelineResult<T & WithMergeFoldDecision>[]> {
+ const results = values.map((value) => ok({ ...value, mergeFold: IMMEDIATE }))
+ if (!options.PERSON_MERGE_FOLD_ENABLED || values.length < 2 || !isTeamEnabled(values[0].team.id)) {
+ return Promise.resolve(results)
+ }
+
+ let runStart = 0
+ while (runStart < values.length) {
+ if (getFoldableAnonDistinctId(values[runStart]) === null) {
+ runStart++
+ continue
+ }
+ let runEnd = runStart + 1
+ while (runEnd < values.length && getFoldableAnonDistinctId(values[runEnd]) !== null) {
+ runEnd++
+ }
+ if (runEnd - runStart >= 2) {
+ planRun(values, results, runStart, runEnd)
+ }
+ runStart = runEnd
+ }
+ return Promise.resolve(results)
+ }
+}
+
+function planRun<T extends MergeFoldScanItem>(
+ values: T[],
+ results: PipelineResult<T & WithMergeFoldDecision>[],
+ runStart: number,
+ runEnd: number
+): void {
+ const targetDistinctId = values[runStart].event.distinct_id
+ const pairByAnonId = new Map<string, MergeFoldPair>()
+
+ for (let index = runStart; index < runEnd; index++) {
+ const anonDistinctId = getFoldableAnonDistinctId(values[index])
+ if (anonDistinctId === null || anonDistinctId === targetDistinctId || pairByAnonId.has(anonDistinctId)) {
+ continue
+ }
+ // An illegal anon id never merges; keeping its event on the immediate
+ // path emits the per-event warning and keeps is_identified untouched,
+ // exactly as today.
+ if (isDistinctIdIllegal(anonDistinctId)) {
+ continue
+ }
+ pairByAnonId.set(anonDistinctId, { anonDistinctId, eventUuid: values[index].event.uuid })
+ }
+
+ if (pairByAnonId.size === 0) {
+ return
+ }
+
+ const plan: MergeFoldPlan = {
+ targetDistinctId,
+ pairs: [...pairByAnonId.values()],
+ status: 'planned',
+ }
+ for (let index = runStart; index < runEnd; index++) {
+ const anonDistinctId = getFoldableAnonDistinctId(values[index])
+ if (anonDistinctId !== null && pairByAnonId.has(anonDistinctId)) {
+ results[index] = ok({ ...values[index], mergeFold: { type: 'planned', plan } })
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 1ae9539c15ab..953123e5154b 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -1,8 +1,9 @@
import { DateTime } from 'luxon'
-import { Counter } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
import { personMergeFailureCounter } from '~/common/persons/metrics'
import { PersonMessage } from '~/common/persons/person-message'
+import { isDistinctIdIllegal } from '~/common/persons/person-utils'
import { timeoutGuard } from '~/common/utils/db/utils'
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
@@ -13,6 +14,7 @@ import { InternalPerson } from '~/types'
import { PersonContext } from './person-context'
import { PersonCreateService } from './person-create-service'
+import type { MergeFoldPair, MergeFoldPlan } from './person-merge-fold'
import {
PersonMergeLimitExceededError,
PersonMergeRaceConditionError,
@@ -43,47 +45,41 @@ export const mergeTxnSuccessCounter = new Counter({
labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],
})
-// used to prevent identify from being used with generic IDs
-// that we can safely assume stem from a bug or mistake
-const BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [
- 'anonymous',
- 'guest',
- 'distinctid',
- 'distinct_id',
- 'id',
- 'not_authenticated',
- 'email',
- 'undefined',
- 'true',
- 'false',
-]
-
-const BARE_CASE_SENSITIVE_ILLEGAL_IDS = ['[object Object]', 'NaN', 'None', 'none', 'null', '0', 'undefined']
-
-// we have seen illegal ids received but wrapped in double quotes
-// to protect ourselves from this we'll add the single- and double-quoted versions of the illegal ids
-const singleQuoteIds = (ids: string[]) => ids.map((id) => `'${id}'`)
-const doubleQuoteIds = (ids: string[]) => ids.map((id) => `"${id}"`)
-
-// some ids are illegal regardless of casing
-// while others are illegal only when cased
-// so, for example, we want to forbid `NaN` but not `nan`
-// but, we will forbid `uNdEfInEd` and `undefined`
-const CASE_INSENSITIVE_ILLEGAL_IDS = new Set(
- BARE_CASE_INSENSITIVE_ILLEGAL_IDS.concat(singleQuoteIds(BARE_CASE_INSENSITIVE_ILLEGAL_IDS)).concat(
- doubleQuoteIds(BARE_CASE_INSENSITIVE_ILLEGAL_IDS)
- )
-)
-
-const CASE_SENSITIVE_ILLEGAL_IDS = new Set(
- BARE_CASE_SENSITIVE_ILLEGAL_IDS.concat(singleQuoteIds(BARE_CASE_SENSITIVE_ILLEGAL_IDS)).concat(
- doubleQuoteIds(BARE_CASE_SENSITIVE_ILLEGAL_IDS)
- )
-)
-
-export const isDistinctIdIllegal = (id: string): boolean => {
- const trimmed = id.trim()
- return trimmed === '' || CASE_INSENSITIVE_ILLEGAL_IDS.has(id.toLowerCase()) || CASE_SENSITIVE_ILLEGAL_IDS.has(id)
+export const mergeFoldExecutedCounter = new Counter({
+ name: 'person_merge_fold_executed_total',
+ help: 'Number of folded merge transactions executed.',
+})
+
+export const mergeFoldFallbackCounter = new Counter({
+ name: 'person_merge_fold_fallback_total',
+ help: 'Number of merge folds abandoned in favor of the sequential path.',
+ labelNames: ['reason'],
+})
+
+export const mergeFoldSizeHistogram = new Histogram({
+ name: 'person_merge_fold_size',
+ help: 'Number of merge pairs folded into one transaction.',
+ buckets: [2, 5, 10, 25, 50, 100, 250, 500],
+})
+
+/** Thrown inside the fold transaction to roll it back when merge-mode move bounds would be exceeded. */
+class MergeFoldLimitError extends Error {}
+
+/** Thrown inside the fold transaction to roll it back when a concurrent merge invalidated the fetched sources. */
+class MergeFoldConflictError extends Error {}
+
+/** Maps a fold failure to the fallback counter's reason label. */
+function foldFallbackReason(error: unknown): 'limit' | 'conflict' | 'deadlock' | 'error' {
+ if (error instanceof MergeFoldLimitError) {
+ return 'limit'
+ }
+ if (error instanceof MergeFoldConflictError) {
+ return 'conflict'
+ }
+ if ((error as { code?: string })?.code === '40P01') {
+ return 'deadlock'
+ }
+ return 'error'
}
/**
@@ -124,8 +120,15 @@ export class PersonMergeService {
this.context.event.event === '$identify' &&
'$anon_distinct_id' in this.context.eventProperties
) {
+ const anonDistinctId = String(this.context.eventProperties['$anon_distinct_id'])
+ // Only await the fold path when a plan exists: an extra microtask
+ // here measurably shifts event interleaving for plain merges.
+ const foldResult = this.context.mergeFoldPlan ? await this.tryFoldedMerge(anonDistinctId) : null
+ if (foldResult !== null) {
+ return foldResult
+ }
return await this.merge(
- String(this.context.eventProperties['$anon_distinct_id']),
+ anonDistinctId,
this.context.distinctId,
this.context.team.id,
this.context.timestamp
@@ -339,6 +342,286 @@ export class PersonMergeService {
}
}
+ /**
+ * Folded-merge entry for $identify events that are part of a MergeFoldPlan.
+ * Returns null when the event should fall through to the sequential merge
+ * path (no plan, pair not planned, plan abandoned, or fold not applicable).
+ */
+ private async tryFoldedMerge(anonDistinctId: string): Promise<PersonMergeResult | null> {
+ const plan = this.context.mergeFoldPlan
+ if (
+ !plan ||
+ plan.targetDistinctId !== this.context.distinctId ||
+ !plan.pairs.some((pair) => pair.anonDistinctId === anonDistinctId)
+ ) {
+ return null
+ }
+
+ if (plan.status === 'abandoned') {
+ return null
+ }
+
+ if (plan.status === 'executed') {
+ this.context.updateIsIdentified = true
+ return mergeSuccess(plan.mergedPerson, Promise.resolve(), true)
+ }
+
+ if (isDistinctIdIllegal(plan.targetDistinctId)) {
+ // The sequential path emits the per-event warning.
+ plan.status = 'abandoned'
+ mergeFoldFallbackCounter.labels({ reason: 'illegal_target' }).inc()
+ return null
+ }
+
+ try {
+ return await this.executeFoldedMerge(plan, anonDistinctId)
+ } catch (error) {
+ // Any failure falls back to the sequential path: the current event
+ // re-runs its own merge (a no-op if the fold partially landed), and
+ // later events in the run process individually with full retries.
+ plan.status = 'abandoned'
+ const reason = foldFallbackReason(error)
+ mergeFoldFallbackCounter.labels({ reason }).inc()
+ // The batch store's caches were updated optimistically inside the
+ // rolled-back transaction (distinct id → target mappings); purge
+ // them so the sequential fallback re-reads committed state.
+ this.context.personStore.removeDistinctIdFromCache(this.context.team.id, plan.targetDistinctId)
+ for (const pair of plan.pairs) {
+ this.context.personStore.removeDistinctIdFromCache(this.context.team.id, pair.anonDistinctId)
+ }
+ logger.warn('🤔', 'folded merge failed, falling back to sequential merges', {
+ team_id: this.context.team.id,
+ distinct_id: plan.targetDistinctId,
+ pairs: plan.pairs.length,
+ reason,
+ error,
+ })
+ return null
+ }
+ }
+
+ /**
+ * Counts each folded source's distinct ids inside the transaction and
+ * aborts the fold (rolling it back) when:
+ * - a source is missing entirely — it was merged away between the locked
+ * fetch (whose locks were released at statement end) and the transaction,
+ * so its already-computed property contribution would be stale;
+ * - a source's count exceeds the LIMIT/ASYNC move limit — those events
+ * need their own per-event DLQ/redirect decision;
+ * - the total exceeds batched SYNC's per-statement batch size.
+ * Returns the expected total so the caller can verify the move touched
+ * exactly that many rows. One cheap indexed GROUP BY that rarely trips.
+ */
+ private async assertFoldSourcesWithinMoveBounds(
+ tx: PersonsStoreTransactionForBatch,
+ mergeSources: InternalPerson[]
+ ): Promise<number> {
+ if (mergeSources.length === 0) {
+ return 0
+ }
+ const mergeMode = this.context.mergeMode
+ const limit = mergeMode.type === 'SYNC' ? undefined : mergeMode.limit
+ const batchSize = mergeMode.type === 'SYNC' ? mergeMode.batchSize : undefined
+
+ const counts = await tx.countDistinctIdsForPersons(
+ this.context.team.id,
+ mergeSources.map((source) => source.id),
+ this.context.distinctId
+ )
+ let total = 0
+ for (const source of mergeSources) {
+ const count = counts.get(source.id)
+ if (count === undefined) {
+ throw new MergeFoldConflictError('folded merge source lost its distinct ids concurrently')
+ }
+ if (limit !== undefined && count > limit) {
+ throw new MergeFoldLimitError('folded merge source exceeds distinct id move limit')
+ }
+ total += count
+ }
+ if (batchSize !== undefined && total > batchSize) {
+ throw new MergeFoldLimitError('folded merge move exceeds sync batch size')
+ }
+ return total
+ }
+
+ private async executeFoldedMerge(plan: MergeFoldPlan, currentAnonDistinctId: string): Promise<PersonMergeResult> {
+ const teamId = this.context.team.id
+ this.context.updateIsIdentified = true
+
+ let target = await this.context.personStore.fetchForUpdate(teamId, plan.targetDistinctId)
+ let pairsToFold = plan.pairs
+
+ if (!target) {
+ // Cold start: no target person yet. Bootstrap it through the
+ // sequential path for the current event's pair (which creates the
+ // person or attaches the distinct_id), then fold the remaining pairs.
+ const bootstrap = await promiseRetry(
+ () =>
+ this.mergeDistinctIds(currentAnonDistinctId, plan.targetDistinctId, teamId, this.context.timestamp),
+ 'merge_distinct_ids'
+ )
+ if (!bootstrap.success || !bootstrap.person) {
+ throw new Error('merge fold bootstrap did not produce a target person')
+ }
+ target = bootstrap.person
+ pairsToFold = plan.pairs.filter((pair) => pair.anonDistinctId !== currentAnonDistinctId)
+ }
+
+ const sources = await this.context.personStore.fetchPersonsForUpdateByDistinctIds(
+ teamId,
+ pairsToFold.map((pair) => pair.anonDistinctId)
+ )
+ const sourceByDistinctId = new Map(sources.map((source) => [source.distinct_id, source]))
+
+ // Partition pairs, preserving pair order for property-merge precedence.
+ const mergeSources: InternalPerson[] = []
+ const seenSourceIds = new Set<string>([target.id])
+ const missingPairs: MergeFoldPair[] = []
+ for (const pair of pairsToFold) {
+ if (isDistinctIdIllegal(pair.anonDistinctId)) {
+ await emitIngestionWarning(this.context.outputs, teamId, {
+ type: 'cannot_merge_with_illegal_distinct_id',
+ details: {
+ illegalDistinctId: pair.anonDistinctId,
+ otherDistinctId: plan.targetDistinctId,
+ distinctId: plan.targetDistinctId,
+ eventUuid: pair.eventUuid,
+ },
+ pipelineStep: 'person-merge',
+ alwaysSend: true,
+ })
+ continue
+ }
+ const source = sourceByDistinctId.get(pair.anonDistinctId)
+ if (!source) {
+ missingPairs.push(pair)
+ continue
+ }
+ if (seenSourceIds.has(source.id)) {
+ continue
+ }
+ if (source.is_identified) {
+ // $identify never merges an already-identified source. One
+ // warning per folded pair (pairs are deduped), not per event.
+ await emitIngestionWarning(this.context.outputs, teamId, {
+ type: 'cannot_merge_already_identified',
+ details: {
+ sourcePersonDistinctId: pair.anonDistinctId,
+ targetPersonDistinctId: plan.targetDistinctId,
+ distinctId: plan.targetDistinctId,
+ eventUuid: pair.eventUuid,
+ personId: target.uuid,
+ otherPersonId: source.uuid,
+ },
+ pipelineStep: 'person-merge',
+ alwaysSend: true,
+ })
+ continue
+ }
+ seenSourceIds.add(source.id)
+ mergeSources.push(source)
+ }
+
+ if (mergeSources.length === 0 && missingPairs.length === 0) {
+ plan.status = 'executed'
+ plan.mergedPerson = target
+ return mergeSuccess(target, Promise.resolve(), true)
+ }
+
+ // Sequential property precedence: each pair merges source properties
+ // under the accumulated target's (target wins, earlier sources win
+ // over later ones). Event $set/$set_once apply on top, as in mergePeople.
+ let mergedProperties: Properties = target.properties
+ for (const source of mergeSources) {
+ mergedProperties = { ...source.properties, ...mergedProperties }
+ }
+ const propertyUpdates = computeEventPropertyUpdates(
+ this.context.event,
+ mergedProperties,
+ this.context.updateAllProperties
+ )
+ const [updatedTempPerson] = applyEventPropertyUpdates(propertyUpdates, {
+ ...target,
+ properties: mergedProperties,
+ })
+
+ const createdAt = DateTime.min(target.created_at, ...mergeSources.map((source) => source.created_at))
+ const version = Math.max(target.version, ...mergeSources.map((source) => source.version)) + 1
+
+ const currentTarget = target
+ const [mergedPerson, kafkaMessages] = await this.context.personStore.inTransaction(
+ 'mergePeopleFold',
+ async (tx) => {
+ const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)
+
+ let person = currentTarget
+ let updateMessages: PersonMessage[] = []
+ if (mergeSources.length > 0) {
+ ;[person, updateMessages] = await tx.updatePersonForMerge(
+ currentTarget,
+ {
+ created_at: createdAt,
+ properties: updatedTempPerson.properties,
+ is_identified: true,
+ version,
+ },
+ this.context.distinctId
+ )
+ }
+
+ const moveResult = await tx.moveDistinctIdsFromPersons(
+ mergeSources,
+ currentTarget,
+ this.context.distinctId
+ )
+ if (!moveResult.success) {
+ throw new TargetPersonNotFoundError('Target person no longer exists')
+ }
+ // A mismatch means a concurrent merge touched the sources
+ // between the count and the move; abort so the sequential path
+ // (whose zero-moved handling retries with fresh persons) takes
+ // over rather than merging stale source properties.
+ if (moveResult.distinctIdsMoved.length !== expectedMoveCount) {
+ throw new MergeFoldConflictError('folded merge moved an unexpected number of distinct ids')
+ }
+
+ const addMessages: PersonMessage[] = []
+ for (const pair of missingPairs) {
+ // See mergeDistinctIds for the personless distinctIdVersion logic.
+ const inserted = await tx.addPersonlessDistinctIdForMerge(teamId, pair.anonDistinctId)
+ const distinctIdVersion = inserted ? 0 : 1
+ addMessages.push(...(await tx.addDistinctId(person, pair.anonDistinctId, distinctIdVersion)))
+ }
+
+ let deleteMessages: PersonMessage[] = []
+ if (mergeSources.length > 0) {
+ await tx.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamId,
+ mergeSources.map((source) => source.id),
+ currentTarget.id,
+ this.context.distinctId
+ )
+ deleteMessages = await tx.deletePersons(mergeSources, this.context.distinctId)
+ }
+
+ return [person, [...updateMessages, ...moveResult.messages, ...addMessages, ...deleteMessages]]
+ }
+ )
+
+ plan.status = 'executed'
+ plan.mergedPerson = mergedPerson
+ mergeFoldExecutedCounter.inc()
+ mergeFoldSizeHistogram.observe(plan.pairs.length)
+
+ const kafkaAck = this.context.produceMessages(kafkaMessages)
+ for (const source of mergeSources) {
+ // Same fire-and-forget contract as executeTransaction.
+ void this.context.producePersonMergeEvent(source, mergedPerson).catch(() => {})
+ }
+ return mergeSuccess(mergedPerson, kafkaAck, true)
+ }
+
public async mergePeople({
mergeInto,
mergeIntoDistinctId,
diff --git a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
index 21b75162eea3..a423de3ae7d8 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
@@ -49,6 +50,23 @@ export interface PersonsStoreTransactionForBatch {
limit?: number
): Promise<MoveDistinctIdsResult>
+ /** Batched unlimited moveDistinctIds for folded merges. */
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string
+ ): Promise<MoveDistinctIdsResult>
+
+ /** Batched deletePerson for folded merges; all persons must belong to one team. */
+ deletePersons(persons: InternalPerson[], distinctId: string): Promise<PersonMessage[]>
+
+ /** Distinct-id counts per person id, for the folded-merge limit pre-check. */
+ countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string
+ ): Promise<Map<string, number>>
+
updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
@@ -56,6 +74,13 @@ export interface PersonsStoreTransactionForBatch {
distinctId: string
): Promise<void>
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string
+ ): Promise<void>
+
addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean>
fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]>
@@ -73,11 +98,13 @@ export type PersonsStoreForBatch = Omit<
PersonsStore,
| 'fetchForChecking'
| 'fetchForUpdate'
+ | 'fetchPersonsForUpdateByDistinctIds'
| 'createPerson'
| 'updatePersonForMerge'
| 'updatePersonWithPropertiesDiffForUpdate'
| 'addDistinctId'
| 'moveDistinctIds'
+ | 'moveDistinctIdsFromPersons'
| 'addPersonlessDistinctId'
| 'addPersonlessDistinctIdForMerge'
| 'prefetchPersons'
@@ -88,6 +115,13 @@ export type PersonsStoreForBatch = Omit<
> & {
fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null>
fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null>
+ fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]>
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<MoveDistinctIdsResult>
createPerson(
createdAt: DateTime,
properties: Properties,
@@ -212,6 +246,26 @@ class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBat
return this.tx.moveDistinctIds(source, target, distinctId, limit, this.batchId)
}
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string
+ ): Promise<MoveDistinctIdsResult> {
+ return this.tx.moveDistinctIdsFromPersons(sources, target, distinctId, this.batchId)
+ }
+
+ deletePersons(persons: InternalPerson[], distinctId: string): Promise<PersonMessage[]> {
+ return this.tx.deletePersons(persons, distinctId)
+ }
+
+ countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string
+ ): Promise<Map<string, number>> {
+ return this.tx.countDistinctIdsForPersons(teamId, personIds, distinctId)
+ }
+
updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
@@ -221,6 +275,15 @@ class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBat
return this.tx.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId)
}
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string
+ ): Promise<void> {
+ return this.tx.updateCohortsAndFeatureFlagsForMergeBatch(teamID, sourcePersonIDs, targetPersonID, distinctId)
+ }
+
addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean> {
return this.tx.addPersonlessDistinctIdForMerge(teamId, distinctId, this.batchId)
}
@@ -244,6 +307,10 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.fetchForUpdate(teamId, distinctId, this.batchId)
}
+ fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]> {
+ return this.store.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, this.batchId)
+ }
+
createPerson(
createdAt: DateTime,
properties: Properties,
@@ -286,6 +353,48 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.moveDistinctIds(source, target, distinctId, limit, tx, this.batchId)
}
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<MoveDistinctIdsResult> {
+ return this.store.moveDistinctIdsFromPersons(sources, target, distinctId, tx, this.batchId)
+ }
+
+ deletePersons(
+ persons: InternalPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ return this.store.deletePersons(persons, distinctId, tx)
+ }
+
+ countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<Map<string, number>> {
+ return this.store.countDistinctIdsForPersons(teamId, personIds, distinctId, tx)
+ }
+
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.store.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ distinctId,
+ tx
+ )
+ }
+
prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
return this.store.prefetchPersons(teamDistinctIds)
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
index 8d0ecea9fcb6..189f3a135b3d 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
@@ -100,6 +100,27 @@ export class PersonsStoreTransaction {
return await this.store.moveDistinctIds(source, target, distinctId, limit, this.tx, batchId)
}
+ async moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ return await this.store.moveDistinctIdsFromPersons(sources, target, distinctId, this.tx, batchId)
+ }
+
+ async deletePersons(persons: InternalPerson[], distinctId: string): Promise<PersonMessage[]> {
+ return await this.store.deletePersons(persons, distinctId, this.tx)
+ }
+
+ async countDistinctIdsForPersons(
+ teamID: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string
+ ): Promise<Map<string, number>> {
+ return await this.store.countDistinctIdsForPersons(teamID, personIds, distinctId, this.tx)
+ }
+
async updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
@@ -115,6 +136,21 @@ export class PersonsStoreTransaction {
)
}
+ async updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string
+ ): Promise<void> {
+ return await this.store.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ distinctId,
+ this.tx
+ )
+ }
+
async addPersonlessDistinctIdForMerge(teamId: number, distinctId: string, batchId: number): Promise<boolean> {
return await this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, this.tx, batchId)
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.ts
index 1555f7816993..7ecefdddeefe 100644
--- a/nodejs/src/ingestion/common/persons/persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { BatchWritingStore } from '~/ingestion/common/stores/batch-writing-store'
@@ -36,6 +37,16 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
*/
fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>
+ /**
+ * Batched fetchForUpdate for folded merges: resolves and row-locks all
+ * persons behind the given distinct_ids in one statement.
+ */
+ fetchPersonsForUpdateByDistinctIds(
+ teamId: number,
+ distinctIds: string[],
+ batchId: number
+ ): Promise<InternalPersonWithDistinctId[]>
+
/**
* Creates a new person
*/
@@ -107,6 +118,36 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
batchId: number
): Promise<MoveDistinctIdsResult>
+ /**
+ * Batched unlimited moveDistinctIds for folded merges
+ */
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ tx: PersonRepositoryTransaction,
+ batchId: number
+ ): Promise<MoveDistinctIdsResult>
+
+ /**
+ * Batched deletePerson for folded merges; all persons must belong to one team
+ */
+ deletePersons(
+ persons: InternalPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]>
+
+ /**
+ * Distinct-id counts per person id, for the folded-merge limit pre-check
+ */
+ countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<Map<string, number>>
+
/**
* Updates cohorts and feature flags for merged persons
*/
@@ -118,6 +159,17 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
tx?: PersonRepositoryTransaction
): Promise<void>
+ /**
+ * Batched updateCohortsAndFeatureFlagsForMerge for folded merges
+ */
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void>
+
/**
* Adds a personless distinct ID
*/
diff --git a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
index ae35c4be325c..fcfb86350a57 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
@@ -6,6 +6,8 @@ export interface EventPipelineRunnerOptions {
PERSON_MERGE_EVENTS_ENABLED: boolean
PERSON_MERGE_EVENTS_PARTITION_COUNT: number
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
+ PERSON_MERGE_FOLD_ENABLED: boolean
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: number
PERSON_PROPERTIES_UPDATE_ALL: boolean
/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */
diff --git a/nodejs/src/ingestion/common/steps/event-processing/normalize-process-person-flag-step.ts b/nodejs/src/ingestion/common/steps/event-processing/normalize-process-person-flag-step.ts
index bb0ce20ff436..3aaaf440ce1c 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/normalize-process-person-flag-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/normalize-process-person-flag-step.ts
@@ -1,3 +1,4 @@
+import { decideProcessPerson } from '~/common/persons/person-utils'
import { normalizeProcessPerson } from '~/common/utils/event'
import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'
import { PipelineResult, drop, ok } from '~/ingestion/framework/results'
@@ -25,59 +26,47 @@ export function createNormalizeProcessPersonFlagStep<TInput extends NormalizePro
): Promise<PipelineResult<TInput & NormalizeProcessPersonFlagOutput>> {
const event = input.event
const warnings: PipelineWarning[] = []
- const forceDisablePersonProcessing = input.headers.force_disable_person_processing === true
- let 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 true
- if (forceDisablePersonProcessing) {
- processPerson = false
- } else {
- // Set either at capture time, or in the populateTeamData step, if team-level opt-out is enabled.
- if (event.properties && '$process_person_profile' in event.properties) {
- const propValue = event.properties.$process_person_profile
- if (propValue === true) {
- // This is the default, and `true` is one of the two valid values.
- } else if (propValue === false) {
- // Only a boolean `false` disables person processing.
- processPerson = false
+ const decision = decideProcessPerson(event, input.headers)
+ const processPerson = decision.processPerson
+ const forceDisablePersonProcessing = !decision.processPerson && decision.reason === 'header'
- if (['$identify', '$create_alias', '$merge_dangerously', '$groupidentify'].includes(event.event)) {
- warnings.push({
- type: 'invalid_event_when_process_person_profile_is_false',
- details: {
- eventUuid: event.uuid,
- event: event.event,
- distinctId: event.distinct_id,
- },
- alwaysSend: true,
- })
+ if (!decision.processPerson && decision.reason === 'property') {
+ if (['$identify', '$create_alias', '$merge_dangerously', '$groupidentify'].includes(event.event)) {
+ warnings.push({
+ type: 'invalid_event_when_process_person_profile_is_false',
+ details: {
+ eventUuid: event.uuid,
+ event: event.event,
+ distinctId: event.distinct_id,
+ },
+ alwaysSend: true,
+ })
- return Promise.resolve(drop('invalid_event_for_flags', [], warnings))
- }
-
- // If person processing is disabled, go ahead and remove person related keys before
- // any plugins have a chance to see them.
- normalizedEvent = normalizeProcessPerson(event, processPerson)
- } else {
- // Anything other than `true` or `false` is invalid, and the default (true) will be
- // used.
- warnings.push({
- type: 'invalid_process_person_profile',
- details: {
- eventUuid: event.uuid,
- event: event.event,
- distinctId: event.distinct_id,
- $process_person_profile: propValue,
- message: 'Only a boolean value is valid for the $process_person_profile property',
- },
- alwaysSend: false,
- })
- }
+ return Promise.resolve(drop('invalid_event_for_flags', [], warnings))
}
+
+ // If person processing is disabled, go ahead and remove person related keys before
+ // any plugins have a chance to see them.
+ normalizedEvent = normalizeProcessPerson(event, processPerson)
+ } else if (decision.processPerson && decision.invalid) {
+ // Anything other than `true` or `false` is invalid, and the default (true) will be
+ // used.
+ warnings.push({
+ type: 'invalid_process_person_profile',
+ details: {
+ eventUuid: event.uuid,
+ event: event.event,
+ distinctId: event.distinct_id,
+ $process_person_profile: decision.invalid.value,
+ message: 'Only a boolean value is valid for the $process_person_profile property',
+ },
+ alwaysSend: false,
+ })
}
return Promise.resolve(
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
index e5027b23587d..188d2209a6b4 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
@@ -4,6 +4,7 @@ import { buildIntegerMatcher } from '~/common/config/config'
import { AsyncOutput } from '~/common/outputs'
import { MergeEventsConfig, PersonContext, PersonOutputs } from '~/ingestion/common/persons/person-context'
import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'
+import type { MergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'
import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'
import { determineMergeMode } from '~/ingestion/common/persons/person-merge-types'
import { PersonPropertyService } from '~/ingestion/common/persons/person-property-service'
@@ -21,6 +22,8 @@ export type ProcessPersonsInput = {
timestamp: DateTime
personlessPerson?: Person
personsStoreForBatch: PersonsStoreForBatch
+ /** The merge-fold planning decision for this event; `immediate` everywhere except planned $identify runs in the grouped analytics lane. */
+ mergeFold: MergeFoldDecision
}
export type ProcessPersonsOutput = {
@@ -66,7 +69,8 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
mergeMode,
options.PERSON_PROPERTIES_UPDATE_ALL,
shouldUpdateLastSeenAt,
- mergeEventsConfig
+ mergeEventsConfig,
+ input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined
)
const processor = new PersonEventProcessor(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 5fe670974e3d..15f66a3e4180 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -162,6 +162,12 @@ export type IngestionConsumerConfig = {
// Defaults to team 2 only. Unlike the Rust REALTIME_COHORT_TEAM_ALLOWLIST, an empty value here
// means "no teams", not "all teams"; use '*' to open the gate.
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
+ // Fold consecutive runs of $identify merges for the same distinct_id in a batch into a single
+ // merge operation (merge-storm mitigation). Master switch; when off, the planning step passes
+ // every event through unplanned and merges stay sequential.
+ PERSON_MERGE_FOLD_ENABLED: boolean
+ // Teams eligible for merge folding: comma-separated team IDs, or '*' for all teams.
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean
@@ -298,6 +304,8 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',
+ PERSON_MERGE_FOLD_ENABLED: false,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,
diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
index 22573b323df2..cfb34ab3665c 100644
--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
@@ -22,6 +22,74 @@ function isSuccessResultWithContext<T, C, R extends string>(
*/
export type ChunkProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>
+/**
+ * Apply a chunk step to a chunk of results: run the step over the OK values,
+ * enforce the one-result-per-value contract, and zip the step results back onto
+ * their contexts (recording lastStep and accumulating side effects and
+ * warnings). Non-OK results pass through unchanged. This is the single
+ * implementation of chunk-step semantics, shared by {@link BaseChunkPipeline}
+ * and the group-level pipeChunk in ConcurrentlyGroupingChunkPipeline.
+ */
+export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string, RStep extends string>(
+ step: ChunkProcessingStep<TIn, TOut, RStep>,
+ stepName: string,
+ items: PipelineResultWithContext<TIn, C, RPrev>[]
+): Promise<PipelineResultWithContext<TOut, C, RPrev | RStep>[]> {
+ const successfulValues = items
+ .filter(isSuccessResultWithContext)
+ .map((resultWithContext) => resultWithContext.result.value)
+
+ let stepResults: PipelineResult<TOut, RStep>[] = []
+ if (successfulValues.length > 0) {
+ const end = pipelineStepDurationHistogram.startTimer({ step_name: stepName, step_type: 'chunk' })
+ try {
+ stepResults = await instrumentFn({ key: stepName, sendException: false, measureTime: false }, () =>
+ step(successfulValues)
+ )
+ end({ result: 'chunk' })
+ } catch (e) {
+ end({ result: 'exception' })
+ throw e
+ }
+ if (stepResults.length !== successfulValues.length) {
+ throw new Error(
+ `Chunk pipeline step ${stepName} returned different number of results than input values: ${stepResults.length} !== ${successfulValues.length}`
+ )
+ }
+ }
+ let stepIndex = 0
+
+ // Map results back, preserving context and non-successful results
+ const output: PipelineResultWithContext<TOut, C, RPrev | RStep>[] = []
+ for (const resultWithContext of items) {
+ if (isOkResult(resultWithContext.result)) {
+ const stepResult = stepResults[stepIndex++]
+ output.push({
+ result: stepResult,
+ context: {
+ ...resultWithContext.context,
+ lastStep: stepName,
+ // Copy-on-write: contexts are rebuilt by spreading at every
+ // step and never mutated in place, so when the step added
+ // nothing the existing array can be shared as-is.
+ sideEffects: stepResult.sideEffects.length
+ ? [...resultWithContext.context.sideEffects, ...stepResult.sideEffects]
+ : resultWithContext.context.sideEffects,
+ warnings: stepResult.warnings.length
+ ? [...resultWithContext.context.warnings, ...stepResult.warnings]
+ : resultWithContext.context.warnings,
+ },
+ })
+ } else {
+ output.push({
+ result: resultWithContext.result,
+ context: resultWithContext.context,
+ })
+ }
+ }
+ return output
+}
+
export class BaseChunkPipeline<
TInput,
TIntermediate,
@@ -51,53 +119,6 @@ export class BaseChunkPipeline<
return null
}
- // Filter successful values for processing
- const successfulValues = previousResults
- .filter(isSuccessResultWithContext)
- .map((resultWithContext) => resultWithContext.result.value)
-
- // Apply current step to successful values
- let stepResults: PipelineResult<TOutput, RStep>[] = []
- if (successfulValues.length > 0) {
- const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'chunk' })
- try {
- stepResults = await instrumentFn({ key: this.stepName, sendException: false, measureTime: false }, () =>
- this.currentStep(successfulValues)
- )
- end({ result: 'chunk' })
- } catch (e) {
- end({ result: 'exception' })
- throw e
- }
- if (stepResults.length !== successfulValues.length) {
- throw new Error(
- `Chunk pipeline step ${this.stepName} returned different number of results than input values: ${stepResults.length} !== ${successfulValues.length}`
- )
- }
- }
- let stepIndex = 0
-
- // Map results back, preserving context and non-successful results
- const output: ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> = []
- for (const resultWithContext of previousResults) {
- if (isOkResult(resultWithContext.result)) {
- const stepResult = stepResults[stepIndex++]
- output.push({
- result: stepResult,
- context: {
- ...resultWithContext.context,
- lastStep: this.stepName,
- sideEffects: [...resultWithContext.context.sideEffects, ...stepResult.sideEffects],
- warnings: [...resultWithContext.context.warnings, ...stepResult.warnings],
- },
- })
- } else {
- output.push({
- result: resultWithContext.result,
- context: resultWithContext.context,
- })
- }
- }
- return output
+ return await applyChunkStepToResults(this.currentStep, this.stepName, previousResults)
}
}
diff --git a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts
index 7a5531f8e2e6..3f4b88570f11 100644
--- a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts
@@ -3,13 +3,19 @@ import { Message } from 'node-rdkafka'
import { IngestionWarningsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
-import { BaseChunkPipeline, ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import {
+ BaseChunkPipeline,
+ ChunkProcessingStep,
+ applyChunkStepToResults,
+} from '~/ingestion/framework/base-chunk-pipeline'
import { BufferingChunkPipeline } from '~/ingestion/framework/buffering-chunk-pipeline'
import { ChunkPipeline } from '~/ingestion/framework/chunk-pipeline.interface'
import { ConcurrentChunkProcessingPipeline } from '~/ingestion/framework/concurrent-chunk-pipeline'
import {
ConcurrentlyGroupingChunkPipeline,
+ GroupChunkProcessor,
GroupingFunction,
+ processGroupChunkSequentially,
} from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'
import {
FanInFunction,
@@ -20,7 +26,6 @@ import {
import { FilterMapChunkPipeline, FilterMapMappingFunction } from '~/ingestion/framework/filter-map-chunk-pipeline'
import { GatheringChunkPipeline } from '~/ingestion/framework/gathering-chunk-pipeline'
import { IngestionWarningHandlingChunkPipeline } from '~/ingestion/framework/ingestion-warning-handling-chunk-pipeline'
-import { Pipeline } from '~/ingestion/framework/pipeline.interface'
import { PipelineConfig, ResultHandlingPipeline } from '~/ingestion/framework/result-handling-pipeline'
import { RetryOptions, withChunkRetry } from '~/ingestion/framework/retry'
import { SequentialChunkPipeline } from '~/ingestion/framework/sequential-chunk-pipeline'
@@ -37,9 +42,11 @@ export interface TeamIdContext {
}
/**
- * Configures how items within a group are processed. Groups produced by
- * `concurrentlyPerGroup` run concurrently; this builder's `sequentially` method
- * defines how the items within a single group are processed.
+ * Composes how a group's queued chunk is processed, as a chain of group chunk
+ * stages: `pipeChunk` applies a chunk step to the whole chunk, `sequentially`
+ * runs each item through a per-item pipeline one at a time. Stages run in
+ * declaration order; `concurrentlyPerGroup` finalizes the chain into the
+ * single {@link GroupChunkProcessor} the grouping pipeline executes per chunk.
*/
export class GroupProcessingBuilder<
TInput,
@@ -54,11 +61,35 @@ export class GroupProcessingBuilder<
// subpipeline callbacks (e.g. in newBatchingPipeline). In this closure's
// signature TOutput only appears in variance-neutral positions.
constructor(
- private readonly buildGroupedPipeline: <U, R2 extends string>(
- processor: Pipeline<TOutput, U, COutput, R2>
+ /** @internal Completes the group definition; called by concurrentlyPerGroup with the terminal stage. */
+ readonly buildGroupedPipeline: <U, R2 extends string>(
+ downstream: GroupChunkProcessor<TOutput, U, COutput, R2>
) => ChunkPipeline<TInput, U, CInput, COutput, R | R2>
) {}
+ private stage<U, R2 extends string>(
+ stageProcessor: GroupChunkProcessor<TOutput, U, COutput, R2>
+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {
+ const buildWithEarlierStages = this.buildGroupedPipeline
+ return new GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2>(
+ <V, R3 extends string>(downstream: GroupChunkProcessor<U, V, COutput, R3>) =>
+ buildWithEarlierStages<V, R2 | R3>(async (items) => await downstream(await stageProcessor(items)))
+ )
+ }
+
+ /**
+ * Apply a chunk step to each group's queued chunk. Same contract as the
+ * outer `pipeChunk`: the step sees the chunk's OK values in processing
+ * order and returns one result per value; non-OK results pass through.
+ * Runs once per started group chunk.
+ */
+ pipeChunk<U, R2 extends string = never>(
+ step: ChunkProcessingStep<TOutput, U, R2>
+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {
+ const stepName = step.name || 'anonymousChunkStep'
+ return this.stage((items) => applyChunkStepToResults(step, stepName, items))
+ }
+
/**
* Process the items within each group sequentially through the provided
* pipeline: one item at a time, in input order. Groups still run
@@ -66,9 +97,9 @@ export class GroupProcessingBuilder<
*/
sequentially<U, R2 extends string = never>(
callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>
- ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {
const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()
- return new ChunkPipelineBuilder(this.buildGroupedPipeline(processor))
+ return this.stage(processGroupChunkSequentially(processor))
}
}
@@ -264,9 +295,9 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
* Group items by key and process the groups concurrently, optionally capped
* by `maxConcurrency`. Results are returned unordered as each group completes.
*
- * The callback receives a group builder whose only method, `sequentially`,
- * configures how items WITHIN a group are processed. Making that step explicit
- * keeps within-group ordering visible at the call site.
+ * The callback composes how a group's queued chunk is processed from group
+ * chunk stages (`pipeChunk`, `sequentially`), keeping within-group ordering
+ * visible at the call site.
*
* @param options.maxConcurrency - Cap on how many groups process at once. Omitted means unbounded.
*/
@@ -274,15 +305,21 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
groupingFn: GroupingFunction<TOutput, TKey>,
callback: (
group: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, R>
- ) => ChunkPipelineBuilder<TInput, U, CInput, COutput, ROut>,
+ ) => GroupProcessingBuilder<TInput, U, CInput, COutput, ROut>,
options?: { maxConcurrency?: number }
): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {
- return callback(
+ const group = callback(
new GroupProcessingBuilder(
- <U2, R2 extends string>(processor: Pipeline<TOutput, U2, COutput, R2>) =>
- new ConcurrentlyGroupingChunkPipeline(groupingFn, processor, this.pipeline, options?.maxConcurrency)
+ <U2, R2 extends string>(processGroupChunk: GroupChunkProcessor<TOutput, U2, COutput, R2>) =>
+ new ConcurrentlyGroupingChunkPipeline(
+ groupingFn,
+ processGroupChunk,
+ this.pipeline,
+ options?.maxConcurrency
+ )
)
)
+ return new ChunkPipelineBuilder(group.buildGroupedPipeline((items) => Promise.resolve(items)))
}
handleSideEffects(
diff --git a/nodejs/src/ingestion/framework/builders/index.ts b/nodejs/src/ingestion/framework/builders/index.ts
index e27c6e77a2a8..3189676e386a 100644
--- a/nodejs/src/ingestion/framework/builders/index.ts
+++ b/nodejs/src/ingestion/framework/builders/index.ts
@@ -5,5 +5,6 @@ export {
TeamAwareChunkPipelineBuilder,
} from './chunk-pipeline-builders'
export type { RetryOptions } from '~/ingestion/framework/retry'
+export type { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
export { BranchingPipelineBuilder, PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'
export { newChunkPipelineBuilder, newBatchingPipeline, newPipelineBuilder } from './helpers'
diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.ts
index ac2c1b2541c4..6210d9854b1b 100644
--- a/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.ts
@@ -3,7 +3,10 @@ import { Message } from 'node-rdkafka'
import { createTestMessage } from '~/tests/helpers/kafka-message'
import { createMockPipeline } from '~/tests/helpers/mock-pipeline'
-import { ConcurrentlyGroupingChunkPipeline } from './concurrently-grouping-chunk-pipeline'
+import {
+ ConcurrentlyGroupingChunkPipeline,
+ processGroupChunkSequentially,
+} from './concurrently-grouping-chunk-pipeline'
import { createContext, createNewChunkPipeline, createNewPipeline, createOkContext } from './helpers'
import { PipelineResultWithContext } from './pipeline.interface'
import { dlq, drop, ok } from './results'
@@ -59,7 +62,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
)
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
expect(pipeline).toBeInstanceOf(ConcurrentlyGroupingChunkPipeline)
})
@@ -73,7 +80,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
const spy = jest.spyOn(previousPipeline, 'feed')
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]
pipeline.feed(testBatch)
@@ -89,7 +100,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
)
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const result = await pipeline.next()
expect(result).toBeNull()
@@ -104,7 +119,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
await expect(pipeline.next()).rejects.toThrow('Processor error')
})
@@ -124,7 +143,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
]
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const results: PipelineResultWithContext<any, any>[] = []
let result = await pipeline.next()
@@ -153,7 +176,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
]
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const resultsPromise = (async () => {
let result = await pipeline.next()
@@ -194,7 +221,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const testBatch = events.map((e) => createOkContext(e, context1))
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
// Collect results and track per-group ordering
const groupResults = new Map<string, number[]>()
@@ -253,7 +284,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
}
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const results: PipelineResultWithContext<any, any>[] = []
let result = await pipeline.next()
@@ -290,7 +325,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
testBatch.push(createOkContext({ index: index++, group: 'slow' }, context1))
previousPipeline.feed(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
// Consume results until we have all normal groups
const results: PipelineResultWithContext<any, any>[] = []
@@ -360,7 +399,7 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const pipeline = new ConcurrentlyGroupingChunkPipeline(
(input) => input.group,
- processor,
+ processGroupChunkSequentially(processor),
previousPipeline,
maxConcurrency
)
@@ -402,7 +441,7 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
const pipeline = new ConcurrentlyGroupingChunkPipeline(
(input) => input.group,
- processor,
+ processGroupChunkSequentially(processor),
previousPipeline,
2
)
@@ -466,7 +505,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
const testBatch = [createContext(dropResult, context1), createContext(dlqResult, context2)]
const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const results: PipelineResultWithContext<any, any>[] = []
let result = await pipeline.next()
@@ -495,7 +538,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
]
const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
const results: PipelineResultWithContext<any, any>[] = []
let result = await pipeline.next()
@@ -542,6 +589,49 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
expect(results.every((r) => r.result.type === 0 && (r.result as any).value.processed)).toBe(true)
})
+ it('should compose chained group chunk steps in order', async () => {
+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((values: { value: string; group: string }[]) =>
+ Promise.resolve(
+ values.map((value) =>
+ value.value === 'a1'
+ ? drop<{ value: string; group: string; first: boolean }>(
+ 'dropped by first step'
+ )
+ : ok({ ...value, first: true })
+ )
+ )
+ )
+ .pipeChunk((values: { value: string; group: string; first: boolean }[]) =>
+ Promise.resolve(values.map((value) => ok({ ...value, second: true })))
+ )
+ .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
+ )
+ .build()
+
+ pipeline.feed([
+ createOkContext({ value: 'a1', group: 'A' }, context1),
+ createOkContext({ value: 'a2', group: 'A' }, context2),
+ ])
+
+ const results: PipelineResultWithContext<any, any>[] = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ results.push(...result)
+ result = await pipeline.next()
+ }
+
+ expect(results).toHaveLength(2)
+ const dropped = results.find((r) => r.context.message === message1)!
+ const processed = results.find((r) => r.context.message === message2)!
+ expect(dropped.result.type).toBe(2) // DROP
+ expect(processed.result).toMatchObject({ value: { value: 'a2', first: true, second: true } })
+ })
+
it('should chain with gather to collect all results', async () => {
const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
.concurrentlyPerGroup(
@@ -578,7 +668,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
// Feed first batch with items for group A
previousPipeline.feed([
@@ -644,7 +738,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
// Feed one element each for groups A and B (B is slow)
previousPipeline.feed([
@@ -854,7 +952,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
const nextPromise = pipeline.next()
@@ -877,7 +979,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
@@ -917,7 +1023,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
previousPipeline.feed([
createOkContext({ value: 'a1', group: 'A' }, context1),
@@ -950,7 +1060,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
return ok({ ...input, processed: true })
})
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
previousPipeline.feed([
createOkContext({ value: 'a1', group: 'A' }, context1),
@@ -986,7 +1100,11 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
)
const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
await expect(pipeline.next()).rejects.toThrow('processor boom')
await expect(pipeline.next()).rejects.toThrow('processor boom')
@@ -1000,10 +1118,183 @@ describe('ConcurrentlyGroupingChunkPipeline', () => {
feed: jest.fn(),
next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),
}
- const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)
+ const pipeline = new ConcurrentlyGroupingChunkPipeline(
+ (input: { value: string; group: string }) => input.group,
+ processGroupChunkSequentially(processor),
+ previousPipeline
+ )
await expect(pipeline.next()).rejects.toThrow('source boom')
await expect(pipeline.next()).rejects.toThrow('source boom')
})
})
+
+ describe('group chunk step', () => {
+ it("runs once per group chunk with that group's values in order", async () => {
+ const scans: string[][] = []
+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((values: { value: string; group: string }[]) => {
+ scans.push(values.map((value) => value.value))
+ return Promise.resolve(values.map((value) => ok(value)))
+ })
+ .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
+ )
+ .build()
+
+ pipeline.feed([
+ createOkContext({ value: 'a1', group: 'A' }, context1),
+ createOkContext({ value: 'b1', group: 'B' }, context2),
+ createOkContext({ value: 'a2', group: 'A' }, context3),
+ ])
+
+ let result = await pipeline.next()
+ while (result !== null) {
+ result = await pipeline.next()
+ }
+
+ expect(scans).toHaveLength(2)
+ expect(scans).toContainEqual(['a1', 'a2'])
+ expect(scans).toContainEqual(['b1'])
+ })
+
+ it('makes returned values visible to the processor', async () => {
+ const seenTags: (string | undefined)[] = []
+ const pipeline = createNewChunkPipeline<{ value: string; group: string; groupTag?: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((values: { value: string; group: string; groupTag?: string }[]) =>
+ Promise.resolve(values.map((value) => ok({ ...value, groupTag: `A:${values.length}` })))
+ )
+ .sequentially((builder) =>
+ builder.pipe((input) => {
+ seenTags.push(input.groupTag)
+ return Promise.resolve(ok(input))
+ })
+ )
+ )
+ .build()
+
+ pipeline.feed([
+ createOkContext({ value: 'a1', group: 'A' }, context1),
+ createOkContext({ value: 'a2', group: 'A' }, context2),
+ ])
+
+ let result = await pipeline.next()
+ while (result !== null) {
+ result = await pipeline.next()
+ }
+
+ expect(seenTags).toEqual(['A:2', 'A:2'])
+ })
+
+ it('passes step-failed values through without invoking the processor', async () => {
+ const processed: string[] = []
+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((values: { value: string; group: string }[]) =>
+ Promise.resolve(
+ values.map((value) =>
+ value.value === 'a1'
+ ? dlq<{ value: string; group: string }>('rejected by group step')
+ : ok(value)
+ )
+ )
+ )
+ .sequentially((builder) =>
+ builder.pipe((input) => {
+ processed.push(input.value)
+ return Promise.resolve(ok(input))
+ })
+ )
+ )
+ .build()
+
+ pipeline.feed([
+ createOkContext({ value: 'a1', group: 'A' }, context1),
+ createOkContext({ value: 'a2', group: 'A' }, context2),
+ ])
+
+ const results: PipelineResultWithContext<any, any>[] = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ results.push(...result)
+ result = await pipeline.next()
+ }
+
+ expect(processed).toEqual(['a2'])
+ expect(results).toHaveLength(2)
+ const dlqd = results.find((r) => r.context.message === message1)!
+ expect(dlqd.result.type).toBe(1) // DLQ
+ })
+
+ it('applies the step to chunks queued while the group was active separately', async () => {
+ const scans: string[][] = []
+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((values: { value: string; group: string }[]) => {
+ scans.push(values.map((value) => value.value))
+ return Promise.resolve(values.map((value) => ok(value)))
+ })
+ .sequentially((builder) =>
+ builder.pipe(async (input) => {
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ return ok(input)
+ })
+ )
+ )
+ .build()
+
+ pipeline.feed([
+ createOkContext({ value: 'a1', group: 'A' }, context1),
+ createOkContext({ value: 'a2', group: 'A' }, context2),
+ ])
+
+ const nextPromise = pipeline.next()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(scans).toEqual([['a1', 'a2']])
+
+ // a3 arrives while the group is mid-chunk: it must not join the
+ // in-flight step application, and gets its own when its chunk starts.
+ pipeline.feed([createOkContext({ value: 'a3', group: 'A' }, context3)])
+ await jest.advanceTimersByTimeAsync(100)
+ await nextPromise
+
+ const nextPromise2 = pipeline.next()
+ await jest.advanceTimersByTimeAsync(50)
+ await nextPromise2
+
+ expect(scans).toEqual([['a1', 'a2'], ['a3']])
+ })
+
+ it('poisons the pipeline when the step throws', async () => {
+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group
+ .pipeChunk((): Promise<never> => {
+ throw new Error('group step boom')
+ })
+ .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
+ )
+ .build()
+
+ pipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
+
+ await expect(pipeline.next()).rejects.toThrow('group step boom')
+ await expect(pipeline.next()).rejects.toThrow('group step boom')
+ })
+ })
})
diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.ts b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.ts
index 095e494ed4e7..eb3f0df0fc07 100644
--- a/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.ts
@@ -8,9 +8,40 @@ import { isOkResult } from './results'
export type GroupingFunction<TInput, TKey> = (input: TInput) => TKey
+/**
+ * Processes one group's queued chunk: receives the chunk's results in
+ * processing order and returns one result per item. Composed by
+ * GroupProcessingBuilder from pipeChunk steps and sequential per-item stages,
+ * in declaration order.
+ */
+export type GroupChunkProcessor<TIn, TOut, C, RStep extends string> = <RPrev extends string>(
+ items: PipelineResultWithContext<TIn, C, RPrev>[]
+) => Promise<PipelineResultWithContext<TOut, C, RPrev | RStep>[]>
+
+/**
+ * The group chunk stage behind `sequentially`: each OK item runs through the
+ * per-item pipeline one at a time, in input order; non-OK items pass through.
+ */
+export function processGroupChunkSequentially<T, U, C, RStep extends string>(
+ processor: Pipeline<T, U, C, RStep>
+): GroupChunkProcessor<T, U, C, RStep> {
+ return async <RPrev extends string>(items: PipelineResultWithContext<T, C, RPrev>[]) => {
+ const results: PipelineResultWithContext<U, C, RPrev | RStep>[] = []
+ for (const item of items) {
+ if (isOkResult(item.result)) {
+ results.push(await processor.process({ result: item.result, context: item.context }))
+ } else {
+ results.push({ result: item.result, context: item.context })
+ }
+ }
+ return results
+ }
+}
+
/**
* A chunk pipeline that groups inputs by a key and processes each group concurrently.
- * Within each group, items are processed sequentially through the provided pipeline.
+ * Each group's queued chunk runs through a single {@link GroupChunkProcessor},
+ * composed by the builder from chunk steps and sequential per-item stages.
*
* Ordering guarantees:
* - Items within the same group are always processed in order, even across multiple next() calls
@@ -68,7 +99,11 @@ export class ConcurrentlyGroupingChunkPipeline<
constructor(
private groupingFn: GroupingFunction<TIntermediate, TKey>,
- private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,
+ // One processor for a group's whole queued chunk, composed by the
+ // builder from chunk steps and sequential per-item stages. Runs once
+ // per started group chunk: items queued while a group is active form a
+ // new chunk with its own invocation.
+ private processGroupChunk: GroupChunkProcessor<TIntermediate, TOutput, COutput, RStep>,
private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,
maxConcurrency?: number
) {
@@ -159,9 +194,7 @@ export class ConcurrentlyGroupingChunkPipeline<
// The key is claimed in activeProcessing synchronously below, so per-key ordering holds even
// when a group parks waiting for a concurrency permit.
- const run = this.limit
- ? this.limit(() => this.processGroupSequentially(queue))
- : this.processGroupSequentially(queue)
+ const run = this.limit ? this.limit(() => this.processGroupChunk(queue)) : this.processGroupChunk(queue)
const processingPromise = run.then(
(results) => {
this.completedResults.push(results)
@@ -187,27 +220,4 @@ export class ConcurrentlyGroupingChunkPipeline<
this.activeProcessing.set(key, processingPromise)
}
-
- private async processGroupSequentially(
- items: PipelineResultWithContext<TIntermediate, COutput, RPrev | RStep>[]
- ): Promise<PipelineResultWithContext<TOutput, COutput, RPrev | RStep>[]> {
- const results: PipelineResultWithContext<TOutput, COutput, RPrev | RStep>[] = []
-
- for (const item of items) {
- if (isOkResult(item.result)) {
- const result = await this.processor.process({
- result: item.result,
- context: item.context,
- })
- results.push(result)
- } else {
- results.push({
- result: item.result,
- context: item.context,
- })
- }
- }
-
- return results
- }
}
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index ed9cf262103b..b6726f8fe598 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -288,6 +288,8 @@ export class IngestionConsumer {
PERSON_MERGE_EVENTS_ENABLED: effectivePersonMergeEventsEnabled(this.config),
PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
+ PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
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,
diff --git a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
index 7d71d3a87ffb..84b67cf08500 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
@@ -1,4 +1,5 @@
import { AsyncOutput, EVENTS_OUTPUT } from '~/common/outputs'
+import { createImmediateMergeFoldStep } from '~/ingestion/common/persons/person-merge-fold'
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'
@@ -31,90 +32,97 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
const { options, outputs, teamManager, groupTypeManager, hogTransformer, topHog } = config
- return builder
- .pipe(createNormalizeProcessPersonFlagStep())
- .pipe(
- topHog(createHogTransformEventStep(hogTransformer), [
- sumOk(
- 'transformations_run',
- (output) => ({ team_id: String(output.team.id) }),
- (output) => output.transformationsRun
- ),
- sumOk(
- 'transformations_run_per_partition',
- (output, input) => ({
- team_id: String(output.team.id),
- partition: String(input.message.partition),
- }),
- (output) => output.transformationsRun
- ),
- sumResult(
- 'events_dropped_by_transformation',
- (_result, input) => ({ team_id: String(input.team.id) }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- sumResult(
- 'events_dropped_by_transformation_per_partition',
- (_result, input) => ({
- team_id: String(input.team.id),
- partition: String(input.message.partition),
- }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
- )
- .pipe(createNormalizeEventStep())
- .pipe(createProcessAiEventStep())
- .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS), {
- retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
- })
- .pipe(
- topHog(createProcessPersonsStep(options, outputs), [
- timer('process_persons_time', (input) => ({
- team_id: String(input.team.id),
- distinct_id: input.normalizedEvent.distinct_id,
- })),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'process_persons' } }
- )
- .pipe(createPrepareEventStep())
- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options), {
- retry: { tries: 5, sleepMs: 100, name: 'process_groups' },
- })
- .pipe(createCreateEventStep(EVENTS_OUTPUT))
- .pipe(createSplitAiEventsStep())
- .pipe(
- topHog(
- createEmitEventStep({
- outputs,
- }),
- [
- sum(
- 'emitted_events',
- (input) => ({ team_id: String(input.teamId) }),
- (input) => input.eventsToEmit.length
+ return (
+ builder
+ .pipe(createNormalizeProcessPersonFlagStep())
+ .pipe(
+ topHog(createHogTransformEventStep(hogTransformer), [
+ sumOk(
+ 'transformations_run',
+ (output) => ({ team_id: String(output.team.id) }),
+ (output) => output.transformationsRun
),
- sum(
- 'emitted_events_per_distinct_id',
- (input) => ({
- team_id: String(input.teamId),
- distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
+ sumOk(
+ 'transformations_run_per_partition',
+ (output, input) => ({
+ team_id: String(output.team.id),
partition: String(input.message.partition),
}),
- (input) => input.eventsToEmit.length
+ (output) => output.transformationsRun
+ ),
+ sumResult(
+ 'events_dropped_by_transformation',
+ (_result, input) => ({ team_id: String(input.team.id) }),
+ (result) => (isDropResult(result) ? 1 : 0)
),
- sum(
- 'emitted_events_per_partition',
- (input) => ({
- team_id: String(input.teamId),
+ sumResult(
+ 'events_dropped_by_transformation_per_partition',
+ (_result, input) => ({
+ team_id: String(input.team.id),
partition: String(input.message.partition),
}),
- (input) => input.eventsToEmit.length
+ (result) => (isDropResult(result) ? 1 : 0)
),
- ]
- ),
- { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
- )
- .pipe(createRecordIngestionLagStep())
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
+ )
+ .pipe(createNormalizeEventStep())
+ .pipe(createProcessAiEventStep())
+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
+ })
+ // AI events are never merge events, so there are no merges to fold in
+ // this branch: every event processes immediately. The branch itself is
+ // temporary and goes away once ingestion fully switches over to the
+ // dedicated AI pipeline.
+ .pipe(createImmediateMergeFoldStep())
+ .pipe(
+ topHog(createProcessPersonsStep(options, outputs), [
+ timer('process_persons_time', (input) => ({
+ team_id: String(input.team.id),
+ distinct_id: input.normalizedEvent.distinct_id,
+ })),
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'process_persons' } }
+ )
+ .pipe(createPrepareEventStep())
+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_groups' },
+ })
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ .pipe(createSplitAiEventsStep())
+ .pipe(
+ topHog(
+ createEmitEventStep({
+ outputs,
+ }),
+ [
+ sum(
+ 'emitted_events',
+ (input) => ({ team_id: String(input.teamId) }),
+ (input) => input.eventsToEmit.length
+ ),
+ sum(
+ 'emitted_events_per_distinct_id',
+ (input) => ({
+ team_id: String(input.teamId),
+ distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
+ partition: String(input.message.partition),
+ }),
+ (input) => input.eventsToEmit.length
+ ),
+ sum(
+ 'emitted_events_per_partition',
+ (input) => ({
+ team_id: String(input.teamId),
+ partition: String(input.message.partition),
+ }),
+ (input) => input.eventsToEmit.length
+ ),
+ ]
+ ),
+ { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
+ )
+ .pipe(createRecordIngestionLagStep())
+ )
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
index 15f009931c7a..9cc15482f921 100644
--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
@@ -6,6 +6,7 @@ import { IngestionWarningsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { TeamManager } from '~/common/utils/team-manager'
import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'
+import { WithMergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
@@ -64,7 +65,10 @@ export interface EventSubpipelineConfig {
topHog: TopHogWrapper
}
-export function createEventSubpipeline<TInput extends EventSubpipelineInput, TContext>(
+// The WithMergeFoldDecision constraint (not a field on EventSubpipelineInput) is deliberate: the
+// decision is produced by the merge-fold planning step, so only compositions wired after it — or
+// ones that decide `immediate` themselves — can build this subpipeline.
+export function createEventSubpipeline<TInput extends EventSubpipelineInput & WithMergeFoldDecision, TContext>(
builder: StartPipelineBuilder<TInput, TContext>,
config: EventSubpipelineConfig
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 25649d0e3a6c..d93100ce94c1 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -14,6 +14,7 @@ import { EventFilterManager } from '~/ingestion/common/event-filters'
import { FeatureFlagCalledDedupService } from '~/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
+import { createMergeFoldPlanningStep } from '~/ingestion/common/persons/person-merge-fold'
import { PersonsStore } from '~/ingestion/common/persons/persons-store'
import { createDenyEventsStep } from '~/ingestion/common/steps/deny-events'
import {
@@ -181,6 +182,8 @@ export function createJoinedIngestionPipeline<
topHog: topHogWrapper,
}
+ const mergeFoldPlanningStep = createMergeFoldPlanningStep<PerDistinctIdPipelineInput>(perDistinctIdOptions)
+
return (
newCommonIngestionPipeline<TInput, TContext, OverflowOutput | AsyncOutput>({
teamManager,
@@ -222,9 +225,14 @@ export function createJoinedIngestionPipeline<
.pipe(createEnrichSurveyPersonPropertiesStep())
.compose((b) => createPostTeamPreprocessingSubpipeline(b, postTeamConfig))
// Group by token:distinctId and process each group concurrently.
- // Events within each group are processed sequentially.
+ // Events within each group are processed sequentially, after the
+ // merge-fold planning step has scanned the group's chunk. Whether
+ // the step plans anything is its own config-driven decision; when
+ // folding is disabled it passes every event through unplanned.
.concurrentlyPerGroup(getTokenAndDistinctId, (group) =>
- group.sequentially((event) => createPerDistinctIdPipeline(event, perEventConfig))
+ group
+ .pipeChunk(mergeFoldPlanningStep)
+ .sequentially((event) => createPerDistinctIdPipeline(event, perEventConfig))
)
.afterBatch((afterBatch) =>
afterBatch
diff --git a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
index c8cf183e06d9..daf925e34fd0 100644
--- a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
@@ -5,6 +5,7 @@ import { HogTransformer } from '~/common/hog-transformations/hog-transformer.int
import { IngestionWarningsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { TeamManager } from '~/common/utils/team-manager'
+import { WithMergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'
import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
import { AI_EVENT_TYPES } from '~/ingestion/common/subpipelines/ai-event-types'
@@ -60,7 +61,12 @@ function classifyEvent(input: PerDistinctIdPipelineInput): EventBranch {
return EVENT_BRANCH_MAP.get(input.event.event) ?? 'event'
}
-export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipelineInput, TContext>(
+// The event branch's person step consumes the merge-fold decision, so this pipeline requires it on
+// its inputs (the joined pipeline's planning step attaches it); the AI branch ignores it.
+export function createPerDistinctIdPipeline<
+ TInput extends PerDistinctIdPipelineInput & WithMergeFoldDecision,
+ TContext,
+>(
builder: StartPipelineBuilder<TInput, TContext>,
config: PerDistinctIdPipelineConfig
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/extract-heatmap-data-step.ts b/nodejs/src/ingestion/pipelines/heatmaps/extract-heatmap-data-step.ts
index 48470bb23cc9..73bf2b177f8f 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/extract-heatmap-data-step.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/extract-heatmap-data-step.ts
@@ -2,9 +2,9 @@ import { Message } from 'node-rdkafka'
import { URL } from 'url'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { isDistinctIdIllegal } from '~/common/persons/person-utils'
import { logger } from '~/common/utils/logger'
import { castTimestampOrNow } from '~/common/utils/utils'
-import { isDistinctIdIllegal } from '~/ingestion/common/persons/person-merge-service'
import { EmitEventStepOutput, IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'
import { PipelineResult, drop, isOkResult, ok } from '~/ingestion/framework/results'
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index dd9f11c5274c..a6a7c700eff9 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -394,6 +394,8 @@ export class IngestionApiServer implements NodeServer {
PERSON_MERGE_EVENTS_ENABLED: effectivePersonMergeEventsEnabled(this.config),
PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
+ PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
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,
diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
index a29063341373..88d3913a3b9e 100644
--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
@@ -14,10 +14,12 @@ import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
+import { fetchDistinctIdValues } from '~/common/persons/repositories/test-helpers'
import { normalizeEvent, normalizeProcessPerson } from '~/common/utils/event'
import { UUIDT } from '~/common/utils/utils'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
+import { MergeFoldPlan } from '~/ingestion/common/persons/person-merge-fold'
import { BatchBoundPersonsStore } from '~/ingestion/common/persons/persons-store-for-batch'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
import {
@@ -49,6 +51,8 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
+ PERSON_MERGE_FOLD_ENABLED: false,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
@@ -112,6 +116,7 @@ describe('createProcessPersonsStep', () => {
team,
timestamp,
personsStoreForBatch: new BatchBoundPersonsStore(personsStore, 0),
+ mergeFold: { type: 'immediate' },
...overrides,
})
@@ -409,4 +414,266 @@ describe('createProcessPersonsStep', () => {
expect(result.output).toBe(ASYNC_OUTPUT)
}
})
+
+ describe('merge folding', () => {
+ const foldOptions: EventPipelineRunnerOptions = {
+ ...options,
+ PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 0,
+ PERSON_MERGE_SYNC_BATCH_SIZE: 0,
+ PERSON_MERGE_FOLD_ENABLED: true,
+ }
+
+ function identifyEvent(
+ anonDistinctId: string,
+ targetDistinctId: string,
+ set: Record<string, any> = {}
+ ): PluginEvent {
+ return {
+ ...pluginEvent,
+ event: '$identify',
+ distinct_id: targetDistinctId,
+ uuid: new UUIDT().toString(),
+ properties: { $anon_distinct_id: anonDistinctId, $set: set },
+ }
+ }
+
+ function planFor(targetDistinctId: string, ...anonDistinctIds: string[]): MergeFoldPlan {
+ return {
+ targetDistinctId,
+ pairs: anonDistinctIds.map((anonDistinctId) => ({
+ anonDistinctId,
+ eventUuid: new UUIDT().toString(),
+ })),
+ status: 'planned',
+ }
+ }
+
+ async function createPersonWithProps(
+ distinctId: string,
+ properties: Record<string, any>,
+ isIdentified: boolean = false
+ ) {
+ const result = await personRepository.createPerson(
+ DateTime.utc(),
+ properties,
+ {},
+ {},
+ teamId,
+ null,
+ isIdentified,
+ new UUIDT().toString(),
+ { distinctId }
+ )
+ if (!result.success) {
+ throw new Error(`Failed to create person with distinct_id ${distinctId}`)
+ }
+ return result.person
+ }
+
+ async function runIdentifies(
+ events: PluginEvent[],
+ plan: MergeFoldPlan | undefined,
+ stepOptions: EventPipelineRunnerOptions
+ ) {
+ const step = createProcessPersonsStep(stepOptions, personOutputs)
+ const results = []
+ for (const event of events) {
+ const result = await step(
+ createInput({
+ normalizedEvent: event,
+ timestamp: DateTime.fromISO(event.timestamp!),
+ mergeFold: plan ? { type: 'planned', plan } : { type: 'immediate' },
+ })
+ )
+ expect(isOkResult(result)).toBe(true)
+ results.push(result)
+ }
+ return results
+ }
+
+ it('produces the same persons as sequential merges for a storm of identifies', async () => {
+ // Sequential arm
+ await createPersonWithProps('seq-anon-1', { a: 1, shared: 'first' })
+ await createPersonWithProps('seq-anon-2', { b: 2, shared: 'second' })
+ await createPersonWithProps('seq-user', { t: 1 })
+ await runIdentifies(
+ [
+ identifyEvent('seq-anon-1', 'seq-user', { s1: true }),
+ identifyEvent('seq-anon-2', 'seq-user', { s2: true }),
+ ],
+ undefined,
+ foldOptions
+ )
+
+ // Folded arm, identical fixtures under different distinct ids
+ await createPersonWithProps('fold-anon-1', { a: 1, shared: 'first' })
+ await createPersonWithProps('fold-anon-2', { b: 2, shared: 'second' })
+ await createPersonWithProps('fold-user', { t: 1 })
+ const plan = planFor('fold-user', 'fold-anon-1', 'fold-anon-2')
+ await runIdentifies(
+ [
+ identifyEvent('fold-anon-1', 'fold-user', { s1: true }),
+ identifyEvent('fold-anon-2', 'fold-user', { s2: true }),
+ ],
+ plan,
+ foldOptions
+ )
+
+ expect(plan.status).toBe('executed')
+ // Person-row updates (merged properties, is_identified) are buffered
+ // by the batch-writing store in both paths; flush to compare final state.
+ await personsStore.flush()
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(2)
+ const foldPerson = persons.find((p) => p.id === plan.mergedPerson!.id)!
+ const sequential = persons.find((p) => p.id !== foldPerson.id)!
+
+ expect(foldPerson.properties).toEqual(sequential.properties)
+ expect(foldPerson.is_identified).toBe(true)
+ const seqDistinctIds = await fetchDistinctIdValues(infra.postgres, sequential)
+ const foldDistinctIds = await fetchDistinctIdValues(infra.postgres, foldPerson)
+ expect(seqDistinctIds.sort()).toEqual(['seq-anon-1', 'seq-anon-2', 'seq-user'])
+ expect(foldDistinctIds.sort()).toEqual(['fold-anon-1', 'fold-anon-2', 'fold-user'])
+ })
+
+ it('short-circuits later events in an executed run without extra persons', async () => {
+ await createPersonWithProps('anon-1', { a: 1 })
+ await createPersonWithProps('anon-2', { b: 2 })
+ await createPersonWithProps('user-1', {})
+ const plan = planFor('user-1', 'anon-1', 'anon-2')
+
+ const results = await runIdentifies(
+ [identifyEvent('anon-1', 'user-1'), identifyEvent('anon-2', 'user-1')],
+ plan,
+ foldOptions
+ )
+
+ expect(plan.status).toBe('executed')
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(1)
+ for (const result of results) {
+ if (isOkResult(result)) {
+ expect(result.value.person.uuid).toBe(persons[0].uuid)
+ }
+ }
+ })
+
+ it('skips already-identified sources with a warning and folds the rest', async () => {
+ await createPersonWithProps('anon-identified', { a: 1 }, true)
+ await createPersonWithProps('anon-2', { b: 2 })
+ await createPersonWithProps('user-1', {})
+ const plan = planFor('user-1', 'anon-identified', 'anon-2')
+
+ await runIdentifies([identifyEvent('anon-identified', 'user-1')], plan, foldOptions)
+
+ expect(plan.status).toBe('executed')
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(2)
+ const target = persons.find((p) => p.id === plan.mergedPerson!.id)!
+ const targetDistinctIds = await fetchDistinctIdValues(infra.postgres, target)
+ expect(targetDistinctIds.sort()).toEqual(['anon-2', 'user-1'])
+ })
+
+ it('bootstraps a missing target and folds remaining pairs, including personless adds', async () => {
+ await createPersonWithProps('anon-1', { a: 1 })
+ // anon-2 has no person row (personless-style)
+ const plan = planFor('user-1', 'anon-1', 'anon-2')
+
+ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, foldOptions)
+
+ expect(plan.status).toBe('executed')
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(1)
+ const distinctIds = await fetchDistinctIdValues(infra.postgres, persons[0])
+ expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])
+ })
+
+ it('folds under LIMIT merge mode when sources are within the move limit', async () => {
+ await createPersonWithProps('anon-1', { a: 1 })
+ await createPersonWithProps('anon-2', { b: 2 })
+ await createPersonWithProps('user-1', {})
+ const plan = planFor('user-1', 'anon-1', 'anon-2')
+
+ // Default options carry PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT=100 (LIMIT mode)
+ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, {
+ ...options,
+ PERSON_MERGE_FOLD_ENABLED: true,
+ })
+
+ expect(plan.status).toBe('executed')
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(1)
+ const distinctIds = await fetchDistinctIdValues(infra.postgres, persons[0])
+ expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])
+ })
+
+ it('abandons the fold when a source exceeds the move limit and merges sequentially', async () => {
+ const bigSource = await createPersonWithProps('anon-1', { a: 1 })
+ await personRepository.addDistinctId(bigSource, 'anon-1-extra-1', 0)
+ await personRepository.addDistinctId(bigSource, 'anon-1-extra-2', 0)
+ await createPersonWithProps('anon-2', { b: 2 })
+ await createPersonWithProps('user-1', {})
+ const plan = planFor('user-1', 'anon-1', 'anon-2')
+
+ // LIMIT mode with a limit of 2: anon-1 owns 3 distinct ids, so the
+ // fold must roll back; the sequential path then DLQs anon-1's merge
+ // per-event while anon-2 still merges normally.
+ await runIdentifies([identifyEvent('anon-2', 'user-1')], plan, {
+ ...options,
+ PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 2,
+ PERSON_MERGE_FOLD_ENABLED: true,
+ })
+
+ expect(plan.status).toBe('abandoned')
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ // anon-1's person survives untouched; anon-2 merged into user-1
+ expect(persons).toHaveLength(2)
+ const target = persons.find((p) => p.id !== bigSource.id)!
+ const distinctIds = await fetchDistinctIdValues(infra.postgres, target)
+ expect(distinctIds.sort()).toEqual(['anon-2', 'user-1'])
+ })
+
+ it('merges sequentially after a mid-transaction fold failure poisons the batch caches', async () => {
+ await createPersonWithProps('anon-1', { a: 1 })
+ await createPersonWithProps('user-1', { t: 1 })
+ const plan = planFor('user-1', 'anon-1', 'anon-2')
+
+ // Fail the fold after the move has already updated the batch
+ // caches; the rollback leaves them pointing anon-1 at the target.
+ // Without the cache purge, the sequential fallback resolves anon-1
+ // to the target from cache and skips a merge that never committed.
+ jest.spyOn(personRepository, 'deletePersons').mockRejectedValueOnce(new Error('fold delete failed'))
+
+ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, foldOptions)
+
+ expect(plan.status).toBe('abandoned')
+ // The sequential fallback merges the current event's pair correctly
+ // (anon-2's pair had no event of its own in this test)
+ await personsStore.flush()
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(1)
+ const distinctIds = await fetchDistinctIdValues(infra.postgres, persons[0])
+ expect(distinctIds.sort()).toEqual(['anon-1', 'user-1'])
+ expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1, t: 1 }))
+ })
+
+ it('abandons the fold when sources changed between fetch and transaction', async () => {
+ await createPersonWithProps('anon-1', { a: 1 })
+ await createPersonWithProps('user-1', {})
+ const plan = planFor('user-1', 'anon-1')
+
+ // Simulate a concurrent merge emptying the source between the
+ // locked fetch and the transaction's count.
+ jest.spyOn(personRepository, 'countDistinctIdsForPersons').mockResolvedValueOnce(new Map())
+
+ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, foldOptions)
+
+ expect(plan.status).toBe('abandoned')
+ // The sequential fallback still completes the merge correctly
+ const persons = await fetchPostgresPersons(infra.postgres, teamId)
+ expect(persons).toHaveLength(1)
+ const distinctIds = await fetchDistinctIdValues(infra.postgres, persons[0])
+ expect(distinctIds.sort()).toEqual(['anon-1', 'user-1'])
+ })
+ })
})
diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.ts
index 8f72a1444e1f..6edc1c2de267 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts
@@ -35,1089 +35,1285 @@ jest.mock('~/common/utils/token-bucket', () => {
jest.mock('~/common/utils/logger')
-describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED: true }])(
- 'Event Pipeline E2E tests (prefetch=$PERSONS_PREFETCH_ENABLED)',
- (prefetchConfig) => {
- const testWithTeamIngester = createTestWithTeamIngester(prefetchConfig, (infra, kafkaProducer) => {
- const outputs = createTestIngestionOutputs(kafkaProducer)
- const ingester = new IngestionConsumer(infra.config, {
+describe.each([
+ { PERSONS_PREFETCH_ENABLED: true, PERSON_MERGE_FOLD_ENABLED: false },
+ { PERSONS_PREFETCH_ENABLED: true, PERSON_MERGE_FOLD_ENABLED: true },
+])('Event Pipeline E2E tests (fold=$PERSON_MERGE_FOLD_ENABLED)', (pipelineConfig) => {
+ const testWithTeamIngester = createTestWithTeamIngester(pipelineConfig, (infra, kafkaProducer) => {
+ const outputs = createTestIngestionOutputs(kafkaProducer)
+ const ingester = new IngestionConsumer(infra.config, {
+ postgres: infra.postgres,
+ redisPool: infra.redisPool,
+ teamManager: infra.teamManager,
+ groupTypeManager: infra.groupTypeManager,
+ groupRepository: infra.groupRepository,
+ personRepository: infra.personRepository,
+ cookielessManager: infra.cookielessManager,
+ outputs,
+ clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),
+ aiSubpipelineFactory: createAiEventSubpipeline,
+ hogTransformer: createHogTransformerService(infra.config, {
+ geoipService: infra.geoipService,
postgres: infra.postgres,
- redisPool: infra.redisPool,
+ pubSub: infra.pubSub,
+ encryptedFields: infra.encryptedFields,
+ integrationManager: infra.integrationManager,
+ monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
teamManager: infra.teamManager,
- groupTypeManager: infra.groupTypeManager,
- groupRepository: infra.groupRepository,
- personRepository: infra.personRepository,
- cookielessManager: infra.cookielessManager,
- outputs,
- clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),
- aiSubpipelineFactory: createAiEventSubpipeline,
- hogTransformer: createHogTransformerService(infra.config, {
- geoipService: infra.geoipService,
- postgres: infra.postgres,
- pubSub: infra.pubSub,
- encryptedFields: infra.encryptedFields,
- integrationManager: infra.integrationManager,
- monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
- teamManager: infra.teamManager,
- }),
- })
- jest.spyOn(infra.groupRepository, 'fetchGroup')
- jest.spyOn(infra.groupRepository, 'insertGroup')
- jest.spyOn(infra.groupRepository, 'updateGroup')
- jest.spyOn(infra.groupRepository, 'updateGroupOptimistically')
- return ingester
- })
- let clickhouse: Clickhouse
- beforeAll(async () => {
- console.log('Creating Clickhouse client')
- clickhouse = Clickhouse.create()
- await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
- await waitForClickHouseKafkaConsumer(clickhouse)
- process.env.SITE_URL = 'https://example.com'
+ }),
})
+ jest.spyOn(infra.groupRepository, 'fetchGroup')
+ jest.spyOn(infra.groupRepository, 'insertGroup')
+ jest.spyOn(infra.groupRepository, 'updateGroup')
+ jest.spyOn(infra.groupRepository, 'updateGroupOptimistically')
+ return ingester
+ })
+ let clickhouse: Clickhouse
+ beforeAll(async () => {
+ console.log('Creating Clickhouse client')
+ clickhouse = Clickhouse.create()
+ await ensureKafkaTopics(TEST_KAFKA_TOPICS)
+ await resetTestDatabase()
+ await clickhouse.resetTestDatabase()
+ await waitForClickHouseKafkaConsumer(clickhouse)
+ process.env.SITE_URL = 'https://example.com'
+ })
+
+ afterAll(async () => {
+ await resetTestDatabase()
+ await clickhouse.resetTestDatabase()
+ clickhouse.close()
+ })
+
+ testWithTeamIngester(
+ 'should process events without a team_id',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const events = [new EventBuilder(team).withEvent('test event').build()]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+
+ await waitForKafkaMessages(kafkaProducer)
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
- clickhouse.close()
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].team_id).toBe(team.id)
+ })
+ }
+ )
- testWithTeamIngester(
- 'should process events without a team_id',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const events = [new EventBuilder(team).withEvent('test event').build()]
+ testWithTeamIngester(
+ 'can set and update group properties with $groupidentify events',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const groupKey = 'group_key'
+ const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ const events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', groupKey, { foo: 'bar' })
+ .build(),
+ ]
- await waitForKafkaMessages(kafkaProducer)
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].team_id).toBe(team.id)
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
+ expect(group).toEqual(
+ expect.objectContaining({
+ team_id: team.id,
+ group_type_index: 0,
+ group_properties: { foo: 'bar' },
+ group_key: groupKey,
+ version: 1,
+ })
+ )
+ })
- testWithTeamIngester(
- 'can set and update group properties with $groupidentify events',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const groupKey = 'group_key'
- const distinctId = new UUIDT().toString()
+ const updateEvents = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', groupKey, { prop: 'value' })
+ .build(),
+ ]
- const events = [
- new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', groupKey, { foo: 'bar' })
- .build(),
- ]
+ await ingester.handleKafkaBatch(createKafkaMessages(updateEvents, token))
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
- expect(group).toEqual(
- expect.objectContaining({
- team_id: team.id,
- group_type_index: 0,
- group_properties: { foo: 'bar' },
- group_key: groupKey,
- version: 1,
- })
- )
- })
+ await waitForExpect(async () => {
+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
+ expect(group).toEqual(
+ expect.objectContaining({
+ team_id: team.id,
+ group_type_index: 0,
+ group_properties: { foo: 'bar', prop: 'value' },
+ group_key: groupKey,
+ version: 2,
+ })
+ )
+ })
+
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ expect(events[0].event).toEqual('$groupidentify')
+ expect(events[0].properties.$group_set).toEqual({ foo: 'bar' })
+ expect(events[1].event).toEqual('$groupidentify')
+ expect(events[1].properties.$group_set).toEqual({ prop: 'value' })
+ })
- const updateEvents = [
+ // Should have fetched the group 4 times:
+ // 1 for each event and 2 in test check
+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)
+ }
+ )
+
+ testWithTeamIngester(
+ 'can handle high amount of $groupidentify in same batch',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const n = 150
+ const distinctId = new UUIDT().toString()
+ const events = []
+ for (let i = 0; i < n; i++) {
+ const m: Record<string, number> = {}
+ m[i.toString()] = i
+ events.push(
new EventBuilder(team, distinctId)
.withEvent('$groupidentify')
- .withGroupProperties('organization', groupKey, { prop: 'value' })
- .build(),
- ]
+ .withGroupProperties('organization', 'group_key', m)
+ .build()
+ )
+ }
- await ingester.handleKafkaBatch(createKafkaMessages(updateEvents, token))
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
- expect(group).toEqual(
- expect.objectContaining({
- team_id: team.id,
- group_type_index: 0,
- group_properties: { foo: 'bar', prop: 'value' },
- group_key: groupKey,
- version: 2,
- })
- )
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(n)
+ })
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- expect(events[0].event).toEqual('$groupidentify')
- expect(events[0].properties.$group_set).toEqual({ foo: 'bar' })
- expect(events[1].event).toEqual('$groupidentify')
- expect(events[1].properties.$group_set).toEqual({ prop: 'value' })
- })
+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)
+ expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)
+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ }
+ )
- // Should have fetched the group 4 times:
- // 1 for each event and 2 in test check
- expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)
- }
- )
+ testWithTeamIngester(
+ 'can handle multiple $groupidentify in same batch',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const timestamp = DateTime.now().toMillis()
+ const distinctId = new UUIDT().toString()
+ const groupKey = 'group_key'
+
+ const events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', groupKey, { k1: 'v1' })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', groupKey, { k2: 'v2', k3: 'v2' })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', groupKey, { k2: 'v3', k4: 'v3' })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- testWithTeamIngester(
- 'can handle high amount of $groupidentify in same batch',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const n = 150
- const distinctId = new UUIDT().toString()
- const events = []
- for (let i = 0; i < n; i++) {
- const m: Record<string, number> = {}
- m[i.toString()] = i
- events.push(
- new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', 'group_key', m)
- .build()
- )
- }
+ await waitForExpect(async () => {
+ await waitForKafkaMessages(kafkaProducer)
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events[0].event).toEqual('$groupidentify')
+ expect(events[0].properties.$group_set).toEqual({ k1: 'v1' })
+ expect(events[1].event).toEqual('$groupidentify')
+ expect(events[1].properties.$group_set).toEqual({ k2: 'v2', k3: 'v2' })
+ expect(events[2].event).toEqual('$groupidentify')
+ expect(events[2].properties.$group_set).toEqual({ k2: 'v3', k4: 'v3' })
+ })
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)
+ expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)
+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
+ expect(group).toEqual(
+ expect.objectContaining({
+ team_id: team.id,
+ group_type_index: 0,
+ group_properties: { k1: 'v1', k2: 'v3', k3: 'v2', k4: 'v3' },
+ group_key: groupKey,
+ // Just one write after the creation of the group
+ version: 2,
+ })
+ )
+ })
+ }
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(n)
- })
+ testWithTeamIngester(
+ 'can handle $groupidentify with no properties',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const events = [new EventBuilder(team).withEvent('$groupidentify').withProperties({}).build()]
- expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
- expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)
- expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
- }
- )
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- testWithTeamIngester(
- 'can handle multiple $groupidentify in same batch',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const timestamp = DateTime.now().toMillis()
- const distinctId = new UUIDT().toString()
- const groupKey = 'group_key'
+ await waitForKafkaMessages(kafkaProducer)
- const events = [
- new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', groupKey, { k1: 'v1' })
- .withTimestamp(timestamp)
- .build(),
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(1)
+ expect(events[0].event).toEqual('$groupidentify')
+ expect(events[0].properties).toEqual({})
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'can handle multiple $groupidentify for different distinct ids',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const n = 50
+ const distinctIds = []
+ for (let i = 0; i < n; i++) {
+ distinctIds.push(new UUIDT().toString())
+ }
+
+ const events = []
+ for (const distinctId of distinctIds) {
+ events.push(
new EventBuilder(team, distinctId)
.withEvent('$groupidentify')
- .withGroupProperties('organization', groupKey, { k2: 'v2', k3: 'v2' })
- .withTimestamp(timestamp + 1)
- .build(),
+ .withGroupProperties('organization', distinctId, { foo: 'bar' })
+ .build()
+ )
+ events.push(
new EventBuilder(team, distinctId)
.withEvent('$groupidentify')
- .withGroupProperties('organization', groupKey, { k2: 'v3', k4: 'v3' })
- .withTimestamp(timestamp + 2)
- .build(),
- ]
+ .withGroupProperties('organization', distinctId, { update: 'new' })
+ .build()
+ )
+ }
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ // handle 100 events in one batch
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForExpect(async () => {
- await waitForKafkaMessages(kafkaProducer)
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events[0].event).toEqual('$groupidentify')
- expect(events[0].properties.$group_set).toEqual({ k1: 'v1' })
- expect(events[1].event).toEqual('$groupidentify')
- expect(events[1].properties.$group_set).toEqual({ k2: 'v2', k3: 'v2' })
- expect(events[2].event).toEqual('$groupidentify')
- expect(events[2].properties.$group_set).toEqual({ k2: 'v3', k4: 'v3' })
- })
+ await waitForKafkaMessages(kafkaProducer)
- expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
- expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)
- expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(n * 2)
+ })
+ for (const distinctId of distinctIds) {
await waitForExpect(async () => {
- const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)
+ const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)
expect(group).toEqual(
expect.objectContaining({
team_id: team.id,
group_type_index: 0,
- group_properties: { k1: 'v1', k2: 'v3', k3: 'v2', k4: 'v3' },
- group_key: groupKey,
- // Just one write after the creation of the group
+ group_properties: { foo: 'bar', update: 'new' },
version: 2,
})
)
})
}
- )
+ }
+ )
+
+ testWithTeamIngester(
+ 'can handle multiple $groupidentify for different distinct ids',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const n = 50
+ const distinctIds = []
+ for (let i = 0; i < n; i++) {
+ distinctIds.push(new UUIDT().toString())
+ }
+
+ const events = []
+ for (const distinctId of distinctIds) {
+ events.push(
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', distinctId, { foo: 'bar' })
+ .build()
+ )
+ events.push(
+ new EventBuilder(team, distinctId)
+ .withEvent('$groupidentify')
+ .withGroupProperties('organization', distinctId, { update: 'new' })
+ .build()
+ )
+ }
- testWithTeamIngester(
- 'can handle $groupidentify with no properties',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const events = [new EventBuilder(team).withEvent('$groupidentify').withProperties({}).build()]
+ // handle 100 events in one batch
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(n * 2)
+ })
+ for (const distinctId of distinctIds) {
await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(1)
- expect(events[0].event).toEqual('$groupidentify')
- expect(events[0].properties).toEqual({})
+ const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)
+ expect(group).toEqual(
+ expect.objectContaining({
+ team_id: team.id,
+ group_type_index: 0,
+ group_properties: { foo: 'bar', update: 'new' },
+ version: 2,
+ })
+ )
})
}
- )
-
- testWithTeamIngester(
- 'can handle multiple $groupidentify for different distinct ids',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const n = 50
- const distinctIds = []
- for (let i = 0; i < n; i++) {
- distinctIds.push(new UUIDT().toString())
- }
+ }
+ )
- const events = []
- for (const distinctId of distinctIds) {
- events.push(
+ testWithTeamIngester(
+ 'can $set and update person properties when reading event',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', distinctId, { foo: 'bar' })
- .build()
- )
- events.push(
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop: 'value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', distinctId, { update: 'new' })
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop: 'updated value' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { value: 'new value' },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
+ )
+ )
+
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[1].event).toEqual('$identify')
+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'updated value' }))
+ expect(events[2].event).toEqual('$identify')
+ expect(events[2].person_properties).toEqual(
+ expect.objectContaining({ prop: 'updated value', value: 'new value' })
+ )
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'merges a storm of $identify events for one distinct_id into a single person',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const userId = new UUIDT().toString()
+ const anonIds = [1, 2, 3].map((i) => `storm-anon-${i}-${userId}`)
+ const timestamp = DateTime.now().toMillis()
+
+ // Seed one person per anon id with its own property
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ anonIds.map((anonId, i) =>
+ new EventBuilder(team, anonId)
+ .withEvent('seed event')
+ .withProperties({ $set: { [`anon_prop_${i}`]: i } })
+ .withTimestamp(timestamp)
.build()
- )
- }
+ ),
+ token
+ )
+ )
- // handle 100 events in one batch
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ // The storm: consecutive $identify events for the same target distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ anonIds.map((anonId, i) =>
+ new EventBuilder(team, userId)
+ .withEvent('$identify')
+ .withProperties({
+ $anon_distinct_id: anonId,
+ $set: { [`identify_prop_${i}`]: i },
+ })
+ .withTimestamp(timestamp + 1 + i)
+ .build()
+ ),
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ const identifies = events.filter((event) => event.event === '$identify')
+ expect(identifies.length).toBe(anonIds.length)
+ // All identifies resolve to one person
+ expect(new Set(identifies.map((event) => event.person_id)).size).toBe(1)
+ })
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(n * 2)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons).toHaveLength(1)
+ const person = persons[0]
+ expect(person.is_identified).toBe(true)
+ expect(person.properties).toEqual(
+ expect.objectContaining({
+ anon_prop_0: 0,
+ anon_prop_1: 1,
+ anon_prop_2: 2,
+ identify_prop_0: 0,
+ identify_prop_1: 1,
+ identify_prop_2: 2,
})
+ )
+ const distinctIds = (await fetchDistinctIds(infra.postgres, person)).map((pdi) => pdi.distinct_id)
+ expect(distinctIds.sort()).toEqual([...anonIds, userId].sort())
+ }
+ )
+
+ testWithTeamIngester(
+ 'per-event person property snapshots for a consecutive $identify run',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Documents the fold's one intentional behavior delta: in a folded
+ // run, every source person's properties land on the target when
+ // the run's first event executes, so the first $identify's emitted
+ // snapshot already carries the later sources' properties. The
+ // sequential path lands them event by event. Final person state is
+ // identical either way.
+ const userId = `user-${new UUIDT().toString()}`
+ const anonA = `anon-a-${userId}`
+ const anonB = `anon-b-${userId}`
+ const timestamp = DateTime.now().toMillis()
- for (const distinctId of distinctIds) {
- await waitForExpect(async () => {
- const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)
- expect(group).toEqual(
- expect.objectContaining({
- team_id: team.id,
- group_type_index: 0,
- group_properties: { foo: 'bar', update: 'new' },
- version: 2,
- })
- )
- })
- }
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, anonA)
+ .withEvent('seed a')
+ .withProperties({ $set: { from_a: true } })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, anonB)
+ .withEvent('seed b')
+ .withProperties({ $set: { from_b: true } })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
+ )
+ )
+
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, userId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonA, $set: { i1: true } })
+ .withTimestamp(timestamp + 10)
+ .build(),
+ new EventBuilder(team, userId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonB, $set: { i2: true } })
+ .withTimestamp(timestamp + 20)
+ .build(),
+ new EventBuilder(team, userId)
+ .withEvent('after event')
+ .withTimestamp(timestamp + 30)
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(5)
+ })
+
+ const events = await fetchEvents(clickhouse, team.id)
+ const identify1 = events.find(
+ (event) => event.event === '$identify' && event.properties.$anon_distinct_id === anonA
+ )!
+ const identify2 = events.find(
+ (event) => event.event === '$identify' && event.properties.$anon_distinct_id === anonB
+ )!
+ const after = events.find((event) => event.event === 'after event')!
+
+ // The first identify always has its own source's properties and
+ // $set, and never a later event's $set.
+ expect(identify1.person_properties).toEqual(expect.objectContaining({ from_a: true, i1: true }))
+ expect(identify1.person_properties).not.toHaveProperty('i2')
+ if (pipelineConfig.PERSON_MERGE_FOLD_ENABLED) {
+ // Folded: B's person properties landed with the fold, before
+ // identify1's row was emitted.
+ expect(identify1.person_properties).toEqual(expect.objectContaining({ from_b: true }))
+ } else {
+ // Sequential: B's person merges only at identify2.
+ expect(identify1.person_properties).not.toHaveProperty('from_b')
}
- )
- testWithTeamIngester(
- 'can handle multiple $groupidentify for different distinct ids',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const n = 50
- const distinctIds = []
- for (let i = 0; i < n; i++) {
- distinctIds.push(new UUIDT().toString())
- }
+ // From the second identify onward the arms are indistinguishable.
+ expect(identify2.person_properties).toEqual(
+ expect.objectContaining({ from_a: true, from_b: true, i1: true, i2: true })
+ )
+ expect(after.person_properties).toEqual(
+ expect.objectContaining({ from_a: true, from_b: true, i1: true, i2: true })
+ )
+
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons).toHaveLength(1)
+ expect(persons[0].is_identified).toBe(true)
+ expect(persons[0].properties).toEqual(
+ expect.objectContaining({ from_a: true, from_b: true, i1: true, i2: true })
+ )
+ }
+ )
+
+ testWithTeamIngester(
+ '$identify and $set events force person property updates even for filtered properties',
+ {},
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- const events = []
- for (const distinctId of distinctIds) {
- events.push(
+ // Chain of events: normal event with filtered props, then $identify with filtered props, then another normal event
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // Event 1: Normal pageview with filtered properties (should be ignored on its own)
new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', distinctId, { foo: 'bar' })
- .build()
- )
- events.push(
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { $browser: 'Chrome', utm_source: 'google' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ // Event 2: $identify with ONLY filtered properties (should force update)
new EventBuilder(team, distinctId)
- .withEvent('$groupidentify')
- .withGroupProperties('organization', distinctId, { update: 'new' })
- .build()
- )
- }
+ .withEvent('$identify')
+ .withProperties({
+ $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ // Event 3: Another normal event with filtered properties
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { utm_source: 'facebook' },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
+ )
+ )
- // handle 100 events in one batch
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
- await waitForKafkaMessages(kafkaProducer)
+ // Event 0 (first pageview): Should have properties from first event only
+ expect(events[0].person_properties).toEqual({
+ $browser: 'Chrome',
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'google',
+ })
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(n * 2)
+ // Event 1 ($identify): Should have accumulated properties from first two events
+ expect(events[1].person_properties).toEqual({
+ $browser: 'Safari', // Updated by $identify
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'google', // Still from first event
+ $geoip_city_name: 'San Francisco', // Added by $identify
})
- for (const distinctId of distinctIds) {
- await waitForExpect(async () => {
- const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)
- expect(group).toEqual(
- expect.objectContaining({
- team_id: team.id,
- group_type_index: 0,
- group_properties: { foo: 'bar', update: 'new' },
- version: 2,
- })
- )
- })
- }
- }
- )
+ // Event 2 (last pageview): Should have all accumulated properties
+ expect(events[2].person_properties).toEqual({
+ $browser: 'Safari', // From $identify
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'facebook', // Updated by this event
+ $geoip_city_name: 'San Francisco', // From $identify
+ })
- testWithTeamIngester(
- 'can $set and update person properties when reading event',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop: 'value' },
- })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop: 'updated value' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { value: 'new value' },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
- )
-
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[1].event).toEqual('$identify')
- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'updated value' }))
- expect(events[2].event).toEqual('$identify')
- expect(events[2].person_properties).toEqual(
- expect.objectContaining({ prop: 'updated value', value: 'new value' })
- )
+ // Verify the final state of the person in the database
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual({
+ $browser: 'Safari',
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'facebook',
+ $geoip_city_name: 'San Francisco',
})
- }
- )
+ // last_seen_at should be set
+ expect(person!.last_seen_at).toBeDefined()
+ expect(person!.last_seen_at!.minute).toBe(0)
+ expect(person!.last_seen_at!.second).toBe(0)
+ })
+ }
+ )
- testWithTeamIngester(
- '$identify and $set events force person property updates even for filtered properties',
- {},
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ '$set events force person property updates even for filtered properties',
+ {},
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Chain of events: normal event with filtered props, then $identify with filtered props, then another normal event
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // Event 1: Normal pageview with filtered properties (should be ignored on its own)
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { $browser: 'Chrome', utm_source: 'google' },
- })
- .withTimestamp(timestamp)
- .build(),
- // Event 2: $identify with ONLY filtered properties (should force update)
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- // Event 3: Another normal event with filtered properties
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { utm_source: 'facebook' },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ // Similar test but with $set event instead of $identify
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // Event 1: Normal event with filtered properties
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { $browser: 'Chrome' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ // Event 2: $set event with filtered properties (should force update)
+ new EventBuilder(team, distinctId)
+ .withEvent('$set')
+ .withProperties({
+ $set: { utm_source: 'twitter', $geoip_country_code: 'US' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
-
- // Event 0 (first pageview): Should have properties from first event only
- expect(events[0].person_properties).toEqual({
- $browser: 'Chrome',
- $creator_event_uuid: events[0].uuid,
- utm_source: 'google',
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
- // Event 1 ($identify): Should have accumulated properties from first two events
- expect(events[1].person_properties).toEqual({
- $browser: 'Safari', // Updated by $identify
- $creator_event_uuid: events[0].uuid,
- utm_source: 'google', // Still from first event
- $geoip_city_name: 'San Francisco', // Added by $identify
- })
+ // Event 0 (first pageview): Should have properties from first event only
+ expect(events[0].person_properties).toEqual({
+ $browser: 'Chrome',
+ $creator_event_uuid: events[0].uuid,
+ })
- // Event 2 (last pageview): Should have all accumulated properties
- expect(events[2].person_properties).toEqual({
- $browser: 'Safari', // From $identify
- $creator_event_uuid: events[0].uuid,
- utm_source: 'facebook', // Updated by this event
- $geoip_city_name: 'San Francisco', // From $identify
- })
+ // Event 1 ($set): Should have accumulated properties from both events
+ expect(events[1].person_properties).toEqual({
+ $browser: 'Chrome', // From first event
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'twitter', // From $set event
+ $geoip_country_code: 'US', // From $set event
+ })
- // Verify the final state of the person in the database
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual({
- $browser: 'Safari',
- $creator_event_uuid: events[0].uuid,
- utm_source: 'facebook',
- $geoip_city_name: 'San Francisco',
- })
- // last_seen_at should be set
- expect(person!.last_seen_at).toBeDefined()
- expect(person!.last_seen_at!.minute).toBe(0)
- expect(person!.last_seen_at!.second).toBe(0)
+ // Verify the final state of the person in the database
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual({
+ $browser: 'Chrome',
+ $creator_event_uuid: events[0].uuid,
+ utm_source: 'twitter',
+ $geoip_country_code: 'US',
})
- }
- )
+ // last_seen_at should be set to hour-rounded timestamp
+ expect(person!.last_seen_at).toBeDefined()
+ expect(person!.last_seen_at!.minute).toBe(0)
+ expect(person!.last_seen_at!.second).toBe(0)
+ })
+ }
+ )
- testWithTeamIngester(
- '$set events force person property updates even for filtered properties',
- {},
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'PERSON_PROPERTIES_UPDATE_ALL flag enables updates for normally filtered properties',
+ { pluginServerConfig: { PERSON_PROPERTIES_UPDATE_ALL: true } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Similar test but with $set event instead of $identify
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // Event 1: Normal event with filtered properties
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { $browser: 'Chrome' },
- })
- .withTimestamp(timestamp)
- .build(),
- // Event 2: $set event with filtered properties (should force update)
- new EventBuilder(team, distinctId)
- .withEvent('$set')
- .withProperties({
- $set: { utm_source: 'twitter', $geoip_country_code: 'US' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // With PERSON_PROPERTIES_UPDATE_ALL=true, even normal pageview events should update
+ // filtered properties like $browser, $geoip_*, etc.
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // Event 1: Normal pageview that creates the person with initial properties
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { $browser: 'Chrome', $geoip_city_name: 'New York' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ // Event 2: Another normal pageview with updated filtered properties
+ // With the flag enabled, these should trigger a person update
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
- // Event 0 (first pageview): Should have properties from first event only
- expect(events[0].person_properties).toEqual({
- $browser: 'Chrome',
- $creator_event_uuid: events[0].uuid,
- })
+ // Event 0 (first pageview): Should have initial properties
+ expect(events[0].person_properties).toEqual({
+ $browser: 'Chrome',
+ $creator_event_uuid: events[0].uuid,
+ $geoip_city_name: 'New York',
+ })
- // Event 1 ($set): Should have accumulated properties from both events
- expect(events[1].person_properties).toEqual({
- $browser: 'Chrome', // From first event
- $creator_event_uuid: events[0].uuid,
- utm_source: 'twitter', // From $set event
- $geoip_country_code: 'US', // From $set event
- })
+ // Event 1 (second pageview): Should have UPDATED properties
+ // This is the key difference - without the flag, these would still show the old values
+ expect(events[1].person_properties).toEqual({
+ $browser: 'Safari',
+ $creator_event_uuid: events[0].uuid,
+ $geoip_city_name: 'San Francisco',
+ })
- // Verify the final state of the person in the database
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual({
- $browser: 'Chrome',
- $creator_event_uuid: events[0].uuid,
- utm_source: 'twitter',
- $geoip_country_code: 'US',
- })
- // last_seen_at should be set to hour-rounded timestamp
- expect(person!.last_seen_at).toBeDefined()
- expect(person!.last_seen_at!.minute).toBe(0)
- expect(person!.last_seen_at!.second).toBe(0)
+ // Verify the final state of the person in the database reflects the updates
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual({
+ $browser: 'Safari',
+ $creator_event_uuid: events[0].uuid,
+ $geoip_city_name: 'San Francisco',
})
- }
- )
+ })
+ }
+ )
- testWithTeamIngester(
- 'PERSON_PROPERTIES_UPDATE_ALL flag enables updates for normally filtered properties',
- { pluginServerConfig: { PERSON_PROPERTIES_UPDATE_ALL: true } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'allowed geoip properties ($geoip_country_name, $geoip_city_name) trigger person updates alongside blocked geoip properties',
+ {},
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // With PERSON_PROPERTIES_UPDATE_ALL=true, even normal pageview events should update
- // filtered properties like $browser, $geoip_*, etc.
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // Event 1: Normal pageview that creates the person with initial properties
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { $browser: 'Chrome', $geoip_city_name: 'New York' },
- })
- .withTimestamp(timestamp)
- .build(),
- // Event 2: Another normal pageview with updated filtered properties
- // With the flag enabled, these should trigger a person update
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // When $geoip_country_name or $geoip_city_name changes, all geoip properties in the batch
+ // should be updated, even the normally-blocked ones like $geoip_latitude
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // Event 1: Create person with initial geoip properties
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: {
+ $geoip_country_name: 'Canada',
+ $geoip_city_name: 'Toronto',
+ $geoip_latitude: 43.6532,
+ $geoip_longitude: -79.3832,
+ },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ // Event 2: Update geoip properties including allowed ones (country/city)
+ // Since $geoip_country_name changes, all geoip properties should be updated
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: {
+ $geoip_country_name: 'United States',
+ $geoip_city_name: 'San Francisco',
+ $geoip_latitude: 37.7749,
+ $geoip_longitude: -122.4194,
+ },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
-
- // Event 0 (first pageview): Should have initial properties
- expect(events[0].person_properties).toEqual({
- $browser: 'Chrome',
- $creator_event_uuid: events[0].uuid,
- $geoip_city_name: 'New York',
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
- // Event 1 (second pageview): Should have UPDATED properties
- // This is the key difference - without the flag, these would still show the old values
- expect(events[1].person_properties).toEqual({
- $browser: 'Safari',
- $creator_event_uuid: events[0].uuid,
- $geoip_city_name: 'San Francisco',
- })
+ // Event 0 (first pageview): Should have initial geoip properties
+ expect(events[0].person_properties).toEqual({
+ $creator_event_uuid: events[0].uuid,
+ $geoip_country_name: 'Canada',
+ $geoip_city_name: 'Toronto',
+ $geoip_latitude: 43.6532,
+ $geoip_longitude: -79.3832,
+ })
- // Verify the final state of the person in the database reflects the updates
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual({
- $browser: 'Safari',
- $creator_event_uuid: events[0].uuid,
- $geoip_city_name: 'San Francisco',
- })
+ // Event 1 (second pageview): Should have UPDATED geoip properties
+ // Because $geoip_country_name is an allowed property, all geoip properties get updated
+ expect(events[1].person_properties).toEqual({
+ $creator_event_uuid: events[0].uuid,
+ $geoip_country_name: 'United States',
+ $geoip_city_name: 'San Francisco',
+ $geoip_latitude: 37.7749,
+ $geoip_longitude: -122.4194,
})
- }
- )
- testWithTeamIngester(
- 'allowed geoip properties ($geoip_country_name, $geoip_city_name) trigger person updates alongside blocked geoip properties',
- {},
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ // Verify the final state of the person in the database reflects the updates
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual({
+ $creator_event_uuid: events[0].uuid,
+ $geoip_country_name: 'United States',
+ $geoip_city_name: 'San Francisco',
+ $geoip_latitude: 37.7749,
+ $geoip_longitude: -122.4194,
+ })
+ })
+ }
+ )
- // When $geoip_country_name or $geoip_city_name changes, all geoip properties in the batch
- // should be updated, even the normally-blocked ones like $geoip_latitude
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // Event 1: Create person with initial geoip properties
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: {
- $geoip_country_name: 'Canada',
- $geoip_city_name: 'Toronto',
- $geoip_latitude: 43.6532,
- $geoip_longitude: -79.3832,
- },
- })
- .withTimestamp(timestamp)
- .build(),
- // Event 2: Update geoip properties including allowed ones (country/city)
- // Since $geoip_country_name changes, all geoip properties should be updated
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: {
- $geoip_country_name: 'United States',
- $geoip_city_name: 'San Francisco',
- $geoip_latitude: 37.7749,
- $geoip_longitude: -122.4194,
- },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'can handle events with $process_person_profile=false',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: distinctId,
+ $set: { prop: 'value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('custom event')
+ .withProperties({
+ distinctId: distinctId,
+ $process_person_profile: false,
+ $group_0: 'group_key',
+ $set: {
+ c: 3,
+ },
+ $set_once: {
+ d: 4,
+ },
+ $unset: ['prop'],
+ })
+ .withOverrides({
+ $set: {
+ a: 1,
+ },
+ $set_once: {
+ b: 2,
+ },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('custom event')
+ .withProperties({})
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
-
- // Event 0 (first pageview): Should have initial geoip properties
- expect(events[0].person_properties).toEqual({
- $creator_event_uuid: events[0].uuid,
- $geoip_country_name: 'Canada',
- $geoip_city_name: 'Toronto',
- $geoip_latitude: 43.6532,
- $geoip_longitude: -79.3832,
- })
-
- // Event 1 (second pageview): Should have UPDATED geoip properties
- // Because $geoip_country_name is an allowed property, all geoip properties get updated
- expect(events[1].person_properties).toEqual({
- $creator_event_uuid: events[0].uuid,
- $geoip_country_name: 'United States',
- $geoip_city_name: 'San Francisco',
- $geoip_latitude: 37.7749,
- $geoip_longitude: -122.4194,
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[1].event).toEqual('custom event')
+ expect(events[1].person_properties).toEqual({})
+ expect(events[2].event).toEqual('custom event')
+ expect(events[2].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ })
+ }
+ )
- // Verify the final state of the person in the database reflects the updates
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual({
- $creator_event_uuid: events[0].uuid,
- $geoip_country_name: 'United States',
- $geoip_city_name: 'San Francisco',
- $geoip_latitude: 37.7749,
- $geoip_longitude: -122.4194,
- })
- })
- }
- )
+ testWithTeamIngester(
+ 'force_upgrade triggers when personless event sent after person creation',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- testWithTeamIngester(
- 'can handle events with $process_person_profile=false',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: distinctId,
- $set: { prop: 'value' },
- })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('custom event')
- .withProperties({
- distinctId: distinctId,
- $process_person_profile: false,
- $group_0: 'group_key',
- $set: {
- c: 3,
- },
- $set_once: {
- d: 4,
- },
- $unset: ['prop'],
- })
- .withOverrides({
- $set: {
- a: 1,
- },
- $set_once: {
- b: 2,
- },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('custom event')
- .withProperties({})
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: distinctId,
+ $set: { prop: 'value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('custom event')
+ .withProperties({
+ $process_person_profile: false,
+ })
+ .withTimestamp(timestamp + 120000) // 2 minutes later (beyond 1-minute grace period)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[1].event).toEqual('custom event')
- expect(events[1].person_properties).toEqual({})
- expect(events[2].event).toEqual('custom event')
- expect(events[2].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_mode).toEqual('full')
+ expect(events[1].event).toEqual('custom event')
+ expect(events[1].person_mode).toEqual('force_upgrade')
+ expect(events[1].person_properties).toEqual({})
+ })
+ }
+ )
- testWithTeamIngester(
- 'force_upgrade triggers when personless event sent after person creation',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'can handle multiple personless events for different users in same batch',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId1 = new UUIDT().toString()
+ const distinctId2 = new UUIDT().toString()
+ const distinctId3 = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: distinctId,
- $set: { prop: 'value' },
- })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('custom event')
- .withProperties({
- $process_person_profile: false,
- })
- .withTimestamp(timestamp + 120000) // 2 minutes later (beyond 1-minute grace period)
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId1)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId2)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId3)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_mode).toEqual('full')
- expect(events[1].event).toEqual('custom event')
- expect(events[1].person_mode).toEqual('force_upgrade')
- expect(events[1].person_properties).toEqual({})
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events.every((e) => e.event === 'pageview')).toBe(true)
+ expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)
+ expect(events.every((e) => Object.keys(e.person_properties).length === 0)).toBe(true)
+ })
+ }
+ )
- testWithTeamIngester(
- 'can handle multiple personless events for different users in same batch',
- {},
- async ({ ingester, team, token }) => {
- const distinctId1 = new UUIDT().toString()
- const distinctId2 = new UUIDT().toString()
- const distinctId3 = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId1)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId2)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId3)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
- )
-
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events.every((e) => e.event === 'pageview')).toBe(true)
- expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)
- expect(events.every((e) => Object.keys(e.person_properties).length === 0)).toBe(true)
- })
- }
- )
-
- testWithTeamIngester(
- 'can handle repeated personless events for same user in same batch',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'can handle repeated personless events for same user in same batch',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false, page: '/home' })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false, page: '/about' })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('pageview')
- .withProperties({ $process_person_profile: false, page: '/contact' })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false, page: '/home' })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false, page: '/about' })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('pageview')
+ .withProperties({ $process_person_profile: false, page: '/contact' })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)
- // All events should have the same deterministic person UUID
- const personIds = events.map((e) => e.person_id)
- expect(new Set(personIds).size).toBe(1)
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)
+ // All events should have the same deterministic person UUID
+ const personIds = events.map((e) => e.person_id)
+ expect(new Set(personIds).size).toBe(1)
+ })
+ }
+ )
- testWithTeamIngester(
- 'can $set and update person properties with top level $set',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: distinctId,
- })
- .withOverrides({
- $set: { prop: 'value' },
- })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'can $set and update person properties with top level $set',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: distinctId,
+ })
+ .withOverrides({
+ $set: { prop: 'value' },
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(1)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(1)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ })
+ }
+ )
- testWithTeamIngester(
- 'should guarantee that person properties are set in the order of the events',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'should guarantee that person properties are set in the order of the events',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- const events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({ $set: { prop: 'value' } })
- .withTimestamp(timestamp)
- .build(),
+ const events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({ $set: { prop: 'value' } })
+ .withTimestamp(timestamp)
+ .build(),
- new EventBuilder(team, distinctId)
- .withEvent('custom event')
- .withProperties({})
- .withTimestamp(timestamp + 1)
- .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('custom event')
+ .withProperties({})
+ .withTimestamp(timestamp + 1)
+ .build(),
- new EventBuilder(team, distinctId)
- .withEvent('custom event')
- .withProperties({
- $set: {
- prop: 'updated value',
- new_prop: 'new value',
- },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ]
+ new EventBuilder(team, distinctId)
+ .withEvent('custom event')
+ .withProperties({
+ $set: {
+ prop: 'updated value',
+ new_prop: 'new value',
+ },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ]
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[1].event).toEqual('custom event')
- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[2].event).toEqual('custom event')
- expect(events[2].person_properties).toEqual(
- expect.objectContaining({ prop: 'updated value', new_prop: 'new value' })
- )
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[1].event).toEqual('custom event')
+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[2].event).toEqual('custom event')
+ expect(events[2].person_properties).toEqual(
+ expect.objectContaining({ prop: 'updated value', new_prop: 'new value' })
+ )
+ })
+ }
+ )
- testWithTeamIngester(
- 'should be able to $set_once person properties but not update',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({ $set_once: { prop: 'value' } })
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({ $set_once: { prop: 'updated value' } })
- .build(),
- ]
+ testWithTeamIngester(
+ 'should be able to $set_once person properties but not update',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({ $set_once: { prop: 'value' } })
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({ $set_once: { prop: 'updated value' } })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[1].event).toEqual('$identify')
+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ })
+ }
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[1].event).toEqual('$identify')
- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- })
- }
- )
+ testWithTeamIngester(
+ 'should be able to $set_once person properties but not update, at the top level',
+ {},
+ async ({ ingester, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({})
+ .withOverrides({ $set_once: { prop: 'value' } })
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({})
+ .withOverrides({ $set_once: { prop: 'updated value' } })
+ .build(),
+ new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),
+ ]
- testWithTeamIngester(
- 'should be able to $set_once person properties but not update, at the top level',
- {},
- async ({ ingester, team, token }) => {
- const distinctId = new UUIDT().toString()
- const events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({})
- .withOverrides({ $set_once: { prop: 'value' } })
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({})
- .withOverrides({ $set_once: { prop: 'updated value' } })
- .build(),
- new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),
- ]
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(events[0].event).toEqual('$identify')
+ expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[1].event).toEqual('$identify')
+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events[2].event).toEqual('custom event')
+ expect(events[2].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'should identify previous events with $anon_distinct_id',
+ {},
+ async ({ ingester, team, token }) => {
+ const initialDistinctId = new UUIDT().toString()
+ const personIdentifier = '[email protected]'
+
+ const events = [
+ new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),
+ new EventBuilder(team, personIdentifier)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: personIdentifier,
+ $anon_distinct_id: initialDistinctId,
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(events[0].event).toEqual('$identify')
- expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[1].event).toEqual('$identify')
- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- expect(events[2].event).toEqual('custom event')
- expect(events[2].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
- })
- }
- )
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- testWithTeamIngester(
- 'should identify previous events with $anon_distinct_id',
- {},
- async ({ ingester, team, token }) => {
- const initialDistinctId = new UUIDT().toString()
- const personIdentifier = '[email protected]'
-
- const events = [
- new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),
- new EventBuilder(team, personIdentifier)
- .withEvent('$identify')
- .withProperties({
- distinct_id: personIdentifier,
- $anon_distinct_id: initialDistinctId,
- })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ expect(events[0].person_id).toEqual(events[1].person_id)
+ })
+ }
+ )
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ testWithTeamIngester(
+ 'should perserve all events if merge fails',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const illegalDistinctId = '0'
+ const distinctId = new UUIDT().toString()
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- expect(events[0].person_id).toEqual(events[1].person_id)
- })
- }
- )
+ const events = [
+ new EventBuilder(team, illegalDistinctId).withEvent('custom event').withProperties({}).build(),
+ new EventBuilder(team, distinctId).withEvent('custom event 2').withProperties({}).build(),
+ ]
- testWithTeamIngester(
- 'should perserve all events if merge fails',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const illegalDistinctId = '0'
- const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- const events = [
- new EventBuilder(team, illegalDistinctId).withEvent('custom event').withProperties({}).build(),
- new EventBuilder(team, distinctId).withEvent('custom event 2').withProperties({}).build(),
- ]
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForExpect(async () => {
+ const persons = await fetchPersons(team.id)
+ expect(persons.length).toEqual(2)
+ })
- await waitForKafkaMessages(kafkaProducer)
+ const mergeEvents = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$merge_dangerously')
+ .withProperties({
+ distinct_id: distinctId,
+ alias: illegalDistinctId,
+ $set: { prop: 'value' },
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const persons = await fetchPersons(team.id)
- expect(persons.length).toEqual(2)
- })
+ await ingester.handleKafkaBatch(createKafkaMessages(mergeEvents, token))
- const mergeEvents = [
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ // Assert that there are 2 different persons in person_id column
+ const personIds = new Set(events.map((event) => event.person_id))
+ expect(personIds.size).toEqual(2)
+ })
+ }
+ )
+
+ testWithTeamIngester('should preserve properties if merge fails', {}, async ({ ingester, team, token }) => {
+ const illegalDistinctId = '0'
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
new EventBuilder(team, distinctId)
.withEvent('$merge_dangerously')
.withProperties({
@@ -1126,3590 +1322,3527 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:
$set: { prop: 'value' },
})
.build(),
- ]
+ new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),
+ ],
+ token
+ )
+ )
- await ingester.handleKafkaBatch(createKafkaMessages(mergeEvents, token))
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ })
+ })
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- // Assert that there are 2 different persons in person_id column
- const personIds = new Set(events.map((event) => event.person_id))
- expect(personIds.size).toEqual(2)
- })
- }
- )
+ testWithTeamIngester(
+ 'should merge all events into same person id',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const initialDistinctId = 'id1'
+ const secondDistinctId = 'id2'
+ const personIdentifier = 'person_id'
+
+ const event1 = new EventBuilder(team, initialDistinctId)
+ .withEvent('custom event')
+ .withProperties({})
+ .build()
+ const event2 = new EventBuilder(team, secondDistinctId)
+ .withEvent('custom event 2')
+ .withProperties({})
+ .build()
+
+ await ingester.handleKafkaBatch(createKafkaMessages([event1, event2], token))
+
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const persons = await fetchPersons(team.id)
+ expect(persons).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ properties: expect.objectContaining({
+ $creator_event_uuid: event1.uuid,
+ }),
+ }),
+ expect.objectContaining({
+ properties: expect.objectContaining({
+ $creator_event_uuid: event2.uuid,
+ }),
+ }),
+ ])
+ )
+ })
- testWithTeamIngester('should preserve properties if merge fails', {}, async ({ ingester, team, token }) => {
- const illegalDistinctId = '0'
- const distinctId = new UUIDT().toString()
await ingester.handleKafkaBatch(
createKafkaMessages(
[
- new EventBuilder(team, distinctId)
- .withEvent('$merge_dangerously')
+ new EventBuilder(team, personIdentifier)
+ .withEvent('$identify')
.withProperties({
- distinct_id: distinctId,
- alias: illegalDistinctId,
- $set: { prop: 'value' },
+ distinct_id: personIdentifier,
+ $anon_distinct_id: initialDistinctId,
+ })
+ .build(),
+ new EventBuilder(team, personIdentifier)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: personIdentifier,
+ $anon_distinct_id: secondDistinctId,
})
.build(),
- new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),
],
token
)
)
+ await waitForKafkaMessages(kafkaProducer)
+
await waitForExpect(async () => {
const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))
+ expect(events.length).toEqual(4)
+ // assert all events have the same person_id
+ const personIds = new Set(events.map((event) => event.person_id))
+ expect(personIds.size).toEqual(1)
})
- })
-
- testWithTeamIngester(
- 'should merge all events into same person id',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const initialDistinctId = 'id1'
- const secondDistinctId = 'id2'
- const personIdentifier = 'person_id'
+ }
+ )
- const event1 = new EventBuilder(team, initialDistinctId)
- .withEvent('custom event')
- .withProperties({})
- .build()
- const event2 = new EventBuilder(team, secondDistinctId)
- .withEvent('custom event 2')
- .withProperties({})
- .build()
+ testWithTeamIngester(
+ 'should resolve to same person id chained merges',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const initialDistinctId = 'initialId'
+ const secondDistinctId = 'secondId'
+ const thirdDistinctId = 'thirdId'
- await ingester.handleKafkaBatch(createKafkaMessages([event1, event2], token))
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),
+ new EventBuilder(team, secondDistinctId).withEvent('custom event 2').withProperties({}).build(),
+ new EventBuilder(team, thirdDistinctId).withEvent('custom event 3').withProperties({}).build(),
+ ],
+ token
+ )
+ )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPersons(team.id)
- expect(persons).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- properties: expect.objectContaining({
- $creator_event_uuid: event1.uuid,
- }),
- }),
- expect.objectContaining({
- properties: expect.objectContaining({
- $creator_event_uuid: event2.uuid,
- }),
- }),
- ])
- )
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(3)
+ expect(new Set(events.map((event) => event.person_id)).size).toEqual(3)
+ })
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, personIdentifier)
- .withEvent('$identify')
- .withProperties({
- distinct_id: personIdentifier,
- $anon_distinct_id: initialDistinctId,
- })
- .build(),
- new EventBuilder(team, personIdentifier)
- .withEvent('$identify')
- .withProperties({
- distinct_id: personIdentifier,
- $anon_distinct_id: secondDistinctId,
- })
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: initialDistinctId,
+ $anon_distinct_id: secondDistinctId,
+ })
+ .build(),
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: initialDistinctId,
+ $anon_distinct_id: thirdDistinctId,
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(4)
- // assert all events have the same person_id
- const personIds = new Set(events.map((event) => event.person_id))
- expect(personIds.size).toEqual(1)
- })
- }
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(5)
+ expect(new Set(events.map((event) => event.person_id)).size).toEqual(1)
+ })
+ }
+ )
- testWithTeamIngester(
- 'should resolve to same person id chained merges',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const initialDistinctId = 'initialId'
- const secondDistinctId = 'secondId'
- const thirdDistinctId = 'thirdId'
+ testWithTeamIngester(
+ 'should resolve to same person id even with complex chained merges',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const initialDistinctId = new UUIDT().toString()
+ const secondDistinctId = new UUIDT().toString()
+ const thirdDistinctId = new UUIDT().toString()
+ const forthDistinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, initialDistinctId)
- .withEvent('custom event')
- .withProperties({})
- .build(),
- new EventBuilder(team, secondDistinctId)
- .withEvent('custom event 2')
- .withProperties({})
- .build(),
- new EventBuilder(team, thirdDistinctId)
- .withEvent('custom event 3')
- .withProperties({})
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),
+ new EventBuilder(team, secondDistinctId).withEvent('custom event 2').withProperties({}).build(),
+ new EventBuilder(team, thirdDistinctId).withEvent('custom event 3').withProperties({}).build(),
+ new EventBuilder(team, forthDistinctId).withEvent('custom event 4').withProperties({}).build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(3)
- expect(new Set(events.map((event) => event.person_id)).size).toEqual(3)
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPersons(team.id)
+ expect(persons.length).toBe(4)
+ })
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: initialDistinctId,
- $anon_distinct_id: secondDistinctId,
- })
- .build(),
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: initialDistinctId,
- $anon_distinct_id: thirdDistinctId,
- })
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: initialDistinctId,
+ $anon_distinct_id: secondDistinctId,
+ })
+ .build(),
+ new EventBuilder(team, thirdDistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ distinct_id: thirdDistinctId,
+ $anon_distinct_id: forthDistinctId,
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(5)
- expect(new Set(events.map((event) => event.person_id)).size).toEqual(1)
- })
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(6)
+ })
+
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, secondDistinctId)
+ .withEvent('$merge_dangerously')
+ .withProperties({
+ distinct_id: secondDistinctId,
+ alias: thirdDistinctId,
+ })
+ .build(),
+ ],
+ token
+ )
+ )
+
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(7)
+ expect(new Set(events.map((event) => event.person_id)).size).toBe(1)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'should produce ingestion warnings for messages over 1MB',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ // For this we basically want the processor to try and produce a new
+ // message larger than 1MB. We do this by creating a person with a lot of
+ // properties. We will end up denormalizing the person properties onto the
+ // event, which already has the properties as $set therefore resulting in a
+ // message that's larger than 1MB. There may also be other attributes that
+ // are added to the event which pushes it over the limit.
+ //
+ // We verify that this is handled by checking that there is a message in the
+ // appropriate topic.
+ const distinctId = new UUIDT().toString()
+
+ const personProperties = {
+ distinct_id: distinctId,
+ $set: {} as Record<string, string>,
}
- )
- testWithTeamIngester(
- 'should resolve to same person id even with complex chained merges',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const initialDistinctId = new UUIDT().toString()
- const secondDistinctId = new UUIDT().toString()
- const thirdDistinctId = new UUIDT().toString()
- const forthDistinctId = new UUIDT().toString()
+ for (let i = 0; i < 10000; i++) {
+ personProperties.$set[new UUIDT().toString()] = new UUIDT().toString()
+ }
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, initialDistinctId)
- .withEvent('custom event')
- .withProperties({})
- .build(),
- new EventBuilder(team, secondDistinctId)
- .withEvent('custom event 2')
- .withProperties({})
- .build(),
- new EventBuilder(team, thirdDistinctId)
- .withEvent('custom event 3')
- .withProperties({})
- .build(),
- new EventBuilder(team, forthDistinctId)
- .withEvent('custom event 4')
- .withProperties({})
- .build(),
- ],
- token
- )
- )
+ const events = [
+ new EventBuilder(team, distinctId).withEvent('$identify').withProperties(personProperties).build(),
+ ]
- await waitForKafkaMessages(kafkaProducer)
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForExpect(async () => {
- const persons = await fetchPersons(team.id)
- expect(persons.length).toBe(4)
- })
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: initialDistinctId,
- $anon_distinct_id: secondDistinctId,
- })
- .build(),
- new EventBuilder(team, thirdDistinctId)
- .withEvent('$identify')
- .withProperties({
- distinct_id: thirdDistinctId,
- $anon_distinct_id: forthDistinctId,
- })
- .build(),
- ],
- token
- )
- )
+ await waitForExpect(async () => {
+ const ingestionWarnings = await fetchIngestionWarnings(clickhouse, team.id)
+ expect(ingestionWarnings.length).toBe(1)
+ expect(ingestionWarnings[0].details.eventUuid).toBe(events[0].uuid)
+ })
+ }
+ )
+
+ const fetchPersons = async (teamId: number) => {
+ const persons = await clickhouse.fetchPersons(teamId)
+ return persons.map((person) => ({
+ ...person,
+ properties: parseJSON(person.properties),
+ }))
+ }
- await waitForKafkaMessages(kafkaProducer)
+ // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
+ // testWithTeamIngester('alias events ordering scenario 1: original order', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
+ // const user1DistinctId = 'user1-distinct-id'
+ // const user2DistinctId = 'user2-distinct-id'
+ // const user3DistinctId = 'user3-distinct-id'
+
+ // const events = [
+ // // User 1 creation
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // name: 'User 1',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 1 - Updated',
+ // },
+ // })
+ // .build(),
+ // // User 2 creation
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // name: 'User 2',
+ // email: `user2-${user2DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 2 - Updated',
+ // },
+ // })
+ // .build(),
+ // // Merge users: alias user1 -> user2
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user1DistinctId,
+ // alias: user2DistinctId,
+ // })
+ // .build(),
+
+ // // Create alias for user2 -> user3
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user2DistinctId,
+ // alias: user3DistinctId,
+ // })
+ // .build(),
+ // ]
+
+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ // await waitForKafkaMessages(kafkaProducer)
+
+ // await waitForExpect(async () => {
+ // const events = await fetchEvents(clickhouse, team.id)
+ // expect(events.length).toBe(6)
+
+ // // TODO: Add specific assertions based on expected behavior
+ // // All events should be processed without errors
+ // expect(events).toBeDefined()
+ // })
+
+ // // fetch the person properties
+ // await waitForExpect(async () => {
+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // expect(persons.length).toBe(1)
+ // const personsClickhouse = await fetchPersons(team.id)
+ // expect(personsClickhouse.length).toBe(1)
+ // expect(persons[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // expect(personsClickhouse[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
+ // id: persons[0].id,
+ // team_id: team.id,
+ // } as InternalPerson)
+ // expect(distinctIdsPersons.length).toBe(3)
+ // // Except distinctids to match the ids, in any order
+ // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
+ // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
+ // )
+ // })
+ // })
+
+ // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
+ // testWithTeamIngester('alias events ordering scenario 2: alias first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
+ // const user1DistinctId = 'user1-distinct-id'
+ // const user2DistinctId = 'user2-distinct-id'
+ // const user3DistinctId = 'user3-distinct-id'
+
+ // const events = [
+ // // User 1 creation
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // name: 'User 1',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 1 - Updated',
+ // },
+ // })
+ // .build(),
+ // // User 2 creation
+ // new EventBuilder(team, user2DistinctId)
+ // .withProperties({
+ // anon_distinct_id: user2DistinctId,
+ // $set: {
+ // name: 'User 2',
+ // email: `user2-${user2DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 2 - Updated',
+ // },
+ // })
+ // .build(),
+
+ // // Create alias for user2 -> user3
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user2DistinctId,
+ // alias: user3DistinctId,
+ // })
+ // .build(),
+
+ // // Merge users: alias user1 -> user2
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user1DistinctId,
+ // alias: user2DistinctId,
+ // })
+ // .build(),
+ // ]
+
+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ // await waitForKafkaMessages(kafkaProducer)
+
+ // await waitForExpect(async () => {
+ // const events = await fetchEvents(clickhouse, team.id)
+ // expect(events.length).toBe(6)
+
+ // // TODO: Add specific assertions based on expected behavior
+ // // All events should be processed without errors
+ // expect(events).toBeDefined()
+ // })
+
+ // // fetch the person properties
+ // await waitForExpect(async () => {
+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // expect(persons.length).toBe(1)
+ // const personsClickhouse = await fetchPersons(team.id)
+ // expect(personsClickhouse.length).toBe(1)
+ // expect(persons[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // expect(personsClickhouse[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
+ // id: persons[0].id,
+ // team_id: team.id,
+ // } as InternalPerson)
+ // expect(distinctIdsPersons.length).toBe(3)
+ // // Except distinctids to match the ids, in any order
+ // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
+ // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
+ // )
+ // })
+ // })
+
+ // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
+ // testWithTeamIngester('alias events ordering scenario 2: user 2 first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
+ // const user1DistinctId = 'user1-distinct-id'
+ // const user2DistinctId = 'user2-distinct-id'
+ // const user3DistinctId = 'user3-distinct-id'
+
+ // const events = [
+ // // User 2 creation
+ // new EventBuilder(team, user2DistinctId)
+ // .withProperties({
+ // anon_distinct_id: user2DistinctId,
+ // $set: {
+ // name: 'User 2',
+ // email: `user2-${user2DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 2 - Updated',
+ // },
+ // })
+ // .build(),
+
+ // // Create alias for user2 -> user3
+ // new EventBuilder(team, user2DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user2DistinctId,
+ // alias: user3DistinctId,
+ // })
+ // .build(),
+
+ // // User 1 creation
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // name: 'User 1',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // },
+ // })
+ // .build(),
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$identify')
+ // .withProperties({
+ // $set: {
+ // new_name: 'User 1 - Updated',
+ // },
+ // })
+ // .build(),
+
+ // // Merge users: alias user1 -> user2
+ // new EventBuilder(team, user1DistinctId)
+ // .withEvent('$create_alias')
+ // .withProperties({
+ // distinct_id: user1DistinctId,
+ // alias: user2DistinctId,
+ // })
+ // .build(),
+ // ]
+
+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ // await waitForKafkaMessages(kafkaProducer)
+
+ // await waitForExpect(async () => {
+ // const events = await fetchEvents(clickhouse, team.id)
+ // expect(events.length).toBe(6)
+
+ // // TODO: Add specific assertions based on expected behavior
+ // // All events should be processed without errors
+ // expect(events).toBeDefined()
+ // })
+
+ // // fetch the person properties
+ // await waitForExpect(async () => {
+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // expect(persons.length).toBe(1)
+ // const personsClickhouse = await fetchPersons(team.id)
+ // expect(personsClickhouse.length).toBe(1)
+ // expect(persons[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // expect(personsClickhouse[0].properties).toMatchObject(
+ // expect.objectContaining({
+ // name: 'User 1',
+ // new_name: 'User 1 - Updated',
+ // email: `user1-${user1DistinctId}@example.com`,
+ // age: 30,
+ // test_name: testName,
+ // })
+ // )
+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
+ // id: persons[0].id,
+ // team_id: team.id,
+ // } as InternalPerson)
+ // expect(distinctIdsPersons.length).toBe(3)
+ // // Except distinctids to match the ids, in any order
+ // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
+ // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
+ // )
+ // })
+ // })
+
+ testWithTeamIngester(
+ 'alias events ordering scenario 2: user 2 first, separate batch',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
+ const user1DistinctId = 'user1-distinct-id'
+ const user2DistinctId = 'user2-distinct-id'
+ const user3DistinctId = 'user3-distinct-id'
+
+ const events = [
+ // User 2 creation
+ new EventBuilder(team, user2DistinctId)
+ .withProperties({
+ anon_distinct_id: user2DistinctId,
+ $set: {
+ name: 'User 2',
+ email: `user2-${user2DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ },
+ })
+ .build(),
+ new EventBuilder(team, user2DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ new_name: 'User 2 - Updated',
+ },
+ })
+ .build(),
+
+ // Create alias for user2 -> user3
+ new EventBuilder(team, user2DistinctId)
+ .withEvent('$create_alias')
+ .withProperties({
+ distinct_id: user2DistinctId,
+ alias: user3DistinctId,
+ })
+ .build(),
+ ]
+
+ const events2 = [
+ // User 1 creation
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ name: 'User 1',
+ email: `user1-${user1DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ },
+ })
+ .build(),
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ new_name: 'User 1 - Updated',
+ },
+ })
+ .build(),
+
+ // Merge users: alias user1 -> user2
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$create_alias')
+ .withProperties({
+ distinct_id: user1DistinctId,
+ alias: user2DistinctId,
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(6)
- })
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, secondDistinctId)
- .withEvent('$merge_dangerously')
- .withProperties({
- distinct_id: secondDistinctId,
- alias: thirdDistinctId,
- })
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(createKafkaMessages(events2, token))
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(6)
+
+ // TODO: Add specific assertions based on expected behavior
+ // All events should be processed without errors
+ expect(events).toBeDefined()
+ })
+
+ // fetch the person properties
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ const personsClickhouse = await fetchPersons(team.id)
+ expect(personsClickhouse.length).toBe(2)
+ expect(persons.map((person) => person.properties)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'User 1',
+ new_name: 'User 1 - Updated',
+ email: `user1-${user1DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ }),
+ expect.objectContaining({
+ name: 'User 2',
+ new_name: 'User 2 - Updated',
+ email: `user2-${user2DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ }),
+ ])
+ )
+ expect(personsClickhouse.map((person) => person.properties)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'User 1',
+ new_name: 'User 1 - Updated',
+ email: `user1-${user1DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ }),
+ expect.objectContaining({
+ name: 'User 2',
+ new_name: 'User 2 - Updated',
+ email: `user2-${user2DistinctId}@example.com`,
+ age: 30,
+ test_name: testName,
+ }),
+ ])
+ )
+ const person1 = persons.find((person) => person.properties.name === 'User 1')!
+ const person2 = persons.find((person) => person.properties.name === 'User 2')!
+ const distinctIdsPersons1 = await fetchDistinctIds(infra.postgres, {
+ id: person1.id,
+ team_id: team.id,
+ } as InternalPerson)
+ expect(distinctIdsPersons1.length).toBe(1)
+ // Except distinctids to match the ids, in any order
+ expect(distinctIdsPersons1.map((distinctId) => distinctId.distinct_id)).toEqual(
+ expect.arrayContaining([user1DistinctId])
+ )
+ const distinctIdsPersons2 = await fetchDistinctIds(infra.postgres, {
+ id: person2.id,
+ team_id: team.id,
+ } as InternalPerson)
+ expect(distinctIdsPersons2.length).toBe(2)
+ // Except distinctids to match the ids, in any order
+ expect(distinctIdsPersons2.map((distinctId) => distinctId.distinct_id)).toEqual(
+ expect.arrayContaining([user2DistinctId, user3DistinctId])
+ )
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'Should set and $unset person properties, different batches',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const user1DistinctId = 'user1-distinct-id'
+
+ const events = [
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ name: 'User 1',
+ property_to_unset: 'value',
+ },
+ })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ const personsClickhouse = await fetchPersons(team.id)
+ expect(personsClickhouse.length).toBe(1)
+ expect(persons[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ property_to_unset: 'value',
+ })
+ )
+ expect(personsClickhouse[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ property_to_unset: 'value',
+ })
)
+ })
- await waitForKafkaMessages(kafkaProducer)
+ const events2 = [
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $unset: ['property_to_unset'],
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(7)
- expect(new Set(events.map((event) => event.person_id)).size).toBe(1)
- })
- }
- )
+ await ingester.handleKafkaBatch(createKafkaMessages(events2, token))
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'should produce ingestion warnings for messages over 1MB',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- // For this we basically want the processor to try and produce a new
- // message larger than 1MB. We do this by creating a person with a lot of
- // properties. We will end up denormalizing the person properties onto the
- // event, which already has the properties as $set therefore resulting in a
- // message that's larger than 1MB. There may also be other attributes that
- // are added to the event which pushes it over the limit.
- //
- // We verify that this is handled by checking that there is a message in the
- // appropriate topic.
- const distinctId = new UUIDT().toString()
-
- const personProperties = {
- distinct_id: distinctId,
- $set: {} as Record<string, string>,
- }
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ const personsClickhouse = await fetchPersons(team.id)
+ expect(personsClickhouse.length).toBe(1)
+ expect(persons[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ })
+ )
+ expect(persons[0].properties).not.toHaveProperty('property_to_unset')
+ expect(personsClickhouse[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ })
+ )
+ expect(personsClickhouse[0].properties).not.toHaveProperty('property_to_unset')
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'Should set and $unset person properties, same batch',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const user1DistinctId = 'user1-distinct-id'
+
+ const events = [
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ name: 'User 1',
+ property_to_unset: 'value',
+ },
+ })
+ .build(),
+ new EventBuilder(team, user1DistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $unset: ['property_to_unset'],
+ })
+ .build(),
+ ]
- for (let i = 0; i < 10000; i++) {
- personProperties.$set[new UUIDT().toString()] = new UUIDT().toString()
- }
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- const events = [
- new EventBuilder(team, distinctId).withEvent('$identify').withProperties(personProperties).build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ const personsClickhouse = await fetchPersons(team.id)
+ expect(personsClickhouse.length).toBe(1)
+ expect(persons[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ })
+ )
+ expect(persons[0].properties).not.toHaveProperty('property_to_unset')
+ expect(personsClickhouse[0].properties).toMatchObject(
+ expect.objectContaining({
+ name: 'User 1',
+ })
+ )
+ expect(personsClickhouse[0].properties).not.toHaveProperty('property_to_unset')
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'should process events with various timestamps when dropping is disabled',
+ { teamOverrides: { drop_events_older_than_seconds: null } },
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const currentTime = DateTime.now().toMillis()
+ const events = [
+ // Current time event
+ new EventBuilder(team)
+ .withEvent('current_time_event')
+ .withTimestamp(currentTime)
+ .withNow(currentTime)
+ .build(),
+ // Recent event (30 minutes ago)
+ new EventBuilder(team)
+ .withEvent('recent_event')
+ .withTimestamp(currentTime - 30 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Old event (2 hours ago)
+ new EventBuilder(team)
+ .withEvent('old_event')
+ .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Very old event (1 day ago)
+ new EventBuilder(team)
+ .withEvent('very_old_event')
+ .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Extremely old event (1 month ago)
+ new EventBuilder(team)
+ .withEvent('extremely_old_event')
+ .withTimestamp(currentTime - 30 * 24 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Future event (1 hour from now)
+ new EventBuilder(team)
+ .withEvent('future_event')
+ .withTimestamp(currentTime + 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ // All events should be processed when dropping is disabled
+ expect(events.length).toBe(6)
+
+ // Verify all events are present
+ const eventTypes = events.map((e) => e.event)
+ expect(eventTypes).toContain('current_time_event')
+ expect(eventTypes).toContain('recent_event')
+ expect(eventTypes).toContain('old_event')
+ expect(eventTypes).toContain('very_old_event')
+ expect(eventTypes).toContain('extremely_old_event')
+ expect(eventTypes).toContain('future_event')
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'should drop old events when dropping is enabled',
+ { teamOverrides: { drop_events_older_than_seconds: 3600 } },
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const currentTime = DateTime.now().toMillis()
+ const events = [
+ // Current time event - should pass
+ new EventBuilder(team)
+ .withEvent('current_time_event')
+ .withTimestamp(currentTime)
+ .withNow(currentTime)
+ .build(),
+ // Recent event (30 minutes ago) - should pass
+ new EventBuilder(team)
+ .withEvent('recent_event')
+ .withTimestamp(currentTime - 30 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Just under threshold (59 minutes ago) - should pass
+ new EventBuilder(team)
+ .withEvent('just_under_threshold')
+ .withTimestamp(currentTime - 59 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Just over threshold (61 minutes ago) - should be dropped
+ new EventBuilder(team)
+ .withEvent('just_over_threshold')
+ .withTimestamp(currentTime - 61 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Old event (2 hours ago) - should be dropped
+ new EventBuilder(team)
+ .withEvent('old_event')
+ .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Very old event (1 day ago) - should be dropped
+ new EventBuilder(team)
+ .withEvent('very_old_event')
+ .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Future event (1 hour from now) - should pass
+ new EventBuilder(team)
+ .withEvent('future_event')
+ .withTimestamp(currentTime + 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ // Only events under 1 hour old should be processed
+ expect(events.length).toBe(4)
+
+ // Verify only expected events are present
+ const eventTypes = events.map((e) => e.event)
+ expect(eventTypes).toContain('current_time_event')
+ expect(eventTypes).toContain('recent_event')
+ expect(eventTypes).toContain('just_under_threshold')
+ expect(eventTypes).toContain('future_event')
+
+ // Verify dropped events are not present
+ expect(eventTypes).not.toContain('just_over_threshold')
+ expect(eventTypes).not.toContain('old_event')
+ expect(eventTypes).not.toContain('very_old_event')
+ })
- await waitForExpect(async () => {
- const ingestionWarnings = await fetchIngestionWarnings(clickhouse, team.id)
- expect(ingestionWarnings.length).toBe(1)
- expect(ingestionWarnings[0].details.eventUuid).toBe(events[0].uuid)
- })
- }
- )
+ // Check that ingestion warnings were created for dropped events
+ await waitForExpect(async () => {
+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)
+ expect(warnings.length).toBe(3)
- const fetchPersons = async (teamId: number) => {
- const persons = await clickhouse.fetchPersons(teamId)
- return persons.map((person) => ({
- ...person,
- properties: parseJSON(person.properties),
- }))
+ const warningTypes = warnings.map((w) => w.type)
+ expect(warningTypes).toEqual(
+ expect.arrayContaining(['event_dropped_too_old', 'event_dropped_too_old', 'event_dropped_too_old'])
+ )
+ })
}
+ )
+
+ testWithTeamIngester(
+ 'should process all events when drop threshold is set to 0',
+ { teamOverrides: { drop_events_older_than_seconds: 0 } },
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const currentTime = DateTime.now().toMillis()
+ const events = [
+ // Current time event - should pass
+ new EventBuilder(team)
+ .withEvent('current_time_event')
+ .withTimestamp(currentTime)
+ .withNow(currentTime)
+ .build(),
+ // Recent event (30 minutes ago) - should pass
+ new EventBuilder(team)
+ .withEvent('recent_event')
+ .withTimestamp(currentTime - 30 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Old event (2 hours ago) - should pass (0 threshold means no dropping)
+ new EventBuilder(team)
+ .withEvent('old_event')
+ .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Very old event (1 day ago) - should pass (0 threshold means no dropping)
+ new EventBuilder(team)
+ .withEvent('very_old_event')
+ .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Extremely old event (1 month ago) - should pass (0 threshold means no dropping)
+ new EventBuilder(team)
+ .withEvent('extremely_old_event')
+ .withTimestamp(currentTime - 30 * 24 * 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ // Future event (1 hour from now) - should pass
+ new EventBuilder(team)
+ .withEvent('future_event')
+ .withTimestamp(currentTime + 60 * 60 * 1000)
+ .withNow(currentTime)
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
- // testWithTeamIngester('alias events ordering scenario 1: original order', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
- // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
- // const user1DistinctId = 'user1-distinct-id'
- // const user2DistinctId = 'user2-distinct-id'
- // const user3DistinctId = 'user3-distinct-id'
-
- // const events = [
- // // User 1 creation
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // name: 'User 1',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 1 - Updated',
- // },
- // })
- // .build(),
- // // User 2 creation
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // name: 'User 2',
- // email: `user2-${user2DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 2 - Updated',
- // },
- // })
- // .build(),
- // // Merge users: alias user1 -> user2
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user1DistinctId,
- // alias: user2DistinctId,
- // })
- // .build(),
-
- // // Create alias for user2 -> user3
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user2DistinctId,
- // alias: user3DistinctId,
- // })
- // .build(),
- // ]
-
- // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- // await waitForKafkaMessages(kafkaProducer)
-
- // await waitForExpect(async () => {
- // const events = await fetchEvents(clickhouse, team.id)
- // expect(events.length).toBe(6)
-
- // // TODO: Add specific assertions based on expected behavior
- // // All events should be processed without errors
- // expect(events).toBeDefined()
- // })
-
- // // fetch the person properties
- // await waitForExpect(async () => {
- // const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // expect(persons.length).toBe(1)
- // const personsClickhouse = await fetchPersons(team.id)
- // expect(personsClickhouse.length).toBe(1)
- // expect(persons[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // expect(personsClickhouse[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
- // id: persons[0].id,
- // team_id: team.id,
- // } as InternalPerson)
- // expect(distinctIdsPersons.length).toBe(3)
- // // Except distinctids to match the ids, in any order
- // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
- // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
- // )
- // })
- // })
-
- // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
- // testWithTeamIngester('alias events ordering scenario 2: alias first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
- // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
- // const user1DistinctId = 'user1-distinct-id'
- // const user2DistinctId = 'user2-distinct-id'
- // const user3DistinctId = 'user3-distinct-id'
-
- // const events = [
- // // User 1 creation
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // name: 'User 1',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 1 - Updated',
- // },
- // })
- // .build(),
- // // User 2 creation
- // new EventBuilder(team, user2DistinctId)
- // .withProperties({
- // anon_distinct_id: user2DistinctId,
- // $set: {
- // name: 'User 2',
- // email: `user2-${user2DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 2 - Updated',
- // },
- // })
- // .build(),
-
- // // Create alias for user2 -> user3
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user2DistinctId,
- // alias: user3DistinctId,
- // })
- // .build(),
-
- // // Merge users: alias user1 -> user2
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user1DistinctId,
- // alias: user2DistinctId,
- // })
- // .build(),
- // ]
-
- // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- // await waitForKafkaMessages(kafkaProducer)
-
- // await waitForExpect(async () => {
- // const events = await fetchEvents(clickhouse, team.id)
- // expect(events.length).toBe(6)
-
- // // TODO: Add specific assertions based on expected behavior
- // // All events should be processed without errors
- // expect(events).toBeDefined()
- // })
-
- // // fetch the person properties
- // await waitForExpect(async () => {
- // const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // expect(persons.length).toBe(1)
- // const personsClickhouse = await fetchPersons(team.id)
- // expect(personsClickhouse.length).toBe(1)
- // expect(persons[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // expect(personsClickhouse[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
- // id: persons[0].id,
- // team_id: team.id,
- // } as InternalPerson)
- // expect(distinctIdsPersons.length).toBe(3)
- // // Except distinctids to match the ids, in any order
- // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
- // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
- // )
- // })
- // })
-
- // TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid
- // testWithTeamIngester('alias events ordering scenario 2: user 2 first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {
- // const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
- // const user1DistinctId = 'user1-distinct-id'
- // const user2DistinctId = 'user2-distinct-id'
- // const user3DistinctId = 'user3-distinct-id'
-
- // const events = [
- // // User 2 creation
- // new EventBuilder(team, user2DistinctId)
- // .withProperties({
- // anon_distinct_id: user2DistinctId,
- // $set: {
- // name: 'User 2',
- // email: `user2-${user2DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 2 - Updated',
- // },
- // })
- // .build(),
-
- // // Create alias for user2 -> user3
- // new EventBuilder(team, user2DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user2DistinctId,
- // alias: user3DistinctId,
- // })
- // .build(),
-
- // // User 1 creation
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // name: 'User 1',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // },
- // })
- // .build(),
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$identify')
- // .withProperties({
- // $set: {
- // new_name: 'User 1 - Updated',
- // },
- // })
- // .build(),
-
- // // Merge users: alias user1 -> user2
- // new EventBuilder(team, user1DistinctId)
- // .withEvent('$create_alias')
- // .withProperties({
- // distinct_id: user1DistinctId,
- // alias: user2DistinctId,
- // })
- // .build(),
- // ]
-
- // await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- // await waitForKafkaMessages(kafkaProducer)
-
- // await waitForExpect(async () => {
- // const events = await fetchEvents(clickhouse, team.id)
- // expect(events.length).toBe(6)
-
- // // TODO: Add specific assertions based on expected behavior
- // // All events should be processed without errors
- // expect(events).toBeDefined()
- // })
-
- // // fetch the person properties
- // await waitForExpect(async () => {
- // const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // expect(persons.length).toBe(1)
- // const personsClickhouse = await fetchPersons(team.id)
- // expect(personsClickhouse.length).toBe(1)
- // expect(persons[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // expect(personsClickhouse[0].properties).toMatchObject(
- // expect.objectContaining({
- // name: 'User 1',
- // new_name: 'User 1 - Updated',
- // email: `user1-${user1DistinctId}@example.com`,
- // age: 30,
- // test_name: testName,
- // })
- // )
- // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {
- // id: persons[0].id,
- // team_id: team.id,
- // } as InternalPerson)
- // expect(distinctIdsPersons.length).toBe(3)
- // // Except distinctids to match the ids, in any order
- // expect(distinctIdsPersons.map((distinctId) => distinctId.distinct_id)).toEqual(
- // expect.arrayContaining([user1DistinctId, user2DistinctId, user3DistinctId])
- // )
- // })
- // })
-
- testWithTeamIngester(
- 'alias events ordering scenario 2: user 2 first, separate batch',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')
- const user1DistinctId = 'user1-distinct-id'
- const user2DistinctId = 'user2-distinct-id'
- const user3DistinctId = 'user3-distinct-id'
-
- const events = [
- // User 2 creation
- new EventBuilder(team, user2DistinctId)
- .withProperties({
- anon_distinct_id: user2DistinctId,
- $set: {
- name: 'User 2',
- email: `user2-${user2DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- },
- })
- .build(),
- new EventBuilder(team, user2DistinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- new_name: 'User 2 - Updated',
- },
- })
- .build(),
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ // All events should be processed when threshold is 0 (no dropping)
+ expect(events.length).toBe(6)
+
+ // Verify all events are present
+ const eventTypes = events.map((e) => e.event)
+ expect(eventTypes).toContain('current_time_event')
+ expect(eventTypes).toContain('recent_event')
+ expect(eventTypes).toContain('old_event')
+ expect(eventTypes).toContain('very_old_event')
+ expect(eventTypes).toContain('extremely_old_event')
+ expect(eventTypes).toContain('future_event')
+ })
- // Create alias for user2 -> user3
- new EventBuilder(team, user2DistinctId)
- .withEvent('$create_alias')
- .withProperties({
- distinct_id: user2DistinctId,
- alias: user3DistinctId,
- })
- .build(),
- ]
+ // Check that no ingestion warnings were created (no events should be dropped)
+ await waitForExpect(async () => {
+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)
+ expect(warnings.length).toBe(0)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'we do not alias users if distinct id changes but we are already identified, with no anonymous event',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // This test is similar to the previous one, except it does not include an initial anonymous event.
+
+ const anonymousId = 'anonymous_id'
+ const initialDistinctId = 'initial_distinct_id'
+ const p2DistinctId = 'p2_distinct_id'
+ const p2NewDistinctId = 'new_distinct_id'
+
+ // Play out a sequence of events that should result in two users being
+ // identified, with the first to events associated with one user, and
+ // the third with another.
+ const events = [
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
+ new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
+ new EventBuilder(team, p2NewDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2DistinctId })
+ .build(),
+ new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
+ // Let's also make sure that we do not alias when switching back to initialDistictId
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2NewDistinctId })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- const events2 = [
- // User 1 creation
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- name: 'User 1',
- email: `user1-${user1DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- },
- })
- .build(),
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- new_name: 'User 1 - Updated',
- },
- })
- .build(),
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
- // Merge users: alias user1 -> user2
- new EventBuilder(team, user1DistinctId)
- .withEvent('$create_alias')
- .withProperties({
- distinct_id: user1DistinctId,
- alias: user2DistinctId,
- })
- .build(),
- ]
+ // Both persons should be identified
+ expect(persons.map((person) => person.is_identified)).toEqual([true, true])
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Check that events are grouped correctly by person
+ const events = await fetchEvents(clickhouse, team.id)
+ const eventsByPersonId = new Map<string, string[]>()
- await ingester.handleKafkaBatch(createKafkaMessages(events2, token))
- await waitForKafkaMessages(kafkaProducer)
+ for (const event of events) {
+ const personId = event.person_id!
+ if (!eventsByPersonId.has(personId)) {
+ eventsByPersonId.set(personId, [])
+ }
+ eventsByPersonId.get(personId)!.push(event.event)
+ }
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(6)
+ expect(eventsByPersonId.size).toBe(2)
+ const eventGroups = Array.from(eventsByPersonId.values()).sort((a, b) => a.length - b.length)
+ expect(eventGroups).toEqual(
+ expect.arrayContaining([
+ expect.arrayContaining(['event 3', '$identify', 'event 4']),
+ expect.arrayContaining(['$identify', 'event 2', '$identify']),
+ ])
+ )
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'we do not leave things in inconsistent state if $identify is run concurrently',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // There are a few places where we have the pattern of:
+ //
+ // 1. fetch from postgres
+ // 2. check rows match condition
+ // 3. perform update
+ //
+ // This test is designed to check the specific case where, in
+ // handling we are creating an unidentified user, then updating this
+ // user to have is_identified = true. Since we are using the
+ // is_identified to decide on if we will merge persons, we want to
+ // make sure we guard against this race condition.
+
+ const anonymousId = 'anonymous_id'
+ const initialDistinctId = 'initial-distinct-id'
+ const newDistinctId = 'new-distinct-id'
+
+ const events = [
+ new EventBuilder(team, newDistinctId).withEvent('some event').build(),
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- // TODO: Add specific assertions based on expected behavior
- // All events should be processed without errors
- expect(events).toBeDefined()
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ expect(persons.map((person) => person.is_identified)).toEqual([true, true])
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'we can alias an anonymous person to an anonymous person',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const anonymous1 = 'anonymous-1'
+ const anonymous2 = 'anonymous-2'
+
+ const events = [
+ new EventBuilder(team, anonymous1).withEvent('anonymous event 1').build(),
+ new EventBuilder(team, anonymous2).withEvent('anonymous event 2').build(),
+ // Then try to alias them
+ new EventBuilder(team, anonymous2)
+ .withEvent('$create_alias')
+ .withProperties({ alias: anonymous1 })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- // fetch the person properties
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- const personsClickhouse = await fetchPersons(team.id)
- expect(personsClickhouse.length).toBe(2)
- expect(persons.map((person) => person.properties)).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- name: 'User 1',
- new_name: 'User 1 - Updated',
- email: `user1-${user1DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- }),
- expect.objectContaining({
- name: 'User 2',
- new_name: 'User 2 - Updated',
- email: `user2-${user2DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- }),
- ])
- )
- expect(personsClickhouse.map((person) => person.properties)).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- name: 'User 1',
- new_name: 'User 1 - Updated',
- email: `user1-${user1DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- }),
- expect.objectContaining({
- name: 'User 2',
- new_name: 'User 2 - Updated',
- email: `user2-${user2DistinctId}@example.com`,
- age: 30,
- test_name: testName,
- }),
- ])
- )
- const person1 = persons.find((person) => person.properties.name === 'User 1')!
- const person2 = persons.find((person) => person.properties.name === 'User 2')!
- const distinctIdsPersons1 = await fetchDistinctIds(infra.postgres, {
- id: person1.id,
- team_id: team.id,
- } as InternalPerson)
- expect(distinctIdsPersons1.length).toBe(1)
- // Except distinctids to match the ids, in any order
- expect(distinctIdsPersons1.map((distinctId) => distinctId.distinct_id)).toEqual(
- expect.arrayContaining([user1DistinctId])
- )
- const distinctIdsPersons2 = await fetchDistinctIds(infra.postgres, {
- id: person2.id,
- team_id: team.id,
- } as InternalPerson)
- expect(distinctIdsPersons2.length).toBe(2)
- // Except distinctids to match the ids, in any order
- expect(distinctIdsPersons2.map((distinctId) => distinctId.distinct_id)).toEqual(
- expect.arrayContaining([user2DistinctId, user3DistinctId])
- )
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- testWithTeamIngester(
- 'Should set and $unset person properties, different batches',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const user1DistinctId = 'user1-distinct-id'
+ // Make sure there is one identified person
+ expect(persons.map((person) => person.is_identified)).toEqual([true])
- const events = [
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- name: 'User 1',
- property_to_unset: 'value',
- },
- })
- .build(),
- ]
+ // Check that events are grouped correctly by person
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(3)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // All events should belong to the same person
+ const personIds = new Set(events.map((e) => e.person_id))
+ expect(personIds.size).toBe(1)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- const personsClickhouse = await fetchPersons(team.id)
- expect(personsClickhouse.length).toBe(1)
- expect(persons[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- property_to_unset: 'value',
- })
- )
- expect(personsClickhouse[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- property_to_unset: 'value',
- })
- )
- })
+ const eventNames = events.map((e) => e.event).sort()
+ expect(eventNames).toEqual(['$create_alias', 'anonymous event 1', 'anonymous event 2'])
+ })
+ }
+ )
- const events2 = [
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $unset: ['property_to_unset'],
- })
- .build(),
- ]
+ testWithTeamIngester(
+ 'we can alias two non-existent persons',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const anonymous1 = 'anonymous-1'
+ const anonymous2 = 'anonymous-2'
- await ingester.handleKafkaBatch(createKafkaMessages(events2, token))
- await waitForKafkaMessages(kafkaProducer)
+ const events = [
+ new EventBuilder(team, anonymous1)
+ .withEvent('$create_alias')
+ .withProperties({ alias: anonymous2 })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- const personsClickhouse = await fetchPersons(team.id)
- expect(personsClickhouse.length).toBe(1)
- expect(persons[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- })
- )
- expect(persons[0].properties).not.toHaveProperty('property_to_unset')
- expect(personsClickhouse[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- })
- )
- expect(personsClickhouse[0].properties).not.toHaveProperty('property_to_unset')
- })
- }
- )
-
- testWithTeamIngester(
- 'Should set and $unset person properties, same batch',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const user1DistinctId = 'user1-distinct-id'
-
- const events = [
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- name: 'User 1',
- property_to_unset: 'value',
- },
- })
- .build(),
- new EventBuilder(team, user1DistinctId)
- .withEvent('$identify')
- .withProperties({
- $unset: ['property_to_unset'],
- })
- .build(),
- ]
-
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- const personsClickhouse = await fetchPersons(team.id)
- expect(personsClickhouse.length).toBe(1)
- expect(persons[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- })
- )
- expect(persons[0].properties).not.toHaveProperty('property_to_unset')
- expect(personsClickhouse[0].properties).toMatchObject(
- expect.objectContaining({
- name: 'User 1',
- })
- )
- expect(personsClickhouse[0].properties).not.toHaveProperty('property_to_unset')
- })
- }
- )
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'should process events with various timestamps when dropping is disabled',
- { teamOverrides: { drop_events_older_than_seconds: null } },
- async ({ ingester, team, kafkaProducer, token }) => {
- const currentTime = DateTime.now().toMillis()
- const events = [
- // Current time event
- new EventBuilder(team)
- .withEvent('current_time_event')
- .withTimestamp(currentTime)
- .withNow(currentTime)
- .build(),
- // Recent event (30 minutes ago)
- new EventBuilder(team)
- .withEvent('recent_event')
- .withTimestamp(currentTime - 30 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Old event (2 hours ago)
- new EventBuilder(team)
- .withEvent('old_event')
- .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Very old event (1 day ago)
- new EventBuilder(team)
- .withEvent('very_old_event')
- .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Extremely old event (1 month ago)
- new EventBuilder(team)
- .withEvent('extremely_old_event')
- .withTimestamp(currentTime - 30 * 24 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Future event (1 hour from now)
- new EventBuilder(team)
- .withEvent('future_event')
- .withTimestamp(currentTime + 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].is_identified).toBe(true)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([anonymous1, anonymous2])
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- // All events should be processed when dropping is disabled
- expect(events.length).toBe(6)
-
- // Verify all events are present
- const eventTypes = events.map((e) => e.event)
- expect(eventTypes).toContain('current_time_event')
- expect(eventTypes).toContain('recent_event')
- expect(eventTypes).toContain('old_event')
- expect(eventTypes).toContain('very_old_event')
- expect(eventTypes).toContain('extremely_old_event')
- expect(eventTypes).toContain('future_event')
- })
- }
- )
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].event).toBe('$create_alias')
+ })
+ }
+ )
- testWithTeamIngester(
- 'should drop old events when dropping is enabled',
- { teamOverrides: { drop_events_older_than_seconds: 3600 } },
- async ({ ingester, team, kafkaProducer, token }) => {
- const currentTime = DateTime.now().toMillis()
- const events = [
- // Current time event - should pass
- new EventBuilder(team)
- .withEvent('current_time_event')
- .withTimestamp(currentTime)
- .withNow(currentTime)
- .build(),
- // Recent event (30 minutes ago) - should pass
- new EventBuilder(team)
- .withEvent('recent_event')
- .withTimestamp(currentTime - 30 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Just under threshold (59 minutes ago) - should pass
- new EventBuilder(team)
- .withEvent('just_under_threshold')
- .withTimestamp(currentTime - 59 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Just over threshold (61 minutes ago) - should be dropped
- new EventBuilder(team)
- .withEvent('just_over_threshold')
- .withTimestamp(currentTime - 61 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Old event (2 hours ago) - should be dropped
- new EventBuilder(team)
- .withEvent('old_event')
- .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Very old event (1 day ago) - should be dropped
- new EventBuilder(team)
- .withEvent('very_old_event')
- .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Future event (1 hour from now) - should pass
- new EventBuilder(team)
- .withEvent('future_event')
- .withTimestamp(currentTime + 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- ]
+ testWithTeamIngester(
+ '$merge_dangerously merges two persons into one',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const oldDistinctId = 'old_distinct_id'
+ const newDistinctId = 'new_distinct_id'
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Create a person for old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- // Only events under 1 hour old should be processed
- expect(events.length).toBe(4)
-
- // Verify only expected events are present
- const eventTypes = events.map((e) => e.event)
- expect(eventTypes).toContain('current_time_event')
- expect(eventTypes).toContain('recent_event')
- expect(eventTypes).toContain('just_under_threshold')
- expect(eventTypes).toContain('future_event')
-
- // Verify dropped events are not present
- expect(eventTypes).not.toContain('just_over_threshold')
- expect(eventTypes).not.toContain('old_event')
- expect(eventTypes).not.toContain('very_old_event')
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ })
- // Check that ingestion warnings were created for dropped events
- await waitForExpect(async () => {
- const warnings = await fetchIngestionWarnings(clickhouse, team.id)
- expect(warnings.length).toBe(3)
-
- const warningTypes = warnings.map((w) => w.type)
- expect(warningTypes).toEqual(
- expect.arrayContaining([
- 'event_dropped_too_old',
- 'event_dropped_too_old',
- 'event_dropped_too_old',
- ])
- )
- })
- }
- )
+ // Send $merge_dangerously from new_distinct_id with alias: old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$merge_dangerously')
+ .withProperties({ alias: oldDistinctId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'should process all events when drop threshold is set to 0',
- { teamOverrides: { drop_events_older_than_seconds: 0 } },
- async ({ ingester, team, kafkaProducer, token }) => {
- const currentTime = DateTime.now().toMillis()
- const events = [
- // Current time event - should pass
- new EventBuilder(team)
- .withEvent('current_time_event')
- .withTimestamp(currentTime)
- .withNow(currentTime)
- .build(),
- // Recent event (30 minutes ago) - should pass
- new EventBuilder(team)
- .withEvent('recent_event')
- .withTimestamp(currentTime - 30 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Old event (2 hours ago) - should pass (0 threshold means no dropping)
- new EventBuilder(team)
- .withEvent('old_event')
- .withTimestamp(currentTime - 2 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Very old event (1 day ago) - should pass (0 threshold means no dropping)
- new EventBuilder(team)
- .withEvent('very_old_event')
- .withTimestamp(currentTime - 24 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Extremely old event (1 month ago) - should pass (0 threshold means no dropping)
- new EventBuilder(team)
- .withEvent('extremely_old_event')
- .withTimestamp(currentTime - 30 * 24 * 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- // Future event (1 hour from now) - should pass
- new EventBuilder(team)
- .withEvent('future_event')
- .withTimestamp(currentTime + 60 * 60 * 1000)
- .withNow(currentTime)
- .build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
+ })
+ }
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- // All events should be processed when threshold is 0 (no dropping)
- expect(events.length).toBe(6)
-
- // Verify all events are present
- const eventTypes = events.map((e) => e.event)
- expect(eventTypes).toContain('current_time_event')
- expect(eventTypes).toContain('recent_event')
- expect(eventTypes).toContain('old_event')
- expect(eventTypes).toContain('very_old_event')
- expect(eventTypes).toContain('extremely_old_event')
- expect(eventTypes).toContain('future_event')
- })
+ testWithTeamIngester(
+ '$create_alias links existing person to new distinct id',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const oldDistinctId = 'old_distinct_id'
+ const newDistinctId = 'new_distinct_id'
- // Check that no ingestion warnings were created (no events should be dropped)
- await waitForExpect(async () => {
- const warnings = await fetchIngestionWarnings(clickhouse, team.id)
- expect(warnings.length).toBe(0)
- })
- }
- )
+ // Create a person for old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'we do not alias users if distinct id changes but we are already identified, with no anonymous event',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // This test is similar to the previous one, except it does not include an initial anonymous event.
-
- const anonymousId = 'anonymous_id'
- const initialDistinctId = 'initial_distinct_id'
- const p2DistinctId = 'p2_distinct_id'
- const p2NewDistinctId = 'new_distinct_id'
-
- // Play out a sequence of events that should result in two users being
- // identified, with the first to events associated with one user, and
- // the third with another.
- const events = [
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
- new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
- new EventBuilder(team, p2NewDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2DistinctId })
- .build(),
- new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
- // Let's also make sure that we do not alias when switching back to initialDistictId
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2NewDistinctId })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ })
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Send $create_alias from new_distinct_id with alias: old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: oldDistinctId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
-
- // Both persons should be identified
- expect(persons.map((person) => person.is_identified)).toEqual([true, true])
-
- // Check that events are grouped correctly by person
- const events = await fetchEvents(clickhouse, team.id)
- const eventsByPersonId = new Map<string, string[]>()
-
- for (const event of events) {
- const personId = event.person_id!
- if (!eventsByPersonId.has(personId)) {
- eventsByPersonId.set(personId, [])
- }
- eventsByPersonId.get(personId)!.push(event.event)
- }
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- expect(eventsByPersonId.size).toBe(2)
- const eventGroups = Array.from(eventsByPersonId.values()).sort((a, b) => a.length - b.length)
- expect(eventGroups).toEqual(
- expect.arrayContaining([
- expect.arrayContaining(['event 3', '$identify', 'event 4']),
- expect.arrayContaining(['$identify', 'event 2', '$identify']),
- ])
- )
- })
- }
- )
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
+ })
+ }
+ )
- testWithTeamIngester(
- 'we do not leave things in inconsistent state if $identify is run concurrently',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // There are a few places where we have the pattern of:
- //
- // 1. fetch from postgres
- // 2. check rows match condition
- // 3. perform update
- //
- // This test is designed to check the specific case where, in
- // handling we are creating an unidentified user, then updating this
- // user to have is_identified = true. Since we are using the
- // is_identified to decide on if we will merge persons, we want to
- // make sure we guard against this race condition.
-
- const anonymousId = 'anonymous_id'
- const initialDistinctId = 'initial-distinct-id'
- const newDistinctId = 'new-distinct-id'
-
- const events = [
- new EventBuilder(team, newDistinctId).withEvent('some event').build(),
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- new EventBuilder(team, newDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- ]
+ testWithTeamIngester(
+ 'alias works in reverse direction',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const oldDistinctId = 'old_distinct_id'
+ const newDistinctId = 'new_distinct_id'
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Create a person for old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- expect(persons.map((person) => person.is_identified)).toEqual([true, true])
- })
- }
- )
+ // Send $create_alias from old_distinct_id with alias: new_distinct_id (reversed)
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, oldDistinctId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: newDistinctId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'we can alias an anonymous person to an anonymous person',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const anonymous1 = 'anonymous-1'
- const anonymous2 = 'anonymous-2'
-
- const events = [
- new EventBuilder(team, anonymous1).withEvent('anonymous event 1').build(),
- new EventBuilder(team, anonymous2).withEvent('anonymous event 2').build(),
- // Then try to alias them
- new EventBuilder(team, anonymous2)
- .withEvent('$create_alias')
- .withProperties({ alias: anonymous1 })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
+ })
+ }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ testWithTeamIngester(
+ 'chained alias merges three persons into one',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const oldDistinctId = 'old_distinct_id'
+ const newDistinctId = 'new_distinct_id'
+ const oldDistinctId2 = 'old_distinct_id_2'
- // Make sure there is one identified person
- expect(persons.map((person) => person.is_identified)).toEqual([true])
+ // Create person for old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Check that events are grouped correctly by person
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(3)
+ // First alias: link new_distinct_id to old_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: oldDistinctId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // All events should belong to the same person
- const personIds = new Set(events.map((e) => e.person_id))
- expect(personIds.size).toBe(1)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ })
- const eventNames = events.map((e) => e.event).sort()
- expect(eventNames).toEqual(['$create_alias', 'anonymous event 1', 'anonymous event 2'])
- })
- }
- )
+ // Create a second person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, oldDistinctId2).withEvent('custom event 2').withProperties({}).build()],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'we can alias two non-existent persons',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const anonymous1 = 'anonymous-1'
- const anonymous2 = 'anonymous-2'
-
- const events = [
- new EventBuilder(team, anonymous1)
- .withEvent('$create_alias')
- .withProperties({ alias: anonymous2 })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ })
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Second alias: merge old_distinct_id_2 into new_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: oldDistinctId2 })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].is_identified).toBe(true)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([
+ newDistinctId,
+ oldDistinctId,
+ oldDistinctId2,
+ ])
+ })
+ }
+ )
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([anonymous1, anonymous2])
+ testWithTeamIngester(
+ '$create_alias before any person exists creates one person with both distinct ids',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$create_alias')
+ .withProperties({ alias: 'old_distinct_id' })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].event).toBe('$create_alias')
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- testWithTeamIngester(
- '$merge_dangerously merges two persons into one',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const oldDistinctId = 'old_distinct_id'
- const newDistinctId = 'new_distinct_id'
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])
+ })
+ }
+ )
- // Create a person for old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ testWithTeamIngester(
+ '$create_alias merges two existing persons into one',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Create two separate persons
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'old_distinct_id').withEvent('event 1').build(),
+ new EventBuilder(team, 'new_distinct_id').withEvent('event 2').build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ })
- // Send $merge_dangerously from new_distinct_id with alias: old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, newDistinctId)
- .withEvent('$merge_dangerously')
- .withProperties({ alias: oldDistinctId })
- .build(),
- ],
- token
- )
+ // Alias them together
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$create_alias')
+ .withProperties({ alias: 'old_distinct_id' })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
- })
- }
- )
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])
+ })
+ }
+ )
- testWithTeamIngester(
- '$create_alias links existing person to new distinct id',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const oldDistinctId = 'old_distinct_id'
- const newDistinctId = 'new_distinct_id'
+ testWithTeamIngester(
+ 'alias merges person properties correctly',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const newDistinctId = 'new_distinct_id'
+ const oldDistinctId = 'old_distinct_id'
- // Create a person for old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ // Create two persons with different properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { key_on_both: 'new value both', key_on_new: 'new value' },
+ })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- })
-
- // Send $create_alias from new_distinct_id with alias: old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, newDistinctId)
- .withEvent('$create_alias')
- .withProperties({ alias: oldDistinctId })
- .build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, oldDistinctId)
+ .withEvent('$pageview')
+ .withProperties({
+ $set: { key_on_both: 'old value both', key_on_old: 'old value' },
+ })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
-
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
- })
- }
- )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'alias works in reverse direction',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const oldDistinctId = 'old_distinct_id'
- const newDistinctId = 'new_distinct_id'
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ expect(persons.map((p) => p.is_identified)).toEqual([false, false])
+ })
- // Create a person for old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ // Alias them: new_distinct_id's values should win for shared keys
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, newDistinctId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: oldDistinctId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Send $create_alias from old_distinct_id with alias: new_distinct_id (reversed)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, oldDistinctId)
- .withEvent('$create_alias')
- .withProperties({ alias: newDistinctId })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
- })
- }
- )
+ expect(persons[0].properties).toEqual(
+ expect.objectContaining({
+ key_on_both: 'new value both',
+ key_on_new: 'new value',
+ key_on_old: 'old value',
+ })
+ )
+ })
+ }
+ )
- testWithTeamIngester(
- 'chained alias merges three persons into one',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const oldDistinctId = 'old_distinct_id'
- const newDistinctId = 'new_distinct_id'
- const oldDistinctId2 = 'old_distinct_id_2'
+ testWithTeamIngester(
+ '$identify with illegal distinct ids does not merge persons',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const anonymousId = 'im-an-anonymous-id'
- // Create person for old_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ // Create a person for the anonymous ID
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
+
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ })
- // First alias: link new_distinct_id to old_distinct_id
+ // Try to $identify with various illegal IDs — each should fail to merge
+ const illegalIds = ['0', 'None', 'undefined', 'NaN', ' ', 'distinctId']
+ for (const illegalId of illegalIds) {
await ingester.handleKafkaBatch(
createKafkaMessages(
[
- new EventBuilder(team, newDistinctId)
- .withEvent('$create_alias')
- .withProperties({ alias: oldDistinctId })
+ new EventBuilder(team, illegalId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
.build(),
],
token
)
)
await waitForKafkaMessages(kafkaProducer)
+ }
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // 1 original + 5 illegal IDs each created their own person (merges failed)
+ expect(persons.length).toBe(1 + illegalIds.length)
+ })
- // Create a second person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, oldDistinctId2).withEvent('custom event 2').withProperties({}).build()],
- token
- )
+ // 'Nan' is a legal ID (only 'NaN' is illegal), so the merge should work
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'Nan')
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- })
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Second alias: merge old_distinct_id_2 into new_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, newDistinctId)
- .withEvent('$create_alias')
- .withProperties({ alias: oldDistinctId2 })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // No extra person created because 'Nan' merged with the anonymous person
+ expect(persons.length).toBe(1 + illegalIds.length)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
-
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([
- newDistinctId,
- oldDistinctId,
- oldDistinctId2,
- ])
- })
- }
- )
+ testWithTeamIngester(
+ '$create_alias with illegal distinct id does not merge persons',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const legalId = 'user123'
+ const illegalId = 'null'
- testWithTeamIngester(
- '$create_alias before any person exists creates one person with both distinct ids',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$create_alias')
- .withProperties({ alias: 'old_distinct_id' })
- .build(),
- ],
- token
- )
+ // Create a person for the legal ID
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, legalId).withEvent('custom event').withProperties({}).build()],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ // Try $create_alias with an illegal alias
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, illegalId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: legalId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // Person with illegal ID got created but not merged
+ expect(persons.length).toBe(2)
+ })
+ }
+ )
+
+ // This case is likely to happen after signup, for example:
+ // 1. User browses website with anonymous_id
+ // 2. User signs up, triggers event with their new_distinct_id (creating a new Person)
+ // 3. In the frontend, try to alias anonymous_id with new_distinct_id
+ // Result should be that we end up with one Person with both ID's
+ testWithTeamIngester(
+ '$identify merges anonymous person into existing person preserving properties',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Create two persons: one anonymous, one with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- '$create_alias merges two existing persons into one',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // Create two separate persons
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'old_distinct_id').withEvent('event 1').build(),
- new EventBuilder(team, 'new_distinct_id').withEvent('event 2').build(),
- ],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$identify')
+ .withProperties({ $set: { email: '[email protected]' } })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- })
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ })
- // Alias them together
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$create_alias')
- .withProperties({ alias: 'old_distinct_id' })
- .build(),
- ],
- token
- )
+ // $identify merges anonymous_id into new_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: 'anonymous_id' })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- testWithTeamIngester(
- 'alias merges person properties correctly',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const newDistinctId = 'new_distinct_id'
- const oldDistinctId = 'old_distinct_id'
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['anonymous_id', 'new_distinct_id'])
+ expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
+ expect(persons[0].is_identified).toBe(true)
+ })
+ }
+ )
- // Create two persons with different properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, newDistinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { key_on_both: 'new value both', key_on_new: 'new value' },
- })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ testWithTeamIngester(
+ '$identify where distinct_id equals $anon_distinct_id is a no-op',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const anonymousId = 'anonymous_id'
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, oldDistinctId)
- .withEvent('$pageview')
- .withProperties({
- $set: { key_on_both: 'old value both', key_on_old: 'old value' },
- })
- .build(),
- ],
- token
- )
+ // Create a person for anonymous_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- expect(persons.map((p) => p.is_identified)).toEqual([false, false])
- })
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Alias them: new_distinct_id's values should win for shared keys
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, newDistinctId)
- .withEvent('$create_alias')
- .withProperties({ alias: oldDistinctId })
- .build(),
- ],
- token
- )
+ // Send $identify where distinct_id == $anon_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, anonymousId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id)).toEqual([anonymousId])
- expect(persons[0].properties).toEqual(
- expect.objectContaining({
- key_on_both: 'new value both',
- key_on_new: 'new value',
- key_on_old: 'old value',
- })
- )
- })
- }
- )
+ // Person should NOT be marked as identified (self-identify is a no-op)
+ expect(persons[0].is_identified).toBe(false)
+ })
+ }
+ )
- testWithTeamIngester(
- '$identify with illegal distinct ids does not merge persons',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const anonymousId = 'im-an-anonymous-id'
+ testWithTeamIngester(
+ '$identify merges multiple anonymous persons sequentially preserving properties',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Create anonymous person and identified person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Create a person for the anonymous ID
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$identify')
+ .withProperties({ $set: { email: '[email protected]' } })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- })
+ // First $identify: merge anonymous_id into new_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: 'anonymous_id' })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Try to $identify with various illegal IDs — each should fail to merge
- const illegalIds = ['0', 'None', 'undefined', 'NaN', ' ', 'distinctId']
- for (const illegalId of illegalIds) {
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, illegalId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
- }
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
+ expect(persons[0].is_identified).toBe(true)
+ })
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // 1 original + 5 illegal IDs each created their own person (merges failed)
- expect(persons.length).toBe(1 + illegalIds.length)
- })
+ // Create a second anonymous person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages([new EventBuilder(team, 'anonymous_id_2').withEvent('anon event 2').build()], token)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // 'Nan' is a legal ID (only 'NaN' is illegal), so the merge should work
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'Nan')
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- ],
- token
- )
+ // Second $identify: merge anonymous_id_2 into new_distinct_id
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'new_distinct_id')
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: 'anonymous_id_2' })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // No extra person created because 'Nan' merged with the anonymous person
- expect(persons.length).toBe(1 + illegalIds.length)
- })
- }
- )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- '$create_alias with illegal distinct id does not merge persons',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const legalId = 'user123'
- const illegalId = 'null'
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([
+ 'anonymous_id',
+ 'anonymous_id_2',
+ 'new_distinct_id',
+ ])
+ expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
+ expect(persons[0].is_identified).toBe(true)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ '$identify does not merge persons across teams',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Create a second team
+ const team2Id = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ await createUserTeamAndOrganization(
+ infra.postgres,
+ team2Id,
+ team2Id,
+ new UUIDT().toString(),
+ new UUIDT().toString(),
+ new UUIDT().toString()
+ )
+ const team2 = (await infra.teamManager.getTeam(team2Id))!
- // Create a person for the legal ID
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, legalId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ // Create a person for team2 with distinct_id '2'
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team2, '2')
+ .withEvent('$identify')
+ .withProperties({ $set: { email: '[email protected]' } })
+ .build(),
+ ],
+ team2.api_token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Try $create_alias with an illegal alias
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, illegalId)
- .withEvent('$create_alias')
- .withProperties({ alias: legalId })
- .build(),
- ],
- token
- )
+ // Create persons for team1 with distinct_ids '1' and '2'
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, '1').withEvent('custom event').withProperties({}).build(),
+ new EventBuilder(team, '2').withEvent('custom event').withProperties({}).build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // Person with illegal ID got created but not merged
- expect(persons.length).toBe(2)
- })
- }
- )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // This case is likely to happen after signup, for example:
- // 1. User browses website with anonymous_id
- // 2. User signs up, triggers event with their new_distinct_id (creating a new Person)
- // 3. In the frontend, try to alias anonymous_id with new_distinct_id
- // Result should be that we end up with one Person with both ID's
- testWithTeamIngester(
- '$identify merges anonymous person into existing person preserving properties',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // Create two persons: one anonymous, one with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token)
+ // Merge '1' into '2' on team1
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, '2')
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: '1' })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$identify')
- .withProperties({ $set: { email: '[email protected]' } })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ // Verify team1 merged correctly
+ await waitForExpect(async () => {
+ const team1Persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(team1Persons.length).toBe(1)
+ const distinctIds = await fetchDistinctIds(infra.postgres, team1Persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['1', '2'])
+ })
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- })
+ // Verify team2's person is untouched
+ await waitForExpect(async () => {
+ const team2Persons = await fetchPostgresPersons(infra.postgres, team2Id)
+ expect(team2Persons.length).toBe(1)
+ expect(team2Persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
+ const distinctIds = await fetchDistinctIds(infra.postgres, team2Persons[0])
+ expect(distinctIds.map((d) => d.distinct_id)).toEqual(['2'])
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'we do not alias users if distinct id changes but we are already identified',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // This test is in reference to
+ // https://github.com/PostHog/posthog/issues/5527 , where we were
+ // correctly identifying that an anonymous user before login should be
+ // aliased to the user they subsequently login as, but incorrectly
+ // aliasing on subsequent $identify events. The anonymous case is
+ // special as we want to alias to a known user, but otherwise we
+ // shouldn't be doing so.
+
+ const anonymousId = 'anonymous_id'
+ const initialDistinctId = 'initial_distinct_id'
+ const p2DistinctId = 'p2_distinct_id'
+ const p2NewDistinctId = 'new_distinct_id'
+
+ // Batch 1: anonymous event, identify, event, second person event, second identify, event
+ const events = [
+ new EventBuilder(team, anonymousId).withEvent('event 1').build(),
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
+ new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
+ new EventBuilder(team, p2NewDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2DistinctId })
+ .build(),
+ new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- // $identify merges anonymous_id into new_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: 'anonymous_id' })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ expect(persons.every((p) => p.is_identified)).toBe(true)
+ })
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ // Batch 2: try to alias back to initialDistinctId (should fail — both already identified)
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2NewDistinctId })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['anonymous_id', 'new_distinct_id'])
- expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
- expect(persons[0].is_identified).toBe(true)
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // Still 2 separate persons — merge was rejected because both are identified
+ expect(persons.length).toBe(2)
+ expect(persons.every((p) => p.is_identified)).toBe(true)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'we do not alias already identified users with no anonymous event',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // This test is in reference to
+ // https://github.com/PostHog/posthog/issues/5527 , where we were
+ // correctly identifying that an anonymous user before login should be
+ // aliased to the user they subsequently login as, but incorrectly
+ // aliasing on subsequent $identify events. The anonymous case is
+ // special as we want to alias to a known user, but otherwise we
+ // shouldn't be doing so. This test is similar to the previous one,
+ // except it does not include an initial anonymous event.
+ const anonymousId = 'anonymous_id'
+ const initialDistinctId = 'initial_distinct_id'
+ const p2DistinctId = 'p2_distinct_id'
+ const p2NewDistinctId = 'new_distinct_id'
+
+ const events = [
+ // First user: identify (no prior anonymous event)
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: anonymousId })
+ .build(),
+ new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
+ // Second user
+ new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
+ new EventBuilder(team, p2NewDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2DistinctId })
+ .build(),
+ new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
+ // Try to alias back to initialDistinctId (should fail — both already identified)
+ new EventBuilder(team, initialDistinctId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: p2NewDistinctId })
+ .build(),
+ ]
+
+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- '$identify where distinct_id equals $anon_distinct_id is a no-op',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const anonymousId = 'anonymous_id'
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ expect(persons.map((p) => p.is_identified)).toEqual([true, true])
+
+ const allEvents = await fetchEvents(clickhouse, team.id)
+ const eventsByPersonId = new Map<string, string[]>()
+ for (const event of allEvents) {
+ const personId = event.person_id!
+ if (!eventsByPersonId.has(personId)) {
+ eventsByPersonId.set(personId, [])
+ }
+ eventsByPersonId.get(personId)!.push(event.event)
+ }
- // Create a person for anonymous_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],
- token
- )
+ expect(eventsByPersonId.size).toBe(2)
+ const eventGroups = Array.from(eventsByPersonId.values()).sort((a, b) => a.length - b.length)
+ expect(eventGroups).toEqual(
+ expect.arrayContaining([
+ expect.arrayContaining(['event 3', '$identify', 'event 4']),
+ expect.arrayContaining(['$identify', 'event 2', '$identify']),
+ ])
)
- await waitForKafkaMessages(kafkaProducer)
+ })
+ }
+ )
- // Send $identify where distinct_id == $anon_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, anonymousId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ '$create_alias merges anonymous person into identified person',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const someAnonId = 'some_anon_id'
+ const identifiedId = 'identified_id'
+ const anonymousId = 'anonymous_id'
+
+ // Create a truly identified person (via real $identify merge)
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, identifiedId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: someAnonId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].is_identified).toBe(true)
+ })
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id)).toEqual([anonymousId])
+ // Create an anonymous person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages([new EventBuilder(team, anonymousId).withEvent('anonymous event').build()], token)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Person should NOT be marked as identified (self-identify is a no-op)
- expect(persons[0].is_identified).toBe(false)
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ })
- testWithTeamIngester(
- '$identify merges multiple anonymous persons sequentially preserving properties',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // Create anonymous person and identified person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token)
+ // $create_alias: alias person (anonymous) is not identified → merge allowed
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, identifiedId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: anonymousId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$identify')
- .withProperties({ $set: { email: '[email protected]' } })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
- // First $identify: merge anonymous_id into new_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: 'anonymous_id' })
- .build(),
- ],
- token
- )
+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(
+ [someAnonId, anonymousId, identifiedId].sort()
)
- await waitForKafkaMessages(kafkaProducer)
+ expect(persons[0].is_identified).toBe(true)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
- expect(persons[0].is_identified).toBe(true)
- })
+ testWithTeamIngester(
+ '$create_alias does not merge when alias person is already identified',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const someAnonId = 'some_anon_id'
+ const identifiedId = 'identified_id'
+ const anonymousId = 'anonymous_id'
- // Create a second anonymous person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, 'anonymous_id_2').withEvent('anon event 2').build()],
- token
- )
+ // Create a truly identified person (via real $identify merge)
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, identifiedId)
+ .withEvent('$identify')
+ .withProperties({ $anon_distinct_id: someAnonId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Second $identify: merge anonymous_id_2 into new_distinct_id
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'new_distinct_id')
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: 'anonymous_id_2' })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ // Create an anonymous person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages([new EventBuilder(team, anonymousId).withEvent('anonymous event').build()], token)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
-
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([
- 'anonymous_id',
- 'anonymous_id_2',
- 'new_distinct_id',
- ])
- expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
- expect(persons[0].is_identified).toBe(true)
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(2)
+ })
- testWithTeamIngester(
- '$identify does not merge persons across teams',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // Create a second team
- const team2Id = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
- await createUserTeamAndOrganization(
- infra.postgres,
- team2Id,
- team2Id,
- new UUIDT().toString(),
- new UUIDT().toString(),
- new UUIDT().toString()
- )
- const team2 = (await infra.teamManager.getTeam(team2Id))!
-
- // Create a person for team2 with distinct_id '2'
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team2, '2')
- .withEvent('$identify')
- .withProperties({ $set: { email: '[email protected]' } })
- .build(),
- ],
- team2.api_token
- )
+ // $create_alias: alias person (identifiedId) IS identified → merge blocked
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, anonymousId)
+ .withEvent('$create_alias')
+ .withProperties({ alias: identifiedId })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Create persons for team1 with distinct_ids '1' and '2'
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, '1').withEvent('custom event').withProperties({}).build(),
- new EventBuilder(team, '2').withEvent('custom event').withProperties({}).build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ // Merge blocked: alias person (identifiedId) has is_identified=true
+ expect(persons.length).toBe(2)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'person and group properties are set on events',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ // Create person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('$whatever')
+ .withProperties({ $set: { pineapple: 'on', pizza: 1 } })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Merge '1' into '2' on team1
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, '2')
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: '1' })
- .build(),
- ],
- token
- )
+ // Set up group types
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('$groupidentify')
+ .withProperties({
+ $group_type: 'organization',
+ $group_key: 'org:5',
+ $group_set: { foo: 'bar' },
+ })
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- // Verify team1 merged correctly
- await waitForExpect(async () => {
- const team1Persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(team1Persons.length).toBe(1)
- const distinctIds = await fetchDistinctIds(infra.postgres, team1Persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['1', '2'])
- })
-
- // Verify team2's person is untouched
- await waitForExpect(async () => {
- const team2Persons = await fetchPostgresPersons(infra.postgres, team2Id)
- expect(team2Persons.length).toBe(1)
- expect(team2Persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))
- const distinctIds = await fetchDistinctIds(infra.postgres, team2Persons[0])
- expect(distinctIds.map((d) => d.distinct_id)).toEqual(['2'])
- })
- }
- )
-
- testWithTeamIngester(
- 'we do not alias users if distinct id changes but we are already identified',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // This test is in reference to
- // https://github.com/PostHog/posthog/issues/5527 , where we were
- // correctly identifying that an anonymous user before login should be
- // aliased to the user they subsequently login as, but incorrectly
- // aliasing on subsequent $identify events. The anonymous case is
- // special as we want to alias to a known user, but otherwise we
- // shouldn't be doing so.
-
- const anonymousId = 'anonymous_id'
- const initialDistinctId = 'initial_distinct_id'
- const p2DistinctId = 'p2_distinct_id'
- const p2NewDistinctId = 'new_distinct_id'
-
- // Batch 1: anonymous event, identify, event, second person event, second identify, event
- const events = [
- new EventBuilder(team, anonymousId).withEvent('event 1').build(),
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
- new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
- new EventBuilder(team, p2NewDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2DistinctId })
- .build(),
- new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
- ]
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('$groupidentify')
+ .withProperties({
+ $group_type: 'second',
+ $group_key: 'second_key',
+ $group_set: { pineapple: 'yummy' },
+ })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- expect(persons.every((p) => p.is_identified)).toBe(true)
- })
+ // Send a regular event with group references and $set
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('test event')
+ .withProperties({
+ $set: { new: 5 },
+ $group_0: 'org:5',
+ $group_1: 'second_key',
+ })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Batch 2: try to alias back to initialDistinctId (should fail — both already identified)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2NewDistinctId })
- .build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ const testEvent = events.find((e) => e.event === 'test event')
+ expect(testEvent).toBeDefined()
+ expect(testEvent!.person_properties).toEqual(
+ expect.objectContaining({ pineapple: 'on', pizza: 1, new: 5 })
)
- await waitForKafkaMessages(kafkaProducer)
+ expect(testEvent!.properties.$group_0).toEqual('org:5')
+ expect(testEvent!.properties.$group_1).toEqual('second_key')
+ })
+ }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // Still 2 separate persons — merge was rejected because both are identified
- expect(persons.length).toBe(2)
- expect(persons.every((p) => p.is_identified)).toBe(true)
- })
- }
- )
+ testWithTeamIngester(
+ '$set wins over $set_once on the same key',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('some_event')
+ .withProperties({
+ $set: { a_prop: 'test-set' },
+ $set_once: { a_prop: 'test-set_once' },
+ })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- testWithTeamIngester(
- 'we do not alias already identified users with no anonymous event',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // This test is in reference to
- // https://github.com/PostHog/posthog/issues/5527 , where we were
- // correctly identifying that an anonymous user before login should be
- // aliased to the user they subsequently login as, but incorrectly
- // aliasing on subsequent $identify events. The anonymous case is
- // special as we want to alias to a known user, but otherwise we
- // shouldn't be doing so. This test is similar to the previous one,
- // except it does not include an initial anonymous event.
- const anonymousId = 'anonymous_id'
- const initialDistinctId = 'initial_distinct_id'
- const p2DistinctId = 'p2_distinct_id'
- const p2NewDistinctId = 'new_distinct_id'
-
- const events = [
- // First user: identify (no prior anonymous event)
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: anonymousId })
- .build(),
- new EventBuilder(team, initialDistinctId).withEvent('event 2').build(),
- // Second user
- new EventBuilder(team, p2DistinctId).withEvent('event 3').build(),
- new EventBuilder(team, p2NewDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2DistinctId })
- .build(),
- new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),
- // Try to alias back to initialDistinctId (should fail — both already identified)
- new EventBuilder(team, initialDistinctId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: p2NewDistinctId })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].properties['$set']).toEqual({ a_prop: 'test-set' })
+ expect(events[0].properties['$set_once']).toEqual({ a_prop: 'test-set_once' })
- await ingester.handleKafkaBatch(createKafkaMessages(events, token))
- await waitForKafkaMessages(kafkaProducer)
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].properties).toEqual(expect.objectContaining({ a_prop: 'test-set' }))
+ })
+ }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
- expect(persons.map((p) => p.is_identified)).toEqual([true, true])
-
- const allEvents = await fetchEvents(clickhouse, team.id)
- const eventsByPersonId = new Map<string, string[]>()
- for (const event of allEvents) {
- const personId = event.person_id!
- if (!eventsByPersonId.has(personId)) {
- eventsByPersonId.set(personId, [])
- }
- eventsByPersonId.get(personId)!.push(event.event)
- }
+ testWithTeamIngester(
+ '$unset removes person properties',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // Create person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('$identify')
+ .withProperties({ $set: { a: 1, b: 2, c: 3 } })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- expect(eventsByPersonId.size).toBe(2)
- const eventGroups = Array.from(eventsByPersonId.values()).sort((a, b) => a.length - b.length)
- expect(eventGroups).toEqual(
- expect.arrayContaining([
- expect.arrayContaining(['event 3', '$identify', 'event 4']),
- expect.arrayContaining(['$identify', 'event 2', '$identify']),
- ])
- )
- })
- }
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1, b: 2, c: 3 }))
+ })
- testWithTeamIngester(
- '$create_alias merges anonymous person into identified person',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const someAnonId = 'some_anon_id'
- const identifiedId = 'identified_id'
- const anonymousId = 'anonymous_id'
+ // $unset a and c
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, 'distinct_id1')
+ .withEvent('some_event')
+ .withProperties({ $unset: ['a', 'c'] })
+ .build(),
+ ],
+ token
+ )
+ )
+ await waitForKafkaMessages(kafkaProducer)
- // Create a truly identified person (via real $identify merge)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ const unsetEvent = events.find((e) => e.event === 'some_event')
+ expect(unsetEvent).toBeDefined()
+ expect(unsetEvent!.properties['$unset']).toEqual(['a', 'c'])
+
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].properties).toEqual(expect.objectContaining({ b: 2 }))
+ expect(persons[0].properties).not.toHaveProperty('a')
+ expect(persons[0].properties).not.toHaveProperty('c')
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ '$set and $set_once apply correctly across sequential events',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ // key encodes when the value is updated, e.g. s0 means only set call for the 0th event
+ // s03o23 means via a set in events 0 and 3 plus via set_once on 2nd and 3rd event
+ const set0 = { s0123o0123: 's0a', s02o13: 's0b', s013: 's0e' }
+ const setOnce0 = { s0123o0123: 'o0a', s13o02: 'o0g', o023: 'o0f' }
+ const set1 = { s0123o0123: 's1a', s13o02: 's1g', s1: 's1c', s013: 's1e' }
+ const setOnce1 = { s0123o0123: 'o1a', s02o13: 'o1b', o1: 'o1d' }
+ const set2 = { s0123o0123: 's2a', s02o13: 's2b' }
+ const setOnce2 = { s0123o0123: 'o2a', s13o02: 'o2g', o023: 'o2f' }
+ const set3 = { s0123o0123: 's3a', s13o02: 's3g', s013: 's3e' }
+ const setOnce3 = { s0123o0123: 'o3a', s02o13: 'o3b', o023: 'o3f' }
+
+ const distinctId = 'distinct_id1'
+
+ // Send 4 events sequentially, each with different $set/$set_once
+ for (const [set, setOnce] of [
+ [set0, setOnce0],
+ [set1, setOnce1],
+ [set2, setOnce2],
+ [set3, setOnce3],
+ ]) {
await ingester.handleKafkaBatch(
createKafkaMessages(
[
- new EventBuilder(team, identifiedId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: someAnonId })
+ new EventBuilder(team, distinctId)
+ .withEvent('some_event')
+ .withProperties({ $set: set, $set_once: setOnce })
.build(),
],
token
)
)
await waitForKafkaMessages(kafkaProducer)
+ }
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].is_identified).toBe(true)
- })
-
- // Create an anonymous person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, anonymousId).withEvent('anonymous event').build()],
- token
- )
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+
+ // $set wins: last write for each key
+ // $set_once wins: first write for each key (only if not already set by $set)
+ expect(persons[0].properties).toEqual(
+ expect.objectContaining({
+ s0123o0123: 's3a',
+ s02o13: 's2b',
+ s1: 's1c',
+ o1: 'o1d',
+ s013: 's3e',
+ o023: 'o0f',
+ s13o02: 's3g',
+ })
)
- await waitForKafkaMessages(kafkaProducer)
+ })
+ }
+ )
+
+ testWithTeamIngester(
+ 'Should not share cached person data between batches',
+ {},
+ async ({ ingester, infra, team, kafkaProducer, token }) => {
+ const distinctId = 'user-across-batches'
+
+ // First batch: Create a person with initial properties
+ const batch1Events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { batch1_prop: 'value1', shared_prop: 'batch1' },
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
+ await ingester.handleKafkaBatch(createKafkaMessages(batch1Events, token))
+ await waitForKafkaMessages(kafkaProducer)
+
+ // Verify batch 1 wrote correctly
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ expect(persons[0].properties).toMatchObject({
+ batch1_prop: 'value1',
+ shared_prop: 'batch1',
})
+ })
- // $create_alias: alias person (anonymous) is not identified → merge allowed
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, identifiedId)
- .withEvent('$create_alias')
- .withProperties({ alias: anonymousId })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ // Second batch: Update the same person with new properties
+ // If the store wasn't reset, it might use stale cached data
+ const batch2Events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { batch2_prop: 'value2', shared_prop: 'batch2' },
+ })
+ .build(),
+ ]
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ await ingester.handleKafkaBatch(createKafkaMessages(batch2Events, token))
+ await waitForKafkaMessages(kafkaProducer)
- const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])
- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(
- [someAnonId, anonymousId, identifiedId].sort()
- )
- expect(persons[0].is_identified).toBe(true)
+ // Verify batch 2 wrote correctly and merged with existing properties
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ // Should have properties from both batches, with batch2 overwriting shared_prop
+ expect(persons[0].properties).toMatchObject({
+ batch1_prop: 'value1',
+ batch2_prop: 'value2',
+ shared_prop: 'batch2',
})
- }
- )
-
- testWithTeamIngester(
- '$create_alias does not merge when alias person is already identified',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const someAnonId = 'some_anon_id'
- const identifiedId = 'identified_id'
- const anonymousId = 'anonymous_id'
+ })
- // Create a truly identified person (via real $identify merge)
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, identifiedId)
- .withEvent('$identify')
- .withProperties({ $anon_distinct_id: someAnonId })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ // Third batch: Verify a third batch also works correctly
+ const batch3Events = [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { batch3_prop: 'value3' },
+ })
+ .build(),
+ ]
- // Create an anonymous person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [new EventBuilder(team, anonymousId).withEvent('anonymous event').build()],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ await ingester.handleKafkaBatch(createKafkaMessages(batch3Events, token))
+ await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(2)
+ await waitForExpect(async () => {
+ const persons = await fetchPostgresPersons(infra.postgres, team.id)
+ expect(persons.length).toBe(1)
+ // Should have properties from all three batches
+ expect(persons[0].properties).toMatchObject({
+ batch1_prop: 'value1',
+ batch2_prop: 'value2',
+ batch3_prop: 'value3',
+ shared_prop: 'batch2',
})
+ })
+ }
+ )
- // $create_alias: alias person (identifiedId) IS identified → merge blocked
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, anonymousId)
- .withEvent('$create_alias')
- .withProperties({ alias: identifiedId })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should correctly apply properties_to_set when updating person',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- // Merge blocked: alias person (identifiedId) has is_identified=true
- expect(persons.length).toBe(2)
- })
- }
- )
+ // First event: Create a person with initial properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { initial_prop: 'initial_value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
+ )
+ )
- testWithTeamIngester(
- 'person and group properties are set on events',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- // Create person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('$whatever')
- .withProperties({ $set: { pineapple: 'on', pizza: 1 } })
- .build(),
- ],
- token
- )
+ // Wait for person to be created
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ initial_prop: 'initial_value',
+ })
)
- await waitForKafkaMessages(kafkaProducer)
+ })
- // Set up group types
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('$groupidentify')
- .withProperties({
- $group_type: 'organization',
- $group_key: 'org:5',
- $group_set: { foo: 'bar' },
- })
- .build(),
- ],
- token
- )
+ // Second event: Update the person with new properties via $identify
+ // This is where the bug manifests - properties_to_set is not applied in ASSERT_VERSION mode
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { email: '[email protected]', name: 'Test User' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
+ )
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('$groupidentify')
- .withProperties({
- $group_type: 'second',
- $group_key: 'second_key',
- $group_set: { pineapple: 'yummy' },
- })
- .build(),
- ],
- token
- )
+ // Verify the properties were updated in the database
+ // BUG: With ASSERT_VERSION mode, properties_to_set is not merged into properties
+ // before writing to database, so only the original properties are written
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ // This assertion will FAIL with the bug - email and name won't be set
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ initial_prop: 'initial_value',
+ email: '[email protected]',
+ name: 'Test User',
+ })
)
- await waitForKafkaMessages(kafkaProducer)
+ })
- // Send a regular event with group references and $set
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('test event')
- .withProperties({
- $set: { new: 5 },
- $group_0: 'org:5',
- $group_1: 'second_key',
- })
- .build(),
- ],
- token
- )
+ // Also verify the event has the correct person properties attached
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toEqual(2)
+ // The second event should have accumulated properties
+ expect(events[1].person_properties).toEqual(
+ expect.objectContaining({
+ initial_prop: 'initial_value',
+ email: '[email protected]',
+ name: 'Test User',
+ })
)
- await waitForKafkaMessages(kafkaProducer)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- const testEvent = events.find((e) => e.event === 'test event')
- expect(testEvent).toBeDefined()
- expect(testEvent!.person_properties).toEqual(
- expect.objectContaining({ pineapple: 'on', pizza: 1, new: 5 })
- )
- expect(testEvent!.properties.$group_0).toEqual('org:5')
- expect(testEvent!.properties.$group_1).toEqual('second_key')
- })
- }
- )
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should correctly apply $set_once for new properties',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- testWithTeamIngester(
- '$set wins over $set_once on the same key',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('some_event')
- .withProperties({
- $set: { a_prop: 'test-set' },
- $set_once: { a_prop: 'test-set_once' },
- })
- .build(),
- ],
- token
- )
+ // First event: Create a person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { name: 'Test User' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].properties['$set']).toEqual({ a_prop: 'test-set' })
- expect(events[0].properties['$set_once']).toEqual({ a_prop: 'test-set_once' })
-
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].properties).toEqual(expect.objectContaining({ a_prop: 'test-set' }))
- })
- }
- )
+ )
- testWithTeamIngester(
- '$unset removes person properties',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // Create person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('$identify')
- .withProperties({ $set: { a: 1, b: 2, c: 3 } })
- .build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ name: 'Test User',
+ })
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1, b: 2, c: 3 }))
- })
+ })
- // $unset a and c
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, 'distinct_id1')
- .withEvent('some_event')
- .withProperties({ $unset: ['a', 'c'] })
- .build(),
- ],
- token
- )
+ // Second event: Use $set_once for a new property
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { first_seen: '2024-01-01' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
- await waitForKafkaMessages(kafkaProducer)
-
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- const unsetEvent = events.find((e) => e.event === 'some_event')
- expect(unsetEvent).toBeDefined()
- expect(unsetEvent!.properties['$unset']).toEqual(['a', 'c'])
-
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].properties).toEqual(expect.objectContaining({ b: 2 }))
- expect(persons[0].properties).not.toHaveProperty('a')
- expect(persons[0].properties).not.toHaveProperty('c')
- })
- }
- )
-
- testWithTeamIngester(
- '$set and $set_once apply correctly across sequential events',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- // key encodes when the value is updated, e.g. s0 means only set call for the 0th event
- // s03o23 means via a set in events 0 and 3 plus via set_once on 2nd and 3rd event
- const set0 = { s0123o0123: 's0a', s02o13: 's0b', s013: 's0e' }
- const setOnce0 = { s0123o0123: 'o0a', s13o02: 'o0g', o023: 'o0f' }
- const set1 = { s0123o0123: 's1a', s13o02: 's1g', s1: 's1c', s013: 's1e' }
- const setOnce1 = { s0123o0123: 'o1a', s02o13: 'o1b', o1: 'o1d' }
- const set2 = { s0123o0123: 's2a', s02o13: 's2b' }
- const setOnce2 = { s0123o0123: 'o2a', s13o02: 'o2g', o023: 'o2f' }
- const set3 = { s0123o0123: 's3a', s13o02: 's3g', s013: 's3e' }
- const setOnce3 = { s0123o0123: 'o3a', s02o13: 'o3b', o023: 'o3f' }
-
- const distinctId = 'distinct_id1'
-
- // Send 4 events sequentially, each with different $set/$set_once
- for (const [set, setOnce] of [
- [set0, setOnce0],
- [set1, setOnce1],
- [set2, setOnce2],
- [set3, setOnce3],
- ]) {
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('some_event')
- .withProperties({ $set: set, $set_once: setOnce })
- .build(),
- ],
- token
- )
- )
- await waitForKafkaMessages(kafkaProducer)
- }
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
+ // Verify the $set_once property was added
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ name: 'Test User',
+ first_seen: '2024-01-01',
+ })
+ )
+ })
+ }
+ )
- // $set wins: last write for each key
- // $set_once wins: first write for each key (only if not already set by $set)
- expect(persons[0].properties).toEqual(
- expect.objectContaining({
- s0123o0123: 's3a',
- s02o13: 's2b',
- s1: 's1c',
- o1: 'o1d',
- s013: 's3e',
- o023: 'o0f',
- s13o02: 's3g',
- })
- )
- })
- }
- )
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should preserve $set_once semantics across multiple events',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- testWithTeamIngester(
- 'Should not share cached person data between batches',
- {},
- async ({ ingester, infra, team, kafkaProducer, token }) => {
- const distinctId = 'user-across-batches'
+ // First event: Create person with $set_once for prop1
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { prop1: 'first_value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
+ )
+ )
- // First batch: Create a person with initial properties
- const batch1Events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { batch1_prop: 'value1', shared_prop: 'batch1' },
- })
- .build(),
- ]
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop1: 'first_value',
+ })
+ )
+ })
- await ingester.handleKafkaBatch(createKafkaMessages(batch1Events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Second event: Try to $set_once prop1 again (should NOT overwrite) and add prop2
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { prop1: 'second_value_should_be_ignored', prop2: 'new_property' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
+ )
+ )
- // Verify batch 1 wrote correctly
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- expect(persons[0].properties).toMatchObject({
- batch1_prop: 'value1',
- shared_prop: 'batch1',
+ // Verify prop1 retains first value, prop2 is added
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop1: 'first_value', // Should NOT be overwritten
+ prop2: 'new_property', // New property should be added
})
- })
-
- // Second batch: Update the same person with new properties
- // If the store wasn't reset, it might use stale cached data
- const batch2Events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { batch2_prop: 'value2', shared_prop: 'batch2' },
- })
- .build(),
- ]
+ )
+ })
- await ingester.handleKafkaBatch(createKafkaMessages(batch2Events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // Third event: Another $set_once with prop1 (still should not change) and prop3
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { prop1: 'third_value_also_ignored', prop3: 'another_new' },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
+ )
+ )
- // Verify batch 2 wrote correctly and merged with existing properties
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- // Should have properties from both batches, with batch2 overwriting shared_prop
- expect(persons[0].properties).toMatchObject({
- batch1_prop: 'value1',
- batch2_prop: 'value2',
- shared_prop: 'batch2',
+ // Final verification
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop1: 'first_value', // Still the original value
+ prop2: 'new_property',
+ prop3: 'another_new',
})
- })
+ )
+ })
+ }
+ )
- // Third batch: Verify a third batch also works correctly
- const batch3Events = [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { batch3_prop: 'value3' },
- })
- .build(),
- ]
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should correctly apply $unset operations',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- await ingester.handleKafkaBatch(createKafkaMessages(batch3Events, token))
- await waitForKafkaMessages(kafkaProducer)
+ // First event: Create a person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: {
+ name: 'Test User',
+ email: '[email protected]',
+ to_remove: 'will be removed',
+ },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
+ )
+ )
- await waitForExpect(async () => {
- const persons = await fetchPostgresPersons(infra.postgres, team.id)
- expect(persons.length).toBe(1)
- // Should have properties from all three batches
- expect(persons[0].properties).toMatchObject({
- batch1_prop: 'value1',
- batch2_prop: 'value2',
- batch3_prop: 'value3',
- shared_prop: 'batch2',
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ name: 'Test User',
+ email: '[email protected]',
+ to_remove: 'will be removed',
})
- })
- }
- )
+ )
+ })
- testWithTeamIngester(
- 'ASSERT_VERSION mode should correctly apply properties_to_set when updating person',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ // Second event: Unset a property
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $unset: ['to_remove'],
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
+ )
+ )
- // First event: Create a person with initial properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { initial_prop: 'initial_value' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ // Verify the property was removed
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ name: 'Test User',
+ email: '[email protected]',
+ })
)
+ expect(person!.properties).not.toHaveProperty('to_remove')
+ })
+ }
+ )
- // Wait for person to be created
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- initial_prop: 'initial_value',
- })
- )
- })
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should correctly apply properties after person merge',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const anonDistinctId = new UUIDT().toString()
+ const identifiedDistinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Second event: Update the person with new properties via $identify
- // This is where the bug manifests - properties_to_set is not applied in ASSERT_VERSION mode
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { email: '[email protected]', name: 'Test User' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // First event: Create anonymous person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, anonDistinctId)
+ .withEvent('pageview')
+ .withProperties({
+ $set: { anon_prop: 'anon_value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
)
+ )
- // Verify the properties were updated in the database
- // BUG: With ASSERT_VERSION mode, properties_to_set is not merged into properties
- // before writing to database, so only the original properties are written
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- // This assertion will FAIL with the bug - email and name won't be set
- expect(person!.properties).toEqual(
- expect.objectContaining({
- initial_prop: 'initial_value',
- email: '[email protected]',
- name: 'Test User',
- })
- )
- })
-
- // Also verify the event has the correct person properties attached
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toEqual(2)
- // The second event should have accumulated properties
- expect(events[1].person_properties).toEqual(
- expect.objectContaining({
- initial_prop: 'initial_value',
- email: '[email protected]',
- name: 'Test User',
- })
- )
- })
- }
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, anonDistinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ anon_prop: 'anon_value',
+ })
+ )
+ })
- testWithTeamIngester(
- 'ASSERT_VERSION mode should correctly apply $set_once for new properties',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ // Second event: Identify with merge and set new properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, identifiedDistinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $anon_distinct_id: anonDistinctId,
+ $set: { email: '[email protected]', name: 'Identified User' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
+ )
+ )
- // First event: Create a person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { name: 'Test User' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ // Verify merged person has all properties
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, identifiedDistinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ anon_prop: 'anon_value',
+ email: '[email protected]',
+ name: 'Identified User',
+ })
)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- name: 'Test User',
- })
- )
- })
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should correctly apply properties from multiple events in same batch',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Second event: Use $set_once for a new property
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { first_seen: '2024-01-01' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
- )
-
- // Verify the $set_once property was added
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- name: 'Test User',
- first_seen: '2024-01-01',
- })
- )
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should preserve $set_once semantics across multiple events',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First event: Create person with $set_once for prop1
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { prop1: 'first_value' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
- )
-
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop1: 'first_value',
- })
- )
- })
-
- // Second event: Try to $set_once prop1 again (should NOT overwrite) and add prop2
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { prop1: 'second_value_should_be_ignored', prop2: 'new_property' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // First: Create person
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { initial: 'value' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
)
+ )
- // Verify prop1 retains first value, prop2 is added
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop1: 'first_value', // Should NOT be overwritten
- prop2: 'new_property', // New property should be added
- })
- )
- })
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ })
- // Third event: Another $set_once with prop1 (still should not change) and prop3
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { prop1: 'third_value_also_ignored', prop3: 'another_new' },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ // Send multiple events in same batch that each set different properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop1: 'value1' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop2: 'value2' },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop3: 'value3' },
+ })
+ .withTimestamp(timestamp + 3)
+ .build(),
+ ],
+ token
)
+ )
- // Final verification
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop1: 'first_value', // Still the original value
- prop2: 'new_property',
- prop3: 'another_new',
- })
- )
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should correctly apply $unset operations',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First event: Create a person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: {
- name: 'Test User',
- email: '[email protected]',
- to_remove: 'will be removed',
- },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ // Verify all properties from the batch were applied
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ initial: 'value',
+ prop1: 'value1',
+ prop2: 'value2',
+ prop3: 'value3',
+ })
)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- name: 'Test User',
- email: '[email protected]',
- to_remove: 'will be removed',
- })
- )
- })
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should handle combined $set and $unset in same event',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Second event: Unset a property
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $unset: ['to_remove'],
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // First event: Create a person with properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { keep_prop: 'keep', remove_prop: 'remove' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
)
+ )
- // Verify the property was removed
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- name: 'Test User',
- email: '[email protected]',
- })
- )
- expect(person!.properties).not.toHaveProperty('to_remove')
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should correctly apply properties after person merge',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const anonDistinctId = new UUIDT().toString()
- const identifiedDistinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First event: Create anonymous person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, anonDistinctId)
- .withEvent('pageview')
- .withProperties({
- $set: { anon_prop: 'anon_value' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ keep_prop: 'keep',
+ remove_prop: 'remove',
+ })
)
+ })
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, anonDistinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- anon_prop: 'anon_value',
- })
- )
- })
-
- // Second event: Identify with merge and set new properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, identifiedDistinctId)
- .withEvent('$identify')
- .withProperties({
- $anon_distinct_id: anonDistinctId,
- $set: { email: '[email protected]', name: 'Identified User' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // Second event: Set new property AND unset existing property in same event
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { new_prop: 'new_value' },
+ $unset: ['remove_prop'],
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ ],
+ token
)
+ )
- // Verify merged person has all properties
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, identifiedDistinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- anon_prop: 'anon_value',
- email: '[email protected]',
- name: 'Identified User',
- })
- )
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should correctly apply properties from multiple events in same batch',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First: Create person
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { initial: 'value' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ // Verify the new property was added and the old one was removed
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ keep_prop: 'keep',
+ new_prop: 'new_value',
+ })
)
+ expect(person!.properties).not.toHaveProperty('remove_prop')
+ })
+ }
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- })
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should handle $unset overlaps within a batch',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Send multiple events in same batch that each set different properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop1: 'value1' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop2: 'value2' },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop3: 'value3' },
- })
- .withTimestamp(timestamp + 3)
- .build(),
- ],
- token
- )
+ // First: Create person with multiple properties
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ ],
+ token
)
+ )
- // Verify all properties from the batch were applied
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- initial: 'value',
- prop1: 'value1',
- prop2: 'value2',
- prop3: 'value3',
- })
- )
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should handle combined $set and $unset in same event',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First event: Create a person with properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { keep_prop: 'keep', remove_prop: 'remove' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop1: 'value1',
+ prop2: 'value2',
+ prop3: 'value3',
+ prop4: 'value4',
+ })
)
+ })
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- keep_prop: 'keep',
- remove_prop: 'remove',
- })
- )
- })
-
- // Second event: Set new property AND unset existing property in same event
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { new_prop: 'new_value' },
- $unset: ['remove_prop'],
- })
- .withTimestamp(timestamp + 1)
- .build(),
- ],
- token
- )
+ // Send batch with overlapping $unset operations
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // First event unsets prop1 and prop2
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $unset: ['prop1', 'prop2'],
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ // Second event also tries to unset prop2 (overlap) and unsets prop3
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $unset: ['prop2', 'prop3'],
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ // Third event sets a new property and unsets prop2 again (already unset)
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { new_prop: 'new_value' },
+ $unset: ['prop2'],
+ })
+ .withTimestamp(timestamp + 3)
+ .build(),
+ ],
+ token
)
+ )
- // Verify the new property was added and the old one was removed
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- keep_prop: 'keep',
- new_prop: 'new_value',
- })
- )
- expect(person!.properties).not.toHaveProperty('remove_prop')
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should handle $unset overlaps within a batch',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // First: Create person with multiple properties
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4' },
- })
- .withTimestamp(timestamp)
- .build(),
- ],
- token
- )
+ // Verify all unsets were applied correctly despite overlaps
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop4: 'value4', // Only prop4 should remain from original
+ new_prop: 'new_value', // New property added
+ })
)
+ expect(person!.properties).not.toHaveProperty('prop1')
+ expect(person!.properties).not.toHaveProperty('prop2')
+ expect(person!.properties).not.toHaveProperty('prop3')
+ })
+ }
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop1: 'value1',
- prop2: 'value2',
- prop3: 'value3',
- prop4: 'value4',
- })
- )
- })
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should preserve $set_once semantics within same batch',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // Send batch with overlapping $unset operations
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // First event unsets prop1 and prop2
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $unset: ['prop1', 'prop2'],
- })
- .withTimestamp(timestamp + 1)
- .build(),
- // Second event also tries to unset prop2 (overlap) and unsets prop3
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $unset: ['prop2', 'prop3'],
- })
- .withTimestamp(timestamp + 2)
- .build(),
- // Third event sets a new property and unsets prop2 again (already unset)
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { new_prop: 'new_value' },
- $unset: ['prop2'],
- })
- .withTimestamp(timestamp + 3)
- .build(),
- ],
- token
- )
+ // Send all events in same batch - $set_once should only apply first value
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { prop1: 'first_value', prop2: 'first_prop2' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: { prop1: 'second_value_ignored', prop3: 'first_prop3' },
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set_once: {
+ prop1: 'third_value_ignored',
+ prop2: 'second_prop2_ignored',
+ prop4: 'first_prop4',
+ },
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
)
+ )
- // Verify all unsets were applied correctly despite overlaps
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop4: 'value4', // Only prop4 should remain from original
- new_prop: 'new_value', // New property added
- })
- )
- expect(person!.properties).not.toHaveProperty('prop1')
- expect(person!.properties).not.toHaveProperty('prop2')
- expect(person!.properties).not.toHaveProperty('prop3')
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should preserve $set_once semantics within same batch',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
-
- // Send all events in same batch - $set_once should only apply first value
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { prop1: 'first_value', prop2: 'first_prop2' },
- })
- .withTimestamp(timestamp)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: { prop1: 'second_value_ignored', prop3: 'first_prop3' },
- })
- .withTimestamp(timestamp + 1)
- .build(),
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set_once: {
- prop1: 'third_value_ignored',
- prop2: 'second_prop2_ignored',
- prop4: 'first_prop4',
- },
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop1: 'first_value', // First $set_once wins
+ prop2: 'first_prop2', // First $set_once wins
+ prop3: 'first_prop3', // New property from second event
+ prop4: 'first_prop4', // New property from third event
+ })
)
+ })
+ }
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop1: 'first_value', // First $set_once wins
- prop2: 'first_prop2', // First $set_once wins
- prop3: 'first_prop3', // New property from second event
- prop4: 'first_prop4', // New property from third event
- })
- )
- })
- }
- )
-
- testWithTeamIngester(
- 'ASSERT_VERSION mode should handle combined $set and $unset within same batch',
- { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
- async ({ ingester, infra, team, token }) => {
- const distinctId = new UUIDT().toString()
- const timestamp = DateTime.now().toMillis()
+ testWithTeamIngester(
+ 'ASSERT_VERSION mode should handle combined $set and $unset within same batch',
+ { pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },
+ async ({ ingester, infra, team, token }) => {
+ const distinctId = new UUIDT().toString()
+ const timestamp = DateTime.now().toMillis()
- // All operations in same batch including person creation
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- // First event creates person with initial properties
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3' },
- })
- .withTimestamp(timestamp)
- .build(),
- // Second event sets new property and unsets prop1
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop4: 'value4' },
- $unset: ['prop1'],
- })
- .withTimestamp(timestamp + 1)
- .build(),
- // Third event updates prop2 and unsets prop3
- new EventBuilder(team, distinctId)
- .withEvent('$identify')
- .withProperties({
- $set: { prop2: 'updated_value2' },
- $unset: ['prop3'],
- })
- .withTimestamp(timestamp + 2)
- .build(),
- ],
- token
- )
+ // All operations in same batch including person creation
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ // First event creates person with initial properties
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3' },
+ })
+ .withTimestamp(timestamp)
+ .build(),
+ // Second event sets new property and unsets prop1
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop4: 'value4' },
+ $unset: ['prop1'],
+ })
+ .withTimestamp(timestamp + 1)
+ .build(),
+ // Third event updates prop2 and unsets prop3
+ new EventBuilder(team, distinctId)
+ .withEvent('$identify')
+ .withProperties({
+ $set: { prop2: 'updated_value2' },
+ $unset: ['prop3'],
+ })
+ .withTimestamp(timestamp + 2)
+ .build(),
+ ],
+ token
)
+ )
- await waitForExpect(async () => {
- const person = await infra.personRepository.fetchPerson(team.id, distinctId)
- expect(person).toBeDefined()
- expect(person!.properties).toEqual(
- expect.objectContaining({
- prop2: 'updated_value2', // Updated by third event
- prop4: 'value4', // Added by second event
- })
- )
- expect(person!.properties).not.toHaveProperty('prop1') // Unset by second event
- expect(person!.properties).not.toHaveProperty('prop3') // Unset by third event
- })
- }
- )
+ await waitForExpect(async () => {
+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)
+ expect(person).toBeDefined()
+ expect(person!.properties).toEqual(
+ expect.objectContaining({
+ prop2: 'updated_value2', // Updated by third event
+ prop4: 'value4', // Added by second event
+ })
+ )
+ expect(person!.properties).not.toHaveProperty('prop1') // Unset by second event
+ expect(person!.properties).not.toHaveProperty('prop3') // Unset by third event
+ })
+ }
+ )
- testWithTeamIngester(
- 'should scrub IPs when team.anonymize_ips=true',
- { teamOverrides: { anonymize_ips: true } },
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$pageview')
- .withProperties({ $ip: '11.12.13.14' })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'should scrub IPs when team.anonymize_ips=true',
+ { teamOverrides: { anonymize_ips: true } },
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$pageview')
+ .withProperties({ $ip: '11.12.13.14' })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].properties.$ip).toBeUndefined()
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].properties.$ip).toBeUndefined()
+ })
+ }
+ )
- testWithTeamIngester(
- 'should use $elements_chain string directly as elements_chain',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$autocapture')
- .withProperties({ $elements_chain: 'button:nth-child="1"', a: 1 })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'should use $elements_chain string directly as elements_chain',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$autocapture')
+ .withProperties({ $elements_chain: 'button:nth-child="1"', a: 1 })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].elements_chain).toBeDefined()
- expect(events[0].properties.$elements_chain).toBeUndefined()
- expect(events[0].properties.a).toBe(1)
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].elements_chain).toBeDefined()
+ expect(events[0].properties.$elements_chain).toBeUndefined()
+ expect(events[0].properties.a).toBe(1)
+ })
+ }
+ )
- testWithTeamIngester(
- 'should convert $elements array to elements_chain',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$autocapture')
- .withProperties({
- $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],
- a: 1,
- })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'should convert $elements array to elements_chain',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$autocapture')
+ .withProperties({
+ $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],
+ a: 1,
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- expect(events[0].elements_chain).toBeDefined()
- expect(events[0].properties.$elements).toBeUndefined()
- expect(events[0].properties.a).toBe(1)
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ expect(events[0].elements_chain).toBeDefined()
+ expect(events[0].properties.$elements).toBeUndefined()
+ expect(events[0].properties.a).toBe(1)
+ })
+ }
+ )
- testWithTeamIngester(
- 'should prefer $elements_chain over $elements when both are present',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$autocapture')
- .withProperties({
- $elements_chain: 'span:nth-child="1"',
- $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],
- })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'should prefer $elements_chain over $elements when both are present',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$autocapture')
+ .withProperties({
+ $elements_chain: 'span:nth-child="1"',
+ $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- // elements_chain is parsed back into element objects by parseRawClickHouseEvent
- // so we check the first element's tag_name to verify $elements_chain was used
- expect(events[0].elements_chain).toBeDefined()
- expect(events[0].elements_chain![0].tag_name).toBe('span')
- expect(events[0].properties.$elements_chain).toBeUndefined()
- expect(events[0].properties.$elements).toBeUndefined()
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ // elements_chain is parsed back into element objects by parseRawClickHouseEvent
+ // so we check the first element's tag_name to verify $elements_chain was used
+ expect(events[0].elements_chain).toBeDefined()
+ expect(events[0].elements_chain![0].tag_name).toBe('span')
+ expect(events[0].properties.$elements_chain).toBeUndefined()
+ expect(events[0].properties.$elements).toBeUndefined()
+ })
+ }
+ )
- testWithTeamIngester(
- 'should route $ai_generation events through AI subpipeline with full enrichment',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$ai_generation')
- .withProperties({
- $ai_model: 'gpt-4',
- $ai_provider: 'openai',
- $ai_input_tokens: 100,
- $ai_output_tokens: 50,
- $ai_trace_id: 12345,
- $ai_parent_id: 67890,
- $ai_model_parameters: {
- temperature: 0.7,
- stream: true,
- max_tokens: 1024,
- },
- $ai_output_choices: JSON.stringify([
- {
- role: 'assistant',
- message: {
- tool_calls: [
- { function: { name: 'get_weather' } },
- { function: { name: 'search_docs' } },
- ],
- },
+ testWithTeamIngester(
+ 'should route $ai_generation events through AI subpipeline with full enrichment',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$ai_generation')
+ .withProperties({
+ $ai_model: 'gpt-4',
+ $ai_provider: 'openai',
+ $ai_input_tokens: 100,
+ $ai_output_tokens: 50,
+ $ai_trace_id: 12345,
+ $ai_parent_id: 67890,
+ $ai_model_parameters: {
+ temperature: 0.7,
+ stream: true,
+ max_tokens: 1024,
+ },
+ $ai_output_choices: JSON.stringify([
+ {
+ role: 'assistant',
+ message: {
+ tool_calls: [
+ { function: { name: 'get_weather' } },
+ { function: { name: 'search_docs' } },
+ ],
},
- ]),
- })
- .build(),
- ],
- token
- )
+ },
+ ]),
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- const props = events[0].properties
-
- // Cost calculation: input/output/total costs from token counts + model pricing
- expect(props.$ai_input_cost_usd).toBeGreaterThan(0)
- expect(props.$ai_output_cost_usd).toBeGreaterThan(0)
- expect(props.$ai_total_cost_usd).toBeGreaterThan(0)
- expect(props.$ai_total_cost_usd).toBe(props.$ai_input_cost_usd + props.$ai_output_cost_usd)
-
- // Cost model metadata
- expect(props.$ai_model_cost_used).toBeDefined()
- expect(props.$ai_cost_model_provider).toBeDefined()
-
- // Trace property normalization: numeric IDs converted to strings
- expect(props.$ai_trace_id).toBe('12345')
- expect(props.$ai_parent_id).toBe('67890')
-
- // Model parameter extraction: promoted to top-level properties
- expect(props.$ai_temperature).toBe(0.7)
- expect(props.$ai_stream).toBe(true)
- expect(props.$ai_max_tokens).toBe(1024)
-
- // Tool call extraction: parsed from $ai_output_choices
- expect(props.$ai_tools_called).toBe('get_weather,search_docs')
- expect(props.$ai_tool_call_count).toBe(2)
- })
- }
- )
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ const props = events[0].properties
+
+ // Cost calculation: input/output/total costs from token counts + model pricing
+ expect(props.$ai_input_cost_usd).toBeGreaterThan(0)
+ expect(props.$ai_output_cost_usd).toBeGreaterThan(0)
+ expect(props.$ai_total_cost_usd).toBeGreaterThan(0)
+ expect(props.$ai_total_cost_usd).toBe(props.$ai_input_cost_usd + props.$ai_output_cost_usd)
+
+ // Cost model metadata
+ expect(props.$ai_model_cost_used).toBeDefined()
+ expect(props.$ai_cost_model_provider).toBeDefined()
+
+ // Trace property normalization: numeric IDs converted to strings
+ expect(props.$ai_trace_id).toBe('12345')
+ expect(props.$ai_parent_id).toBe('67890')
+
+ // Model parameter extraction: promoted to top-level properties
+ expect(props.$ai_temperature).toBe(0.7)
+ expect(props.$ai_stream).toBe(true)
+ expect(props.$ai_max_tokens).toBe(1024)
+
+ // Tool call extraction: parsed from $ai_output_choices
+ expect(props.$ai_tools_called).toBe('get_weather,search_docs')
+ expect(props.$ai_tool_call_count).toBe(2)
+ })
+ }
+ )
- testWithTeamIngester(
- 'should route $ai_trace events through AI subpipeline with trace normalization',
- {},
- async ({ ingester, team, kafkaProducer, token }) => {
- const distinctId = new UUIDT().toString()
- await ingester.handleKafkaBatch(
- createKafkaMessages(
- [
- new EventBuilder(team, distinctId)
- .withEvent('$ai_trace')
- .withProperties({
- $ai_trace_id: 'trace-abc',
- $ai_span_id: 99999,
- $ai_session_id: true,
- })
- .build(),
- ],
- token
- )
+ testWithTeamIngester(
+ 'should route $ai_trace events through AI subpipeline with trace normalization',
+ {},
+ async ({ ingester, team, kafkaProducer, token }) => {
+ const distinctId = new UUIDT().toString()
+ await ingester.handleKafkaBatch(
+ createKafkaMessages(
+ [
+ new EventBuilder(team, distinctId)
+ .withEvent('$ai_trace')
+ .withProperties({
+ $ai_trace_id: 'trace-abc',
+ $ai_span_id: 99999,
+ $ai_session_id: true,
+ })
+ .build(),
+ ],
+ token
)
+ )
- await waitForKafkaMessages(kafkaProducer)
- await waitForExpect(async () => {
- const events = await fetchEvents(clickhouse, team.id)
- expect(events.length).toBe(1)
- const props = events[0].properties
-
- // Trace normalization applied to all AI events
- expect(props.$ai_trace_id).toBe('trace-abc')
- expect(props.$ai_span_id).toBe('99999')
- expect(props.$ai_session_id).toBe('true')
-
- // No cost enrichment for $ai_trace events
- expect(props.$ai_input_cost_usd).toBeUndefined()
- expect(props.$ai_output_cost_usd).toBeUndefined()
- expect(props.$ai_total_cost_usd).toBeUndefined()
- })
- }
- )
- }
-)
+ await waitForKafkaMessages(kafkaProducer)
+ await waitForExpect(async () => {
+ const events = await fetchEvents(clickhouse, team.id)
+ expect(events.length).toBe(1)
+ const props = events[0].properties
+
+ // Trace normalization applied to all AI events
+ expect(props.$ai_trace_id).toBe('trace-abc')
+ expect(props.$ai_span_id).toBe('99999')
+ expect(props.$ai_session_id).toBe('true')
+
+ // No cost enrichment for $ai_trace events
+ expect(props.$ai_input_cost_usd).toBeUndefined()
+ expect(props.$ai_output_cost_usd).toBeUndefined()
+ expect(props.$ai_total_cost_usd).toBeUndefined()
+ })
+ }
+ )
+})
diff --git a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
index f66403d00c2f..691aa018e373 100644
--- a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
@@ -97,6 +97,8 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
+ PERSON_MERGE_FOLD_ENABLED: false,
+ PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',