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.

fix(ingestion): write persons per key and compute merges at delete (#107052)

Zach Brown157cfebafc4e
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.ts
index 87f3bcae865d..63005e1c6e33 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.test.ts
@@ -84,6 +84,7 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {
updateCohortsAndFeatureFlagsForMergeBatch: jest.fn(),
createPerson: jest.fn(),
updatePerson: jest.fn(),
+ handleOversizedPersonProperties: jest.fn(),
updatePersonAssertVersion: jest.fn(),
updatePersonsBatch: jest.fn(),
deletePerson: jest.fn(),
diff --git a/nodejs/src/common/personhog/personhog-person-repository.ts b/nodejs/src/common/personhog/personhog-person-repository.ts
index c99522269965..d1d37659b03f 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.ts
@@ -210,13 +210,29 @@ export class PersonHogPersonRepository implements PersonRepository {
return this.postgres.updatePerson(person, update, tag)
}
+ handleOversizedPersonProperties(
+ person: InternalPerson,
+ update: PersonUpdateFields
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ return this.postgres.handleOversizedPersonProperties(person, update)
+ }
+
updatePersonAssertVersion(personUpdate: PersonUpdate): Promise<[number | undefined, PersonMessage[]]> {
return this.postgres.updatePersonAssertVersion(personUpdate)
}
- updatePersonsBatch(
- personUpdates: PersonUpdate[]
- ): Promise<Map<string, { success: boolean; version?: number; kafkaMessage?: PersonMessage; error?: Error }>> {
+ updatePersonsBatch(personUpdates: PersonUpdate[]): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ > {
return this.postgres.updatePersonsBatch(personUpdates)
}
diff --git a/nodejs/src/common/persons/person-update-batch.ts b/nodejs/src/common/persons/person-update-batch.ts
index aa624c35ba96..9240a62734bd 100644
--- a/nodejs/src/common/persons/person-update-batch.ts
+++ b/nodejs/src/common/persons/person-update-batch.ts
@@ -8,10 +8,11 @@ export interface PersonUpdate {
team_id: number
uuid: string
distinct_id: string
- properties: Properties // Original properties from database
+ properties: Properties // The properties this pod last read or landed
properties_last_updated_at: PropertiesLastUpdatedAt
properties_last_operation: PropertiesLastOperation
created_at: DateTime
+ /** The row version the base reflects, from the newest write answer or row read the entry has taken. */
version: number
is_identified: boolean
is_user_id: number | null
@@ -19,14 +20,25 @@ export interface PersonUpdate {
needs_write: boolean
// Fine-grained property tracking
properties_to_set: Properties // Properties to set/update
+ properties_to_set_once: Properties // Properties to set only where the row has none
properties_to_unset: string[] // Property keys to unset
original_is_identified: boolean
original_created_at: DateTime
original_last_seen_at: DateTime | null
/** If true, bypass batch-level filtering for person property updates (set for $identify, $set, etc.) */
force_update?: boolean
+ /** Set on a record a flush re-targeted after its person was merged away; its lanes are then the only carrier. */
+ retargeted?: boolean
}
+/** A merge's write to the survivor; `properties` holds only the keys to set. Identity and version are the row's. */
+export type MergePersonUpdate = Omit<Partial<InternalPerson>, 'id' | 'uuid' | 'team_id' | 'version'> & {
+ properties_to_set_once?: Properties
+ properties_to_unset?: string[]
+}
+
+export type PendingPersonChanges = { toSet: Properties; toSetOnce: Properties; toUnset: string[]; createdAt: DateTime }
+
export interface PersonPropertyUpdate {
updated: boolean
properties: Properties
@@ -50,6 +62,7 @@ export function fromInternalPerson(person: InternalPerson, distinctId: string):
last_seen_at: person.last_seen_at,
needs_write: false,
properties_to_set: {},
+ properties_to_set_once: {},
properties_to_unset: [],
original_is_identified: person.is_identified,
original_created_at: person.created_at,
@@ -62,6 +75,12 @@ export function toInternalPerson(personUpdate: PersonUpdate): InternalPerson {
// Calculate final properties by applying set and unset operations
const finalProperties = { ...personUpdate.properties }
+ for (const [key, value] of Object.entries(personUpdate.properties_to_set_once)) {
+ if (!Object.hasOwn(finalProperties, key)) {
+ finalProperties[key] = value
+ }
+ }
+
// Apply properties to set
Object.entries(personUpdate.properties_to_set).forEach(([key, value]) => {
finalProperties[key] = value
diff --git a/nodejs/src/common/persons/repositories/person-repository-transaction.ts b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
index f0ed187972f2..1392946b6bdf 100644
--- a/nodejs/src/common/persons/repositories/person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { PersonUpdate } from '~/common/persons/person-update-batch'
import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
@@ -40,6 +41,23 @@ export interface PersonRepositoryTransaction {
/** See PersonRepository.isPersonLive; only meaningful while holding the person's mark. */
isPersonLive(person: InternalPerson): Promise<boolean>
+ /** The target and sources are row-locked, in ascending id order, until the transaction ends. */
+ readMergeRows(teamId: number, targetId: string, sourceIds: string[]): Promise<InternalPerson[]>
+
+ /** See PersonRepository.updatePersonsBatch; the rows are written under this transaction. */
+ updatePersonsBatch(personUpdates: PersonUpdate[]): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ >
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
moveDistinctIds(source: InternalPerson, target: InternalPerson, limit?: number): Promise<MoveDistinctIdsResult>
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index 84db4dd48be6..85a2875d36ec 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -190,6 +190,12 @@ export interface PersonRepository {
tag?: string
): Promise<[InternalPerson, PersonMessage[], boolean]>
+ /** Trims and writes a person whose stored properties already exceed the size limit, or rejects the update. */
+ handleOversizedPersonProperties(
+ person: InternalPerson,
+ update: PersonUpdateFields
+ ): Promise<[InternalPerson, PersonMessage[], boolean]>
+
updatePersonAssertVersion(personUpdate: PersonUpdate): Promise<[number | undefined, PersonMessage[]]>
/**
@@ -198,11 +204,21 @@ export interface PersonRepository {
* - success: boolean indicating if the update succeeded
* - version: the new version if successful
* - kafkaMessage: the Kafka message to send if successful
+ * - person: the row after the update, if successful
* - error: error details if the update failed
*/
- updatePersonsBatch(
- personUpdates: PersonUpdate[]
- ): Promise<Map<string, { success: boolean; version?: number; kafkaMessage?: PersonMessage; error?: Error }>>
+ updatePersonsBatch(personUpdates: PersonUpdate[]): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ >
deletePerson(person: InternalPerson): Promise<PersonMessage[]>
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 fdaf8f8f2b1f..4773861ebf62 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { PersonUpdate } from '~/common/persons/person-update-batch'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { TransactionClient } from '~/common/utils/db/postgres'
import { Properties } from '~/plugin-scaffold'
@@ -71,6 +72,25 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
return await this.repository.isPersonLive(person, this.transaction)
}
+ async readMergeRows(teamId: number, targetId: string, sourceIds: string[]): Promise<InternalPerson[]> {
+ return await this.repository.readMergeRows(teamId, targetId, sourceIds, this.transaction)
+ }
+
+ async updatePersonsBatch(personUpdates: PersonUpdate[]): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ > {
+ return await this.repository.updatePersonsBatch(personUpdates, this.transaction)
+ }
+
async addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return await this.repository.addDistinctId(person, distinctId, version, 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 850db8d850d0..f36844915ea5 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -252,6 +252,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { name: 'Jane' },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -317,28 +318,182 @@ describe('PostgresPersonRepository', () => {
expect(messages).toEqual([])
})
- it('updatePersonsBatch skips tombstoned persons and leaves the death version intact', async () => {
- const livePerson = await createTestPerson(team.id, 'guard-batch-live-did')
- const deadPerson = await createTestPerson(team.id, 'guard-batch-dead-did')
- await tombstonePerson(deadPerson)
- const deathVersion = deadPerson.version + 1
+ it('updatePersonsBatch keeps what another writer set after the snapshot was read', async () => {
+ const person = await createTestPerson(team.id, 'batch-lost-update-did', { own: 'v1' })
+ const olderCreatedAt = person.created_at.minus({ minutes: 5 })
+ const laterLastSeenAt = person.created_at.plus({ hours: 1 })
- const results = await repository.updatePersonsBatch([
- buildPersonUpdate(livePerson, 'guard-batch-live-did', livePerson.version),
- buildPersonUpdate(deadPerson, 'guard-batch-dead-did', deathVersion),
- ])
+ // Another writer lands a key, its metadata and newer scalars after this pod's read.
+ await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ `UPDATE posthog_person
+ SET properties = properties || '{"from_merge": "kept?", "gone": "x"}'::jsonb,
+ properties_last_updated_at = '{"from_merge": "new", "gone": "x"}'::jsonb,
+ created_at = $3, is_identified = true, last_seen_at = $4, version = version + 1
+ WHERE team_id = $1 AND id = $2`,
+ [team.id, person.id, olderCreatedAt.toISO(), laterLastSeenAt.toISO()],
+ 'otherWriter'
+ )
- expect(results.get(livePerson.uuid)).toMatchObject({ success: true })
- expect(results.get(deadPerson.uuid)?.success).toBe(false)
- expect(results.get(deadPerson.uuid)?.error).toBeInstanceOf(NoRowsUpdatedError)
+ // This pod flushes its own $set and $unset from the snapshot it read before that write.
+ const stale = {
+ ...buildPersonUpdate(person, 'batch-lost-update-did', person.version),
+ properties: { own: 'v1' },
+ properties_to_set: { own: 'v2' },
+ properties_to_set_once: { from_merge: 'stale', filled: 'yes' },
+ properties_to_unset: ['gone'],
+ properties_last_updated_at: { from_merge: 'old' },
+ is_identified: false,
+ }
+ const results = await repository.updatePersonsBatch([stale])
+ expect(results.get(person.uuid)).toMatchObject({ success: true })
const rows = await postgres.query(
PostgresUse.PERSONS_WRITE,
- 'SELECT version FROM posthog_person WHERE team_id = $1 AND id = $2',
- [team.id, deadPerson.id],
- 'fetchDeadPersonVersion'
+ `SELECT properties, properties_last_updated_at, is_identified,
+ extract(epoch FROM created_at)::bigint AS created_at_epoch,
+ extract(epoch FROM last_seen_at)::bigint AS last_seen_at_epoch
+ FROM posthog_person WHERE team_id = $1 AND id = $2`,
+ [team.id, person.id],
+ 'fetchAfterBatch'
)
- expect(Number(rows.rows[0].version)).toBe(deathVersion)
+ // Set-once fills a missing key and leaves the other writer's key alone.
+ expect(rows.rows[0].properties).toEqual({ own: 'v2', from_merge: 'kept?', filled: 'yes' })
+ expect(rows.rows[0].properties_last_updated_at).toEqual({ from_merge: 'new', gone: 'x' })
+ expect(Number(rows.rows[0].created_at_epoch)).toBe(Math.floor(olderCreatedAt.toSeconds()))
+ expect(rows.rows[0].is_identified).toBe(true)
+ expect(Number(rows.rows[0].last_seen_at_epoch)).toBe(Math.floor(laterLastSeenAt.toSeconds()))
+ })
+
+ it('updatePersonsBatch writes the snapshot over the row for a team off the per-key allowlist', async () => {
+ const otherTeamId = await createTeam(postgres, team.organization_id)
+ const perKeyRepository = new PostgresPersonRepository(postgres, {
+ personBatchWritePerKeyTeamAllowlist: String(team.id),
+ })
+ const onPerson = await createTestPerson(team.id, 'per-key-on-did', { own: 'v1' })
+ const offPerson = await createTestPerson(otherTeamId, 'per-key-off-did', { own: 'v1' })
+ await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ `UPDATE posthog_person
+ SET properties = properties || '{"other": "kept?"}'::jsonb, is_identified = true, version = version + 1
+ WHERE id = ANY($1::bigint[])`,
+ [[onPerson.id, offPerson.id]],
+ 'otherWriter'
+ )
+ const staleOn = {
+ ...buildPersonUpdate(onPerson, 'per-key-on-did', onPerson.version),
+ properties: { own: 'v1' },
+ properties_to_set: { own: 'v2' },
+ is_identified: false,
+ }
+ const staleOff = {
+ ...buildPersonUpdate(offPerson, 'per-key-off-did', offPerson.version),
+ properties: { own: 'v1' },
+ properties_to_set: { own: 'v2' },
+ is_identified: false,
+ }
+
+ const results = await perKeyRepository.updatePersonsBatch([staleOn, staleOff])
+
+ expect(results.get(onPerson.uuid)).toMatchObject({ success: true })
+ expect(results.get(offPerson.uuid)).toMatchObject({ success: true })
+ const rows = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT id, properties, is_identified FROM posthog_person WHERE id = ANY($1::bigint[]) ORDER BY id',
+ [[onPerson.id, offPerson.id]],
+ 'fetchAfterBatch'
+ )
+ expect(rows.rows).toEqual([
+ { id: onPerson.id, properties: { own: 'v2', other: 'kept?' }, is_identified: true },
+ { id: offPerson.id, properties: { own: 'v2' }, is_identified: false },
+ ])
+ })
+
+ it('readMergeRows locks the target and the sources', async () => {
+ const target = await createTestPerson(team.id, 'merge-rows-target')
+ const source = await createTestPerson(team.id, 'merge-rows-source')
+ const probe = (id: string) =>
+ postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT id FROM posthog_person WHERE id = $1 FOR UPDATE NOWAIT',
+ [id],
+ 'mergeRowsProbe'
+ )
+
+ await postgres.transaction(PostgresUse.PERSONS_WRITE, 'mergeRowsHold', async (tx) => {
+ const rows = await repository.readMergeRows(team.id, target.id, [source.id], tx)
+ expect(rows.map((row) => row.id).sort()).toEqual([target.id, source.id].sort())
+ await expect(probe(target.id)).rejects.toThrow('could not obtain lock')
+ await expect(probe(source.id)).rejects.toThrow('could not obtain lock')
+ })
+ })
+
+ it('updatePersonsBatch locks its rows in ascending id order before it touches any of them', async () => {
+ const first = await createTestPerson(team.id, 'lock-order-first')
+ const second = await createTestPerson(team.id, 'lock-order-second')
+ expect(Number(first.id)).toBeLessThan(Number(second.id))
+ // Rewrite the first row so a physical-order scan reaches the higher id first.
+ await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'UPDATE posthog_person SET version = version + 1 WHERE id = $1',
+ [first.id],
+ 'lockOrderReorder'
+ )
+
+ // A merge holds the lower id; ordered locking blocks the write there and leaves the higher id free.
+ let markLocked!: () => void
+ let releaseHold!: () => void
+ const locked = new Promise<void>((resolve) => (markLocked = resolve))
+ const held = new Promise<void>((resolve) => (releaseHold = resolve))
+ const holder = postgres.transaction(PostgresUse.PERSONS_WRITE, 'lockOrderHold', async (tx) => {
+ await postgres.query(
+ tx,
+ 'SELECT id FROM posthog_person WHERE id = $1 FOR NO KEY UPDATE',
+ [first.id],
+ 'lockOrderHold'
+ )
+ markLocked()
+ await held
+ })
+ await locked
+ const waitingOnLock = async (): Promise<boolean> => {
+ const { rows } = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ `SELECT 1 FROM pg_stat_activity
+ WHERE wait_event_type = 'Lock' AND query LIKE '%<updatePersonsBatch>%'`,
+ [],
+ 'lockOrderProbe'
+ )
+ return rows.length > 0
+ }
+ try {
+ const writing = repository.updatePersonsBatch([
+ buildPersonUpdate(second, 'lock-order-second', second.version),
+ buildPersonUpdate(first, 'lock-order-first', first.version),
+ ])
+ for (let attempt = 0; !(await waitingOnLock()); attempt++) {
+ expect(attempt).toBeLessThan(500)
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+
+ await expect(
+ postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT id FROM posthog_person WHERE id = $1 FOR UPDATE NOWAIT',
+ [second.id],
+ 'lockOrderProbe'
+ )
+ ).resolves.toBeDefined()
+
+ releaseHold()
+ await holder
+ const results = await writing
+ expect(results.get(first.uuid)).toMatchObject({ success: true })
+ expect(results.get(second.uuid)).toMatchObject({ success: true })
+ } finally {
+ releaseHold()
+ await holder
+ }
})
it.each([
@@ -383,6 +538,59 @@ describe('PostgresPersonRepository', () => {
expect(lockedPartitions).toBe(1)
})
+ it('updatePersonsBatch sanitizes null bytes in unset keys the same way as set keys', async () => {
+ const person = await createTestPerson(team.id, 'batch-null-byte-did')
+ const nullByteKey = 'bad\u0000key'
+ const sanitizedKey = 'bad\uFFFDkey'
+
+ // A set of the key lands sanitized; an unset of the same raw key must remove it, not fail the statement.
+ const setting = {
+ ...buildPersonUpdate(person, 'batch-null-byte-did', person.version),
+ properties_to_set: { [nullByteKey]: 'x', keep: 'y' },
+ }
+ expect((await repository.updatePersonsBatch([setting])).get(person.uuid)).toMatchObject({ success: true })
+
+ const unsetting = {
+ ...buildPersonUpdate(person, 'batch-null-byte-did', person.version),
+ properties_to_set: {},
+ properties_to_unset: [nullByteKey],
+ }
+ expect((await repository.updatePersonsBatch([unsetting])).get(person.uuid)).toMatchObject({ success: true })
+
+ const rows = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT properties FROM posthog_person WHERE team_id = $1 AND id = $2',
+ [team.id, person.id],
+ 'fetchAfterNullByteUnset'
+ )
+ expect(rows.rows[0].properties).not.toHaveProperty(sanitizedKey)
+ expect(rows.rows[0].properties).toMatchObject({ keep: 'y' })
+ })
+
+ it('updatePersonsBatch skips tombstoned persons and leaves the death version intact', async () => {
+ const livePerson = await createTestPerson(team.id, 'guard-batch-live-did')
+ const deadPerson = await createTestPerson(team.id, 'guard-batch-dead-did')
+ await tombstonePerson(deadPerson)
+ const deathVersion = deadPerson.version + 1
+
+ const results = await repository.updatePersonsBatch([
+ buildPersonUpdate(livePerson, 'guard-batch-live-did', livePerson.version),
+ buildPersonUpdate(deadPerson, 'guard-batch-dead-did', deathVersion),
+ ])
+
+ expect(results.get(livePerson.uuid)).toMatchObject({ success: true })
+ expect(results.get(deadPerson.uuid)?.success).toBe(false)
+ expect(results.get(deadPerson.uuid)?.error).toBeInstanceOf(NoRowsUpdatedError)
+
+ const rows = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT version FROM posthog_person WHERE team_id = $1 AND id = $2',
+ [team.id, deadPerson.id],
+ 'fetchDeadPersonVersion'
+ )
+ expect(Number(rows.rows[0].version)).toBe(deathVersion)
+ })
+
it.each([
[
'moveDistinctIds',
@@ -1843,6 +2051,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { name: 'Jane', age: 30 },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -1880,6 +2089,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { name: 'Jane', age: 30 },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -1915,6 +2125,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { name: 'Jane' },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -1946,6 +2157,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { new_prop: 'new_value', to_update: 'new' }, // New properties to merge
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -1986,6 +2198,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: {},
properties_to_unset: ['remove_me'],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -2024,6 +2237,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { update: 'new', added: 'fresh' },
properties_to_unset: ['remove'],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -2652,6 +2866,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { description: 'x'.repeat(150) },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
@@ -2902,6 +3117,7 @@ describe('PostgresPersonRepository', () => {
needs_write: true,
properties_to_set: { name: 'Jane', age: 30, data: 'y'.repeat(2500) },
properties_to_unset: [],
+ properties_to_set_once: {},
original_is_identified: false,
original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
original_last_seen_at: null,
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index 54f6d3275ab4..51ec443cb8e1 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -10,7 +10,7 @@ import {
personPropertiesSizeViolationCounter,
} from '~/common/persons/metrics'
import { canTrimProperty } from '~/common/persons/person-property-utils'
-import { PersonUpdate } from '~/common/persons/person-update-batch'
+import { PersonUpdate, toInternalPerson } from '~/common/persons/person-update-batch'
import { CreatePersonResult, MoveDistinctIdsResult, PersonPropertiesSize } from '~/common/utils/db/db'
import {
moveDistinctIdsCountHistogram,
@@ -102,6 +102,8 @@ export interface PostgresPersonRepositoryOptions {
* (team_id, uuid) arbiter requires a unique index production does not have yet.
*/
personCreateClaimTeamAllowlist: string
+ /** Teams whose batch writes merge per key with the row; other teams write the pod's whole view over it ('*' for all). */
+ personBatchWritePerKeyTeamAllowlist: string
}
const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
@@ -110,6 +112,7 @@ const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
personPropertiesTrimTargetBytes: DEFAULT_PERSON_PROPERTIES_TRIM_TARGET_BYTES,
personMergeTombstoneTeamAllowlist: '',
personCreateClaimTeamAllowlist: '',
+ personBatchWritePerKeyTeamAllowlist: '*',
}
export class PostgresPersonRepository
@@ -118,6 +121,7 @@ export class PostgresPersonRepository
private options: PostgresPersonRepositoryOptions
private isTombstoneTeam: ValueMatcher<number>
private isClaimTeam: ValueMatcher<number>
+ private isPerKeyWriteTeam: ValueMatcher<number>
constructor(
private postgres: PostgresRouter,
@@ -126,9 +130,10 @@ export class PostgresPersonRepository
this.options = { ...DEFAULT_OPTIONS, ...options }
this.isTombstoneTeam = buildIntegerMatcher(this.options.personMergeTombstoneTeamAllowlist, true)
this.isClaimTeam = buildIntegerMatcher(this.options.personCreateClaimTeamAllowlist, true)
+ this.isPerKeyWriteTeam = buildIntegerMatcher(this.options.personBatchWritePerKeyTeamAllowlist, true)
}
- private async handleOversizedPersonProperties(
+ async handleOversizedPersonProperties(
person: InternalPerson,
update: PersonUpdateFields,
tx?: TransactionClient
@@ -1533,6 +1538,25 @@ export class PostgresPersonRepository
return rows.length > 0
}
+ async readMergeRows(
+ teamId: number,
+ targetId: string,
+ sourceIds: string[],
+ tx?: TransactionClient
+ ): Promise<InternalPerson[]> {
+ // Ascending id order, as the batch write locks, so the two cannot deadlock.
+ const { rows } = await this.postgres.query<RawPerson>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `SELECT ${PERSON_COLUMNS} FROM posthog_person
+ WHERE team_id = $1 AND id = ANY($2::bigint[]) AND is_deleted = false
+ ORDER BY id
+ FOR NO KEY UPDATE`,
+ [teamId, [targetId, ...sourceIds]],
+ 'readMergeRows'
+ )
+ return rows.map((row) => this.toPerson(row))
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
@@ -2030,14 +2054,7 @@ export class PostgresPersonRepository
async updatePersonAssertVersion(personUpdate: PersonUpdate): Promise<[number | undefined, PersonMessage[]]> {
try {
- // Calculate final properties by applying set and unset operations
- const finalProperties = { ...personUpdate.properties }
- Object.entries(personUpdate.properties_to_set).forEach(([key, value]) => {
- finalProperties[key] = value
- })
- personUpdate.properties_to_unset.forEach((key) => {
- delete finalProperties[key]
- })
+ const finalProperties = toInternalPerson(personUpdate).properties
const { rows } = await this.postgres.query<RawPerson>(
PostgresUse.PERSONS_WRITE,
@@ -2104,91 +2121,141 @@ export class PostgresPersonRepository
* Batch update multiple persons in a single query using UNNEST.
* This uses a fixed query structure regardless of batch size, enabling prepared statement reuse.
*
- * The method updates all mutable fields (properties, is_identified, created_at) and increments version.
- * It does NOT assert version - it always overwrites with the provided values.
+ * No version assertion. A team on the per-key allowlist merges every column with the row; any other team writes
+ * its snapshot over it, in a second statement when a batch spans both.
*/
async updatePersonsBatch(
- personUpdates: PersonUpdate[]
- ): Promise<Map<string, { success: boolean; version?: number; kafkaMessage?: PersonMessage; error?: Error }>> {
+ personUpdates: PersonUpdate[],
+ tx?: TransactionClient
+ ): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ > {
const results = new Map<
string,
- { success: boolean; version?: number; kafkaMessage?: PersonMessage; error?: Error }
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
>()
- if (personUpdates.length === 0) {
- return results
+ const perKey = personUpdates.filter((update) => this.isPerKeyWriteTeam(update.team_id))
+ const snapshot = personUpdates.filter((update) => !this.isPerKeyWriteTeam(update.team_id))
+ for (const [updates, mergePerKey] of [
+ [perKey, true],
+ [snapshot, false],
+ ] as const) {
+ if (updates.length > 0) {
+ await this.runUpdatePersonsBatch(updates, mergePerKey, tx, results)
+ }
}
+ return results
+ }
+ private async runUpdatePersonsBatch(
+ personUpdates: PersonUpdate[],
+ mergePerKey: boolean,
+ tx: TransactionClient | undefined,
+ results: Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ ): Promise<void> {
// Prepare arrays for UNNEST - one array per column we're updating/filtering on
const uuids: string[] = []
const teamIds: number[] = []
const properties: string[] = []
- const propertiesLastUpdatedAt: string[] = []
- const propertiesLastOperation: string[] = []
const isIdentified: boolean[] = []
const createdAt: string[] = []
const lastSeenAt: (string | null)[] = []
+ const propertiesToUnset: string[] = []
+ const propertiesToSetOnce: string[] = []
for (const update of personUpdates) {
uuids.push(update.uuid)
teamIds.push(update.team_id)
- // Calculate final properties by applying set and unset operations
- const finalProperties = { ...update.properties }
- Object.entries(update.properties_to_set).forEach(([key, value]) => {
- finalProperties[key] = value
- })
- update.properties_to_unset.forEach((key) => {
- delete finalProperties[key]
- })
-
- // sanitizeJsonbValue already returns JSON.stringify(value) for objects, so don't double-stringify
- properties.push(sanitizeJsonbValue(finalProperties))
- propertiesLastUpdatedAt.push(sanitizeJsonbValue(update.properties_last_updated_at))
- propertiesLastOperation.push(sanitizeJsonbValue(update.properties_last_operation))
+ properties.push(
+ sanitizeJsonbValue(mergePerKey ? update.properties_to_set : toInternalPerson(update).properties)
+ )
+ propertiesToUnset.push(sanitizeJsonbValue(update.properties_to_unset))
+ propertiesToSetOnce.push(sanitizeJsonbValue(update.properties_to_set_once))
isIdentified.push(update.is_identified)
createdAt.push(update.created_at.toISO()!)
lastSeenAt.push(update.last_seen_at?.toISO() ?? null)
}
+ const setColumns = mergePerKey
+ ? `properties = ((batch.new_set_once::jsonb || p.properties) || batch.new_properties::jsonb)
+ - ARRAY(SELECT jsonb_array_elements_text(batch.unset_json::jsonb)),
+ is_identified = p.is_identified OR batch.new_is_identified,
+ created_at = LEAST(p.created_at, batch.new_created_at::timestamp with time zone),
+ last_seen_at = GREATEST(p.last_seen_at, batch.new_last_seen_at::timestamp with time zone),`
+ : `properties = batch.new_properties::jsonb,
+ is_identified = batch.new_is_identified,
+ created_at = batch.new_created_at::timestamp with time zone,
+ last_seen_at = batch.new_last_seen_at::timestamp with time zone,`
+
try {
// Use UNNEST to pass arrays, keeping query structure constant for prepared statement reuse
// Note: batch column names are prefixed with 'new_' to avoid any potential confusion with table columns
- // The team_id = ANY filter lets the planner prune partitions; the join alone locks all of them.
+ // Lock in ascending id order first, as a merge does, so the two cannot deadlock.
+ // The team_id = ANY filters let the planner prune partitions; the joins alone lock all of them.
const { rows } = await this.postgres.query<RawPerson>(
- PostgresUse.PERSONS_WRITE,
+ tx ?? PostgresUse.PERSONS_WRITE,
`
+ WITH locked AS MATERIALIZED (
+ SELECT p.id FROM posthog_person AS p
+ JOIN UNNEST($1::uuid[], $2::integer[]) AS ids(batch_uuid, batch_team_id)
+ ON p.uuid = ids.batch_uuid AND p.team_id = ids.batch_team_id
+ WHERE p.is_deleted = false AND p.team_id = ANY($2::integer[])
+ ORDER BY p.id
+ FOR NO KEY UPDATE
+ )
UPDATE posthog_person AS p SET
- properties = batch.new_properties::jsonb,
- properties_last_updated_at = batch.new_properties_last_updated_at::jsonb,
- properties_last_operation = batch.new_properties_last_operation::jsonb,
- is_identified = batch.new_is_identified,
- created_at = batch.new_created_at::timestamp with time zone,
- last_seen_at = batch.new_last_seen_at::timestamp with time zone,
+ ${setColumns}
version = COALESCE(p.version, 0)::numeric + 1
FROM UNNEST(
$1::uuid[],
$2::integer[],
$3::text[],
- $4::text[],
+ $4::boolean[],
$5::text[],
- $6::boolean[],
+ $6::text[],
$7::text[],
$8::text[]
- ) AS batch(batch_uuid, batch_team_id, new_properties, new_properties_last_updated_at, new_properties_last_operation, new_is_identified, new_created_at, new_last_seen_at)
+ ) AS batch(batch_uuid, batch_team_id, new_properties, new_is_identified, new_created_at, new_last_seen_at, unset_json, new_set_once)
WHERE p.uuid = batch.batch_uuid AND p.team_id = batch.batch_team_id AND p.is_deleted = false
AND p.team_id = ANY($2::integer[])
+ AND p.id IN (SELECT id FROM locked)
RETURNING ${PERSON_COLUMNS_PREFIXED}
`,
[
uuids,
teamIds,
properties,
- propertiesLastUpdatedAt,
- propertiesLastOperation,
isIdentified,
createdAt,
lastSeenAt,
+ propertiesToUnset,
+ propertiesToSetOnce,
],
'updatePersonsBatch'
)
@@ -2208,6 +2275,7 @@ export class PostgresPersonRepository
success: true,
version: updatedPerson.version,
kafkaMessage: generateKafkaPersonUpdateMessage(updatedPerson),
+ person: updatedPerson,
})
} else {
// Person was not found/updated - likely deleted or merged
@@ -2220,6 +2288,7 @@ export class PostgresPersonRepository
}
}
} catch (error) {
+ // Under a transaction the failed statement has aborted it; the caller must roll back.
// If the batch update fails due to properties size constraint, we need to handle it
// For now, mark all as failed - the caller can fall back to individual updates
if (this.isPropertiesSizeConstraintViolation(error)) {
@@ -2243,8 +2312,6 @@ export class PostgresPersonRepository
}
}
}
-
- return results
}
async updateCohortsAndFeatureFlagsForMerge(
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 bbfa416bfb42..c955565d0794 100644
--- a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
@@ -52,8 +52,20 @@ export interface RawPostgresPersonRepository {
updatePersonAssertVersion(personUpdate: PersonUpdate): Promise<[number | undefined, PersonMessage[]]>
updatePersonsBatch(
- personUpdates: PersonUpdate[]
- ): Promise<Map<string, { success: boolean; version?: number; kafkaMessage?: PersonMessage; error?: Error }>>
+ personUpdates: PersonUpdate[],
+ tx?: TransactionClient
+ ): Promise<
+ Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: PersonMessage
+ person?: InternalPerson
+ error?: Error
+ }
+ >
+ >
deletePerson(person: InternalPerson, tx?: TransactionClient): Promise<PersonMessage[]>
@@ -74,6 +86,14 @@ export interface RawPostgresPersonRepository {
/** See PersonRepository.isPersonLive. */
isPersonLive(person: InternalPerson, tx?: TransactionClient): Promise<boolean>
+ /** The target and sources are row-locked, in ascending id order, until the transaction ends. */
+ readMergeRows(
+ teamId: number,
+ targetId: string,
+ sourceIds: string[],
+ tx?: TransactionClient
+ ): Promise<InternalPerson[]>
+
addDistinctId(
person: InternalPerson,
distinctId: string,
diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap
index cc48ada7ac1c..196364592f75 100644
--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap
+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.serial.test.ts.snap
@@ -1149,7 +1149,7 @@ exports[`IngestionConsumer typical event processing person property merging via
"person_created_at": "2025-01-01 00:00:00",
"person_id": "<REPLACED-UUID-3>",
"person_mode": "full",
- "person_properties": "{"j":"w","$current_url":"http://localhost:8000","$creator_event_uuid":"<REPLACED-UUID-4>","$initial_current_url":"http://localhost:8000","k":"v","l":"x"}",
+ "person_properties": "{"j":"w","k":"v","l":"x","$current_url":"http://localhost:8000","$creator_event_uuid":"<REPLACED-UUID-4>","$initial_current_url":"http://localhost:8000"}",
"project_id": 2,
"properties": "{"$current_url":"http://localhost:8000","alias":"<REPLACED-UUID-1>","$set":{"l":"x","$current_url":"http://localhost:8000"},"$ip":"127.0.0.1","$set_once":{"$initial_current_url":"http://localhost:8000"}}",
"team_id": 2,
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts
new file mode 100644
index 000000000000..0e4ac36f834b
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts
@@ -0,0 +1,562 @@
+import { DateTime } from 'luxon'
+
+import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from '~/common/outputs'
+import { FILTERED_PERSON_UPDATE_PROPERTIES } from '~/common/persons/person-property-utils'
+import { PersonUpdate } from '~/common/persons/person-update-batch'
+import { PersonPropertiesSizeViolationError, PersonRepository } from '~/common/persons/repositories/person-repository'
+import { NoRowsUpdatedError, UUIDT } from '~/common/utils/utils'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+import { InternalPerson } from '~/types'
+
+import { BatchWritingPersonsStore } from './batch-writing-person-store'
+import { createDefaultSyncMergeMode } from './person-merge-types'
+import { EventOps } from './person-update'
+import { MergePersonsRequest } from './persons-store'
+
+type Held = { label: string; deliver: () => void }
+
+/**
+ * Rows with the per-key statement's semantics under a transaction that rolls back on a throw. With
+ * `deferStatements` the batch statement evaluates its rows when the held answer is released, as a statement
+ * blocked on a merge's row lock does.
+ */
+class FakeRepository {
+ rows = new Map<string, InternalPerson>()
+ distinctToUuid = new Map<string, string>()
+ held: Held[] = []
+ holdFetches = false
+ deferStatements = false
+ deleteFailures: unknown[] = []
+ writes: string[] = []
+ private nextId = 1
+
+ addPerson(uuid: string, distinctIds: string[], properties: Record<string, unknown>): InternalPerson {
+ const row: InternalPerson = {
+ id: String(this.nextId++),
+ uuid,
+ team_id: 1,
+ properties: { ...properties },
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ created_at: DateTime.fromISO('2026-01-01T00:00:00Z', { zone: 'utc' }),
+ version: 1,
+ is_identified: false,
+ is_user_id: null,
+ last_seen_at: null,
+ }
+ this.rows.set(uuid, row)
+ for (const distinctId of distinctIds) {
+ this.distinctToUuid.set(`1:${distinctId}`, uuid)
+ }
+ return this.snapshot(row)
+ }
+
+ release(index = 0): void {
+ const [held] = this.held.splice(index, 1)
+ held.deliver()
+ }
+
+ releaseAll(): void {
+ while (this.held.length > 0) {
+ this.release(0)
+ }
+ }
+
+ labels(): string[] {
+ return this.held.map((held) => held.label)
+ }
+
+ async settle(predicate: () => boolean): Promise<void> {
+ for (let i = 0; i < 200 && !predicate(); i++) {
+ await new Promise((resolve) => setImmediate(resolve))
+ }
+ if (!predicate()) {
+ throw new Error(`condition never held; held: ${this.labels().join(', ')}`)
+ }
+ }
+
+ private lookup(teamId: number, distinctId: string): InternalPerson | undefined {
+ const uuid = this.distinctToUuid.get(`${teamId}:${distinctId}`)
+ const row = uuid === undefined ? undefined : this.rows.get(uuid)
+ return row ? this.snapshot(row) : undefined
+ }
+
+ private snapshot(row: InternalPerson): InternalPerson {
+ return { ...row, properties: { ...row.properties } }
+ }
+
+ private deliver<T>(hold: boolean, label: string, value: () => T): Promise<T> {
+ if (!hold) {
+ return Promise.resolve(value())
+ }
+ return new Promise((resolve) => this.held.push({ label, deliver: () => resolve(value()) }))
+ }
+
+ /** Read at call time, answered at release: a read that began before a merge returns the source. */
+ fetchPerson = jest.fn((teamId: number, distinctId: string) => {
+ const person = this.lookup(teamId, distinctId)
+ return this.deliver(this.holdFetches, `fetch:${distinctId}`, () => person)
+ })
+
+ fetchPersonsByDistinctIds = jest.fn((keys: { teamId: number; distinctId: string }[]) =>
+ this.deliver(this.holdFetches, `prefetch:${keys.map((key) => key.distinctId).join(',')}`, () =>
+ keys.flatMap(({ teamId, distinctId }) => {
+ const person = this.lookup(teamId, distinctId)
+ return person ? [{ ...person, distinct_id: distinctId }] : []
+ })
+ )
+ )
+
+ fetchPersonsForUpdateByDistinctIds = jest.fn((teamId: number, distinctIds: string[]) =>
+ this.deliver(this.holdFetches, `fetchForUpdate:${distinctIds.join(',')}`, () =>
+ distinctIds.flatMap((distinctId) => {
+ const person = this.lookup(teamId, distinctId)
+ return person ? [{ ...person, distinct_id: distinctId }] : []
+ })
+ )
+ )
+
+ private applyBatch(updates: PersonUpdate[]): Map<string, unknown> {
+ const results = new Map<string, unknown>()
+ for (const update of updates) {
+ this.writes.push(
+ `write ${update.uuid} set=${JSON.stringify(update.properties_to_set)} setOnce=${JSON.stringify(update.properties_to_set_once)} unset=${JSON.stringify(update.properties_to_unset)}`
+ )
+ if (results.has(update.uuid)) {
+ continue
+ }
+ const row = this.rows.get(update.uuid)
+ if (!row || row.team_id !== update.team_id) {
+ results.set(update.uuid, { success: false, error: new NoRowsUpdatedError(`no row ${update.uuid}`) })
+ continue
+ }
+ const properties = { ...update.properties_to_set_once, ...row.properties, ...update.properties_to_set }
+ for (const key of update.properties_to_unset) {
+ delete properties[key]
+ }
+ row.properties = properties
+ row.is_identified = row.is_identified || update.is_identified
+ row.created_at = DateTime.min(row.created_at, update.created_at)
+ if (update.last_seen_at && (!row.last_seen_at || update.last_seen_at > row.last_seen_at)) {
+ row.last_seen_at = update.last_seen_at
+ }
+ row.version += 1
+ results.set(update.uuid, {
+ success: true,
+ version: row.version,
+ kafkaMessage: {},
+ person: this.snapshot(row),
+ })
+ }
+ return results
+ }
+
+ updatePersonsBatch = jest.fn((updates: PersonUpdate[]) => {
+ const label = `write:${updates.map((update) => update.uuid).join(',')}`
+ if (this.deferStatements) {
+ return this.deliver(true, label, () => this.applyBatch(updates))
+ }
+ const results = this.applyBatch(updates)
+ return this.deliver(false, label, () => results)
+ })
+
+ handleOversizedPersonProperties = jest.fn()
+ personPropertiesSize = jest.fn().mockResolvedValue(0)
+ fetchPersonDistinctIdMappings = jest.fn().mockResolvedValue([])
+
+ inTransaction = jest.fn(async (_description: string, body: (tx: unknown) => Promise<unknown>) => {
+ const rowsBefore = new Map([...this.rows].map(([uuid, row]) => [uuid, this.snapshot(row)]))
+ const idsBefore = new Map(this.distinctToUuid)
+ try {
+ return await body(this.tx)
+ } catch (error) {
+ this.rows = rowsBefore
+ this.distinctToUuid = idsBefore
+ throw error
+ }
+ })
+
+ tx = {
+ claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ isPersonLive: jest.fn().mockResolvedValue(true),
+ /** The merge's own statement: its rows are locked by the merge, so it answers at once. */
+ updatePersonsBatch: jest.fn((updates: PersonUpdate[]) => Promise.resolve(this.applyBatch(updates))),
+ readMergeRows: jest.fn((teamId: number, targetId: string, sourceIds: string[]) =>
+ Promise.resolve(
+ [...this.rows.values()]
+ .filter((row) => row.team_id === teamId && (row.id === targetId || sourceIds.includes(row.id)))
+ .map((row) => this.snapshot(row))
+ )
+ ),
+ moveDistinctIds: jest.fn((source: InternalPerson, target: InternalPerson) => {
+ const moved: string[] = []
+ for (const [key, uuid] of this.distinctToUuid) {
+ if (uuid === source.uuid) {
+ this.distinctToUuid.set(key, target.uuid)
+ moved.push(key.slice(key.indexOf(':') + 1))
+ }
+ }
+ if (moved.length === 0) {
+ return Promise.resolve({ success: false, error: 'SourceNotFound' })
+ }
+ return Promise.resolve({ success: true, messages: [], distinctIdsMoved: moved })
+ }),
+ moveDistinctIdsFromPersons: jest.fn(),
+ updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),
+ updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
+ deletePerson: jest.fn((person: InternalPerson) => {
+ const failure = this.deleteFailures.shift()
+ if (failure) {
+ return Promise.reject(failure)
+ }
+ this.rows.delete(person.uuid)
+ return Promise.resolve([])
+ }),
+ deletePersons: jest.fn(),
+ addDistinctId: jest.fn().mockResolvedValue([]),
+ fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),
+ countDistinctIdsForPersons: jest.fn(),
+ createPerson: jest.fn(),
+ }
+}
+
+const setOps = (set: Record<string, unknown>, unset: string[] = []): EventOps => ({
+ set,
+ setOnce: {},
+ unset,
+ denied: false,
+ shouldForceUpdate: true,
+ eventName: '$set',
+})
+
+function mergeRequest(
+ targetDistinctId: string,
+ sourceDistinctId: string,
+ set: Record<string, unknown> = {}
+): MergePersonsRequest {
+ const eventUuid = new UUIDT().toString()
+ return {
+ teamId: 1,
+ targetDistinctId,
+ sources: [{ distinctId: sourceDistinctId, eventUuid }],
+ eventOps: { set, setOnce: {}, unset: [], denied: false, shouldForceUpdate: true, eventName: '$identify' },
+ eventUuid,
+ allowIdentifiedSources: true,
+ mergeMode: createDefaultSyncMergeMode(),
+ createdAtMs: DateTime.fromISO('2026-02-01T00:00:00Z').toMillis(),
+ }
+}
+
+const makeOutputs = () =>
+ createMockIngestionOutputs<
+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT | PersonMergeEventsOutput
+ >()
+
+describe('BatchWritingPersonsStore merging through PostgresPersonMerge', () => {
+ let fake: FakeRepository
+ let outputs: ReturnType<typeof makeOutputs>
+ let store: BatchWritingPersonsStore
+
+ beforeEach(() => {
+ fake = new FakeRepository()
+ outputs = makeOutputs()
+ store = new BatchWritingPersonsStore(fake as unknown as PersonRepository, outputs, {
+ optimisticUpdateRetryInterval: 1,
+ })
+ })
+
+ afterEach(async () => {
+ fake.holdFetches = false
+ fake.deferStatements = false
+ fake.releaseAll()
+ try {
+ await store.flush()
+ } catch {
+ // a test may leave a write that cannot land
+ }
+ try {
+ await store.shutdown()
+ } catch {
+ // a test may leave the cache dirty
+ }
+ })
+
+ it.each([
+ ['set', {}, setOps({ k: 'A' })],
+ ['unset', { k: 'old' }, setOps({}, ['k'])],
+ ])(
+ "a flush statement blocked behind this pod's merge does not re-target the source's pre-merge %s over the survivor",
+ async (_lane, sourceProperties, ops) => {
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], sourceProperties)
+ const source = await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ await store.applyEventOps(source!, ops, 's', 0)
+ // The statement waits on the source's lock; the merge reads the source's pending change, sees the
+ // survivor holds the key, and decides the survivor wins.
+ fake.deferStatements = true
+ const flushing = store.flush()
+ await fake.settle(() => fake.labels().length === 1)
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+ expect(result.results[0].outcome).toBe('merged')
+ fake.deferStatements = false
+ fake.releaseAll()
+ await flushing
+
+ await store.flush()
+
+ expect(fake.rows.get('S')).toBeUndefined()
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'B' })
+ }
+ )
+
+ it("an identify's $set of a filtered key lands on an already identified survivor", async () => {
+ const filtered = [...FILTERED_PERSON_UPDATE_PROPERTIES][0]
+ fake.addPerson('T', ['t'], { [filtered]: 'old' })
+ fake.rows.get('T')!.is_identified = true
+ fake.addPerson('S', ['s'], {})
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ // The merge queues the event's $set as a set the flush would ignore on its own; the event's ops then
+ // apply to the survivor, as the processor does after a merge.
+ const request = mergeRequest('t', 's', { [filtered]: 'v' })
+ const result = await store.mergePersons(request, 0)
+ await store.applyEventOps(result.survivor!, request.eventOps, 't', 0)
+
+ await store.flush()
+
+ expect(fake.rows.get('T')!.properties).toEqual({ [filtered]: 'v' })
+ })
+
+ it('an explicit $set on a moved id during the merge reaches the survivor although it holds the key', async () => {
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], {})
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ // Between the move and the outcome read, on an id the store already maps.
+ const moveDistinctIds = store.moveDistinctIds.bind(store)
+ jest.spyOn(store, 'moveDistinctIds').mockImplementationOnce(async (...args) => {
+ const moved = await moveDistinctIds(...args)
+ const person = await store.fetchForUpdate(1, 's', 0)
+ await store.applyEventOps(person!, setOps({ k: 'v' }), 's', 0)
+ return moved
+ })
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+ expect(result.results[0].outcome).toBe('merged')
+
+ await store.flush()
+
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'v' })
+ })
+
+ it("a chained re-target keeps the last_seen_at the first hop carried when the survivor's entry is gone", async () => {
+ const seen = DateTime.fromISO('2026-03-01T00:00:00Z', { zone: 'utc' })
+ fake.addPerson('P1', ['a'], {})
+ fake.addPerson('P2', ['b'], {})
+ fake.addPerson('P3', ['c'], {})
+ const p1 = await store.fetchForUpdate(1, 'a', 0)
+ await store.applyEventOps(p1!, setOps({ k: 'A' }), 'a', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(p1!, {}, [], { last_seen_at: seen }, 'a')
+ // Another pod merged P1 into P2; this pod never cached P2.
+ fake.distinctToUuid.set('1:a', 'P2')
+ fake.rows.delete('P1')
+ fake.deferStatements = true
+ const flushing = store.flush()
+ await fake.settle(() => fake.labels().length === 1)
+ fake.release(0)
+ await fake.settle(() => fake.labels().length === 1)
+ fake.release(0)
+ await fake.settle(() => fake.labels().length === 1)
+ expect(fake.labels()).toEqual(['write:P2'])
+ // P2 is merged into P3 while that write waits.
+ fake.distinctToUuid.set('1:a', 'P3')
+ fake.distinctToUuid.set('1:b', 'P3')
+ fake.rows.delete('P2')
+ fake.deferStatements = false
+ fake.release(0)
+ await flushing
+
+ const landed = fake.updatePersonsBatch.mock.calls.flat(2).find((update) => update.uuid === 'P3')
+ expect(landed?.last_seen_at?.toISO()).toBe(seen.toISO())
+ })
+
+ it('a re-target whose survivor is merged away in turn lands on the final survivor', async () => {
+ fake.addPerson('P1', ['a'], {})
+ fake.addPerson('P2', ['b'], {})
+ fake.addPerson('P3', ['c'], {})
+ const p1 = await store.fetchForUpdate(1, 'a', 0)
+ await store.fetchForUpdate(1, 'b', 0)
+ // Another pod merged P1 into P2; this pod still holds P1's entry.
+ fake.distinctToUuid.set('1:a', 'P2')
+ fake.rows.delete('P1')
+ await store.applyEventOps(p1!, setOps({ k: 'A' }), 'a', 0)
+ fake.deferStatements = true
+ const flushing = store.flush()
+ // The statement finds no row for P1, the record retries alone and finds none again, and the re-target
+ // onto P2 waits while another pod merges P2 into P3.
+ await fake.settle(() => fake.labels().length === 1)
+ fake.release(0)
+ await fake.settle(() => fake.labels().length === 1)
+ fake.release(0)
+ await fake.settle(() => fake.labels().length === 1)
+ expect(fake.labels()).toEqual(['write:P2'])
+ fake.distinctToUuid.set('1:a', 'P3')
+ fake.distinctToUuid.set('1:b', 'P3')
+ fake.rows.delete('P2')
+ fake.deferStatements = false
+ fake.release(0)
+ await flushing
+
+ expect(fake.rows.get('P3')!.properties).toEqual({ k: 'A' })
+ })
+
+ it("a merge's outcome is on the row when the pod stops right after the commit", async () => {
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], { a: 1 })
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ jest.spyOn(store, 'takeMergedRow').mockImplementationOnce(() => {
+ throw new Error('pod stopped')
+ })
+
+ await expect(store.mergePersons(mergeRequest('t', 's'), 0)).rejects.toThrow('pod stopped')
+
+ expect(fake.rows.get('S')).toBeUndefined()
+ expect(fake.rows.get('T')).toMatchObject({ properties: { k: 'B', a: 1 }, is_identified: true })
+ })
+
+ it('an oversized survivor rolls the merge back and commits it on a rerun without the outcome, warning once', async () => {
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], { a: 1 })
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ // As in Postgres, the violation aborts its transaction: any later statement in it fails.
+ let abortedTransaction = -1
+ fake.tx.updatePersonsBatch.mockImplementationOnce((updates: PersonUpdate[]) => {
+ abortedTransaction = fake.inTransaction.mock.calls.length
+ return Promise.resolve(
+ new Map(
+ updates.map((update) => [
+ update.uuid,
+ { success: false, error: new PersonPropertiesSizeViolationError('too big', 1, update.id) },
+ ])
+ )
+ )
+ })
+ const deletePerson = fake.tx.deletePerson.getMockImplementation()!
+ fake.tx.deletePerson.mockImplementation((person: InternalPerson) =>
+ fake.inTransaction.mock.calls.length === abortedTransaction
+ ? Promise.reject(new Error('current transaction is aborted'))
+ : deletePerson(person)
+ )
+
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+
+ expect(result.results[0].outcome).toBe('merged')
+ expect(fake.inTransaction).toHaveBeenCalledTimes(2)
+ expect(fake.tx.updatePersonsBatch).toHaveBeenCalledTimes(1)
+ expect(fake.rows.get('S')).toBeUndefined()
+ expect(fake.distinctToUuid.get('1:s')).toBe('T')
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'B' })
+ const warnings = outputs.queueMessages.mock.calls.filter(([output]) => output === INGESTION_WARNINGS_OUTPUT)
+ expect(warnings).toHaveLength(1)
+ expect(String(warnings[0][1][0].value)).toContain('person_properties_size_violation')
+ })
+
+ it("the survivor a merge hands back shows this pod's unflushed changes", async () => {
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], { a: 1 })
+ await store.fetchForUpdate(1, 's', 0)
+ const target = await store.fetchForUpdate(1, 't', 0)
+ await store.applyEventOps(target!, setOps({ p: 'pending' }), 't', 0)
+
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+
+ expect(result.survivor!.properties).toEqual({ k: 'B', a: 1, p: 'pending' })
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'B', a: 1 })
+ })
+
+ it('a merge that rolls back leaves nothing of it queued on the survivor', async () => {
+ const target = fake.addPerson('T', ['t'], { own: 'x' })
+ fake.addPerson('S', ['s', 's2'], { a: 1 })
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ // The delete fails on a concurrent distinct-id add; the retry finds the source merged elsewhere and
+ // settles without merging.
+ fake.deleteFailures.push(Object.assign(new Error('fk'), { code: '23503' }))
+ const lookup = fake.fetchPerson.getMockImplementation()!
+ fake.fetchPerson.mockImplementation((teamId: number, distinctId: string) =>
+ distinctId === 's' && fake.tx.deletePerson.mock.calls.length > 0
+ ? Promise.resolve(undefined)
+ : lookup(teamId, distinctId)
+ )
+
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+
+ expect(result.survivor?.uuid).toBe('T')
+ expect(fake.rows.get('S')).toBeDefined()
+ const entry = store.getCachedPersonForUpdateByPersonId(1, target.id)!
+ expect(entry.properties_to_set_once).toEqual({})
+ expect(entry.is_identified).toBe(false)
+ expect(entry.created_at.toISO()).toBe(target.created_at.toISO())
+ // The rollback made the moved ids the source's again, in the cache too.
+ expect((await store.fetchForUpdate(1, 's2', 0))!.uuid).toBe('S')
+ })
+
+ it('a team off the locked-outcome allowlist queues the survivor for the flush and locks no row', async () => {
+ await store.shutdown()
+ store = new BatchWritingPersonsStore(fake as unknown as PersonRepository, outputs, {
+ optimisticUpdateRetryInterval: 1,
+ mergeLockedOutcomeTeamAllowlist: '',
+ })
+ fake.addPerson('T', ['t'], { k: 'B' })
+ fake.addPerson('S', ['s'], { a: 1, k: 'A' })
+ await store.fetchForUpdate(1, 's', 0)
+ await store.fetchForUpdate(1, 't', 0)
+
+ const result = await store.mergePersons(mergeRequest('t', 's'), 0)
+
+ expect(result.results[0].outcome).toBe('merged')
+ expect(result.survivor!.properties).toEqual({ k: 'B', a: 1 })
+ expect(fake.tx.readMergeRows).not.toHaveBeenCalled()
+ expect(fake.tx.updatePersonsBatch).not.toHaveBeenCalled()
+ expect(fake.rows.get('S')).toBeUndefined()
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'B' })
+
+ await store.flush()
+
+ expect(fake.rows.get('T')).toMatchObject({ properties: { k: 'B', a: 1 }, is_identified: true })
+ })
+
+ it("a re-target keeps the survivor's newer last_seen_at", async () => {
+ const seen = DateTime.fromISO('2026-03-01T00:00:00Z', { zone: 'utc' })
+ fake.addPerson('T', ['t'], {})
+ fake.rows.get('T')!.last_seen_at = seen
+ fake.addPerson('S', ['s'], {})
+ fake.rows.get('S')!.last_seen_at = DateTime.fromISO('2026-01-01T00:00:00Z', { zone: 'utc' })
+ const source = await store.fetchForUpdate(1, 's', 0)
+ await store.applyEventOps(source!, setOps({ k: 'A' }), 's', 0)
+ // Another pod merges S into T.
+ fake.distinctToUuid.set('1:s', 'T')
+ fake.rows.delete('S')
+
+ await store.flush()
+
+ const retargeted = fake.updatePersonsBatch.mock.calls.flat(2).find((update) => update.uuid === 'T')
+ expect(retargeted?.last_seen_at?.toISO()).toBe(seen.toISO())
+ })
+
+ it('a merge that fails for good leaves no moved distinct id mapped to the survivor', async () => {
+ fake.addPerson('T', ['t'], {})
+ fake.addPerson('S', ['s1', 's2'], {})
+ await store.fetchForUpdate(1, 's1', 0)
+ await store.fetchForUpdate(1, 't', 0)
+ fake.deleteFailures.push(new Error('connection reset'))
+
+ await expect(store.mergePersons(mergeRequest('t', 's1'), 0)).rejects.toThrow('connection reset')
+
+ expect((await store.fetchForUpdate(1, 's2', 0))!.uuid).toBe('S')
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.model.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.model.test.ts
new file mode 100644
index 000000000000..00c7e62eb80c
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.model.test.ts
@@ -0,0 +1,1445 @@
+import { isEqual } from 'lodash'
+import { DateTime } from 'luxon'
+
+import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from '~/common/outputs'
+import { FILTERED_PERSON_UPDATE_PROPERTIES } from '~/common/persons/person-property-utils'
+import { MergePersonUpdate, PersonUpdate, toInternalPerson } from '~/common/persons/person-update-batch'
+import { InternalPersonWithDistinctId, PersonRepository } from '~/common/persons/repositories/person-repository'
+import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
+import { NoRowsUpdatedError } from '~/common/utils/utils'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+import { InternalPerson } from '~/types'
+
+import { BatchWritingPersonsStore } from './batch-writing-person-store'
+import { EventOps } from './person-update'
+
+jest.mock('~/ingestion/common/ingestion-warnings', () => ({
+ emitIngestionWarning: jest.fn().mockResolvedValue(undefined),
+}))
+
+jest.mock('~/common/persons/metrics', () => ({
+ observeLatencyByVersion: jest.fn(),
+ personCacheOperationsCounter: { inc: jest.fn() },
+ personCacheSizeHistogram: { observe: jest.fn() },
+ personDatabaseOperationsPerBatchHistogram: { observe: jest.fn() },
+ personFallbackOperationsCounter: { inc: jest.fn() },
+ personFetchForCheckingCacheOperationsCounter: { inc: jest.fn() },
+ personFetchForUpdateCacheOperationsCounter: { inc: jest.fn() },
+ personFlushBatchSizeHistogram: { observe: jest.fn() },
+ personFlushLatencyHistogram: { observe: jest.fn() },
+ personFlushOperationsCounter: { inc: jest.fn() },
+ personMethodCallsPerBatchHistogram: { observe: jest.fn() },
+ personOptimisticUpdateConflictsPerBatchCounter: { inc: jest.fn() },
+ personProfileBatchIgnoredPropertiesCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personProfileIgnoredPropertiesCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personProfileUpdateOutcomeCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personProfileBatchUpdateOutcomeCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personPropertyKeyUpdateCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personRetryAttemptsHistogram: { observe: jest.fn() },
+ personWriteMethodAttemptCounter: { inc: jest.fn() },
+ personWriteMethodLatencyHistogram: { observe: jest.fn() },
+ totalPersonUpdateLatencyPerBatchHistogram: { observe: jest.fn() },
+}))
+
+type Held = { label: string; deliver: () => void }
+type RowSnapshot = { version: number; properties: Record<string, unknown> }
+type Landing = { value: unknown; seq: number; version: number }
+
+/** Reads on master too, where PersonUpdate has no set-once lane. */
+const setOnceOf = (update: { properties_to_set_once?: Record<string, unknown> }): Record<string, unknown> =>
+ update.properties_to_set_once ?? {}
+
+/**
+ * Rows with the batch statement's per-key semantics. A held call still reads or commits at call
+ * time; only its answer waits, so the test decides the order results reach the store.
+ */
+class FakePersonRepository {
+ readonly rows = new Map<string, InternalPerson>()
+ readonly distinctToUuid = new Map<string, string>()
+ readonly held: Held[] = []
+ /** The newest row version the store has received per person, from a write result or a fetch. */
+ readonly newestDelivered = new Map<string, RowSnapshot>()
+ /** Every value each row has held per key, in commit order, whichever writer committed it. */
+ readonly committed = new Map<string, Map<string, { value: unknown; at: number }[]>>()
+ /** Commit counter, so a value in the history can be placed before or after a merge. */
+ clock = 0
+ /** Per person and key this pod wrote, the row value its newest landed write left, in commit order. */
+ readonly podLanded = new Map<string, Map<string, Landing>>()
+ /** Writes that sent a value this pod had landed on that row before, over another value the row held by then. */
+ readonly replayed: string[] = []
+ /** Every value this pod's writes have landed per row and key, so a second landing of one is a replay. */
+ readonly podLandedValues = new Map<string, Map<string, unknown[]>>()
+ /** Another pod's last write per row and key, which this pod must leave alone unless it wrote that key. */
+ readonly otherPodLast = new Map<string, Map<string, unknown>>()
+ /** Keys this pod's writes have ever carried per row. */
+ readonly podCarried = new Map<string, Set<string>>()
+ /** Every write call as it came in, for reading one seed by hand. */
+ readonly writes: string[] = []
+ /** The driver's current step, stamped on the write log. */
+ step = -1
+ /** Writes that carried nothing and changed no scalar: the store should not have sent them. */
+ readonly idleWrites: string[] = []
+ private seq = 0
+ holdWrites = false
+ holdFetches = false
+ /** How many of the next row reads fail as a transient repository error. */
+ fetchFailures = 0
+ private nextId = 1
+
+ addPerson(uuid: string, distinctIds: string[], properties: Record<string, unknown>, teamId = 1): InternalPerson {
+ const row: InternalPerson = {
+ id: String(this.nextId++),
+ uuid,
+ team_id: teamId,
+ properties: { ...properties },
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ created_at: DateTime.fromISO('2026-01-01T00:00:00Z', { zone: 'utc' }),
+ version: 1,
+ is_identified: false,
+ is_user_id: null,
+ last_seen_at: null,
+ }
+ this.rows.set(uuid, row)
+ this.recordCommit(row)
+ for (const distinctId of distinctIds) {
+ this.distinctToUuid.set(`${teamId}:${distinctId}`, uuid)
+ }
+ return this.snapshot(row)
+ }
+
+ /** Another pod merged source into target: carried keys fill gaps, the ids move, the source row goes. */
+ mergeAway(sourceUuid: string, targetUuid: string): void {
+ const source = this.rows.get(sourceUuid)!
+ const target = this.rows.get(targetUuid)!
+ for (const [key, value] of Object.entries(source.properties)) {
+ if (!Object.hasOwn(target.properties, key)) {
+ this.noteOtherPod(targetUuid, key, value)
+ }
+ }
+ target.properties = { ...source.properties, ...target.properties }
+ target.version += 1
+ this.recordCommit(target)
+ for (const [key, uuid] of this.distinctToUuid) {
+ if (uuid === sourceUuid) {
+ this.distinctToUuid.set(key, targetUuid)
+ }
+ }
+ this.rows.delete(sourceUuid)
+ }
+
+ /** Another pod's per-key write. */
+ otherPodSet(uuid: string, properties: Record<string, unknown>): void {
+ const row = this.rows.get(uuid)!
+ row.properties = { ...row.properties, ...properties }
+ row.version += 1
+ this.recordCommit(row)
+ Object.entries(properties).forEach(([key, value]) => this.noteOtherPod(uuid, key, value))
+ }
+
+ /** Another pod's per-key unset. */
+ otherPodUnset(uuid: string, key: string): void {
+ const row = this.rows.get(uuid)!
+ delete row.properties[key]
+ row.version += 1
+ this.recordCommit(row)
+ this.recordAbsent(uuid, key)
+ this.noteOtherPod(uuid, key, undefined)
+ }
+
+ /** The merge transaction's id move, called on this fake as the transaction. */
+ moveDistinctIds = jest.fn((source: InternalPerson, target: InternalPerson) => {
+ const moved: string[] = []
+ for (const [key, uuid] of this.distinctToUuid) {
+ if (uuid === source.uuid) {
+ this.distinctToUuid.set(key, target.uuid)
+ moved.push(key.slice(key.indexOf(':') + 1))
+ }
+ }
+ return Promise.resolve({ success: true, messages: [], distinctIdsMoved: moved })
+ })
+
+ release(index = 0): void {
+ const [held] = this.held.splice(index, 1)
+ held.deliver()
+ }
+
+ releaseAll(): void {
+ while (this.held.length > 0) {
+ this.release(0)
+ }
+ }
+
+ labels(): string[] {
+ return this.held.map((held) => held.label)
+ }
+
+ async settle(predicate: () => boolean): Promise<void> {
+ for (let i = 0; i < 200 && !predicate(); i++) {
+ await new Promise((resolve) => setImmediate(resolve))
+ }
+ if (!predicate()) {
+ throw new Error(`condition never held; held: ${this.labels().join(', ')}`)
+ }
+ }
+
+ private failing(label: string): Promise<never> | undefined {
+ if (this.fetchFailures === 0) {
+ return undefined
+ }
+ this.fetchFailures--
+ return this.fail(
+ this.holdFetches,
+ label,
+ Object.assign(new Error('persons unavailable'), { isRetriable: true })
+ )
+ }
+
+ fetchPerson = jest.fn((teamId: number, distinctId: string) => {
+ const failure = this.failing(`fetch:${distinctId}`)
+ if (failure) {
+ return failure
+ }
+ const person = this.lookup(teamId, distinctId)
+ this.noteRead(`fetch:${distinctId}`, [person])
+ return this.deliver(this.holdFetches, `fetch:${distinctId}`, person, () => this.observePerson(person))
+ })
+
+ fetchPersonsByDistinctIds = jest.fn((keys: { teamId: number; distinctId: string }[]) => {
+ const failure = this.failing(`prefetch:${keys.map((key) => key.distinctId).join(',')}`)
+ if (failure) {
+ return failure
+ }
+ const persons = keys.flatMap(({ teamId, distinctId }): InternalPersonWithDistinctId[] => {
+ const person = this.lookup(teamId, distinctId)
+ return person ? [{ ...person, distinct_id: distinctId }] : []
+ })
+ this.noteRead(`prefetch:${keys.map((key) => key.distinctId).join(',')}`, persons)
+ return this.deliver(this.holdFetches, `prefetch:${keys.map((key) => key.distinctId).join(',')}`, persons, () =>
+ persons.forEach((person) => this.observePerson(person))
+ )
+ })
+
+ fetchPersonsForUpdateByDistinctIds = jest.fn((teamId: number, distinctIds: string[]) => {
+ const failure = this.failing(`fetchForUpdate:${distinctIds.join(',')}`)
+ if (failure) {
+ return failure
+ }
+ const persons = distinctIds.flatMap((distinctId): InternalPersonWithDistinctId[] => {
+ const person = this.lookup(teamId, distinctId)
+ return person ? [{ ...person, distinct_id: distinctId }] : []
+ })
+ this.noteRead(`fetchForUpdate:${distinctIds.join(',')}`, persons)
+ return this.deliver(this.holdFetches, `fetchForUpdate:${distinctIds.join(',')}`, persons, () =>
+ persons.forEach((person) => this.observePerson(person))
+ )
+ })
+
+ updatePersonsBatch = jest.fn((updates: PersonUpdate[]) => {
+ const results = new Map<
+ string,
+ {
+ success: boolean
+ version?: number
+ kafkaMessage?: object
+ properties?: Record<string, unknown>
+ person?: InternalPerson
+ error?: Error
+ }
+ >()
+ for (const update of updates) {
+ this.writes.push(
+ `write@${this.step} ${update.uuid} (entry ${update.id}) set=${JSON.stringify(update.properties_to_set)} setOnce=${JSON.stringify(setOnceOf(update))} unset=${JSON.stringify(update.properties_to_unset)} identified=${update.is_identified}/${update.original_is_identified} -> ${this.rows.has(update.uuid) ? 'lands' : 'no row'}`
+ )
+ // UNNEST applies one source row per target row, so a repeated uuid changes nothing more.
+ if (results.has(update.uuid)) {
+ continue
+ }
+ const row = this.rows.get(update.uuid)
+ if (!row || row.team_id !== update.team_id) {
+ results.set(update.uuid, { success: false, error: new NoRowsUpdatedError(`no row ${update.uuid}`) })
+ continue
+ }
+ // Master's statement replaces the whole property map and every scalar; the branch's merges per key.
+ const snapshot = SNAPSHOT_SQL || !Object.hasOwn(update, 'properties_to_set_once')
+ const carried = snapshot
+ ? { ...update.properties, ...update.properties_to_set }
+ : { ...setOnceOf(update), ...update.properties_to_set }
+ this.noteReplays(row, snapshot ? carried : this.filling(row, update))
+ const properties = snapshot
+ ? { ...carried }
+ : { ...carried, ...row.properties, ...update.properties_to_set }
+ for (const key of update.properties_to_unset) {
+ delete properties[key]
+ }
+ if (!snapshot && Object.keys(carried).length === 0 && update.properties_to_unset.length === 0) {
+ const identifies = update.is_identified && !row.is_identified
+ const backdates = update.created_at < row.created_at
+ const advances = !!update.last_seen_at && (!row.last_seen_at || update.last_seen_at > row.last_seen_at)
+ if (!identifies && !backdates && !advances) {
+ this.idleWrites.push(`${update.uuid} v${row.version}`)
+ }
+ }
+ row.properties = properties
+ if (snapshot) {
+ row.is_identified = update.is_identified
+ row.created_at = update.created_at
+ row.last_seen_at = update.last_seen_at
+ } else {
+ row.is_identified = row.is_identified || update.is_identified
+ row.created_at = DateTime.min(row.created_at, update.created_at)
+ if (update.last_seen_at && (!row.last_seen_at || update.last_seen_at > row.last_seen_at)) {
+ row.last_seen_at = update.last_seen_at
+ }
+ }
+ row.version += 1
+ this.recordCommit(row)
+ update.properties_to_unset.forEach((key) => this.recordAbsent(update.uuid, key))
+ this.noteLanded(row, [...Object.keys(carried), ...update.properties_to_unset])
+ results.set(update.uuid, {
+ success: true,
+ version: row.version,
+ kafkaMessage: {},
+ properties: { ...row.properties },
+ person: this.snapshot(row),
+ })
+ }
+ return this.deliver(this.holdWrites, `write:${updates.map((update) => update.uuid).join(',')}`, results, () => {
+ for (const [uuid, result] of results) {
+ if (result.success) {
+ this.observe(uuid, { version: result.version!, properties: result.properties! })
+ }
+ }
+ })
+ })
+
+ /** Master's single-row write: the whole snapshot replaces the row. */
+ updatePerson = jest.fn((person: InternalPerson, update: Partial<InternalPerson>) => {
+ const row = this.rows.get(person.uuid)
+ if (!row || row.team_id !== person.team_id) {
+ return this.fail(
+ this.holdWrites,
+ `updatePerson:${person.uuid}`,
+ new NoRowsUpdatedError(`no row ${person.uuid}`)
+ )
+ }
+ this.noteReplays(row, update.properties ?? {})
+ row.properties = { ...(update.properties ?? row.properties) }
+ row.is_identified = update.is_identified ?? row.is_identified
+ row.created_at = update.created_at ?? row.created_at
+ row.last_seen_at = update.last_seen_at ?? row.last_seen_at
+ row.version += 1
+ this.recordCommit(row)
+ this.noteLanded(row, Object.keys(row.properties))
+ const written = this.snapshot(row)
+ return this.deliver(this.holdWrites, `updatePerson:${person.uuid}`, [written, [], false] as const, () =>
+ this.observePerson(written)
+ )
+ })
+
+ /** The version-checked write: the record's whole view replaces the row when the version still matches. */
+ updatePersonAssertVersion = jest.fn((update: PersonUpdate) => {
+ const row = this.rows.get(update.uuid)
+ this.writes.push(
+ `cas ${update.uuid} (entry ${update.id}) v${update.version} vs row v${row?.version ?? '-'} set=${JSON.stringify(update.properties_to_set)} setOnce=${JSON.stringify(setOnceOf(update))} unset=${JSON.stringify(update.properties_to_unset)} -> ${row && row.version === update.version ? 'lands' : 'conflict'}`
+ )
+ if (!row || row.team_id !== update.team_id || row.version !== update.version) {
+ return this.deliver(this.holdWrites, `cas:${update.uuid}`, [undefined, []] as const, () => undefined)
+ }
+ const lanes = { ...setOnceOf(update), ...update.properties_to_set }
+ if (
+ Object.keys(lanes).length === 0 &&
+ update.properties_to_unset.length === 0 &&
+ update.is_identified === row.is_identified &&
+ (update.last_seen_at?.toMillis() ?? null) === (row.last_seen_at?.toMillis() ?? null)
+ ) {
+ this.idleWrites.push(`${update.uuid} v${row.version}`)
+ }
+ this.noteReplays(row, this.filling(row, update))
+ const properties = { ...update.properties }
+ for (const [key, value] of Object.entries(setOnceOf(update))) {
+ if (!Object.hasOwn(properties, key)) {
+ properties[key] = value
+ }
+ }
+ Object.assign(properties, update.properties_to_set)
+ for (const key of update.properties_to_unset) {
+ delete properties[key]
+ }
+ row.properties = properties
+ row.is_identified = update.is_identified
+ row.last_seen_at = update.last_seen_at
+ row.version += 1
+ this.recordCommit(row)
+ update.properties_to_unset.forEach((key) => this.recordAbsent(update.uuid, key))
+ this.noteLanded(row, [...Object.keys(lanes), ...update.properties_to_unset])
+ const written = this.snapshot(row)
+ return this.deliver(this.holdWrites, `cas:${update.uuid}`, [row.version, []] as const, () =>
+ this.observePerson(written)
+ )
+ })
+ handleOversizedPersonProperties = jest.fn()
+ personPropertiesSize = jest.fn().mockResolvedValue(0)
+ fetchPersonDistinctIdMappings = jest.fn().mockResolvedValue([])
+ inTransaction = jest.fn(async (_description: string, body: (tx: unknown) => Promise<unknown>) => body({}))
+
+ /** The merge's statement as the transaction: the merge holds the row locks, so it answers at once. */
+ tx = {
+ updatePersonsBatch: (updates: PersonUpdate[]) => {
+ const held = this.holdWrites
+ this.holdWrites = false
+ try {
+ return this.updatePersonsBatch(updates)
+ } finally {
+ this.holdWrites = held
+ }
+ },
+ } as unknown as PersonRepositoryTransaction
+
+ private lookup(teamId: number, distinctId: string): InternalPerson | undefined {
+ const uuid = this.distinctToUuid.get(`${teamId}:${distinctId}`)
+ const row = uuid === undefined ? undefined : this.rows.get(uuid)
+ return row ? this.snapshot(row) : undefined
+ }
+
+ private snapshot(row: InternalPerson): InternalPerson {
+ return { ...row, properties: { ...row.properties } }
+ }
+
+ /** The values a per-key write changes: its sets, and its set-once values where the row lacks the key. */
+ private filling(row: InternalPerson, update: PersonUpdate): Record<string, unknown> {
+ const fills = Object.fromEntries(
+ Object.entries(setOnceOf(update)).filter(([key]) => !Object.hasOwn(row.properties, key))
+ )
+ return { ...fills, ...update.properties_to_set }
+ }
+
+ /** Exact while the driver never re-sets a value: a value landed on this row before is a replay. */
+ private noteReplays(row: InternalPerson, carried: Record<string, unknown>): void {
+ const seen = this.podLandedValues.get(row.uuid) ?? new Map<string, unknown[]>()
+ this.podLandedValues.set(row.uuid, seen)
+ for (const [key, value] of Object.entries(carried)) {
+ const before = seen.get(key) ?? []
+ const again = before.some((previous) => isEqual(previous, value))
+ before.push(value)
+ seen.set(key, before)
+ if (again && !isEqual(row.properties[key], value)) {
+ this.replayed.push(
+ `${row.uuid}.${key}=${JSON.stringify(value)} over ${JSON.stringify(row.properties[key])}`
+ )
+ }
+ }
+ }
+
+ private recordCommit(row: InternalPerson): void {
+ const at = ++this.clock
+ const history = this.committed.get(row.uuid) ?? new Map<string, { value: unknown; at: number }[]>()
+ for (const [key, value] of Object.entries(row.properties)) {
+ const values = history.get(key) ?? []
+ if (values.length === 0 || !isEqual(values[values.length - 1].value, value)) {
+ values.push({ value, at })
+ }
+ history.set(key, values)
+ }
+ for (const [key, values] of history) {
+ if (!Object.hasOwn(row.properties, key) && values[values.length - 1].value !== undefined) {
+ values.push({ value: undefined, at })
+ }
+ }
+ this.committed.set(row.uuid, history)
+ }
+
+ /** An unset of a key the row never held still counts as the key being absent afterwards. */
+ private recordAbsent(uuid: string, key: string): void {
+ const history = this.committed.get(uuid) ?? new Map<string, { value: unknown; at: number }[]>()
+ const values = history.get(key) ?? []
+ if (values.length === 0 || values[values.length - 1].value !== undefined) {
+ values.push({ value: undefined, at: ++this.clock })
+ }
+ history.set(key, values)
+ this.committed.set(uuid, history)
+ }
+
+ private noteLanded(row: InternalPerson, keys: string[]): void {
+ const landed = this.podLanded.get(row.uuid) ?? new Map<string, Landing>()
+ const carried = this.podCarried.get(row.uuid) ?? new Set<string>()
+ for (const key of keys) {
+ landed.set(key, { value: row.properties[key], seq: ++this.seq, version: row.version })
+ carried.add(key)
+ }
+ this.podLanded.set(row.uuid, landed)
+ this.podCarried.set(row.uuid, carried)
+ }
+
+ private noteOtherPod(uuid: string, key: string, value: unknown): void {
+ const last = this.otherPodLast.get(uuid) ?? new Map<string, unknown>()
+ last.set(key, value)
+ this.otherPodLast.set(uuid, last)
+ }
+
+ private observe(uuid: string, snapshot: RowSnapshot): void {
+ const current = this.newestDelivered.get(uuid)
+ if (!current || snapshot.version > current.version) {
+ this.newestDelivered.set(uuid, { version: snapshot.version, properties: { ...snapshot.properties } })
+ }
+ }
+
+ private observePerson(person: InternalPerson | undefined): void {
+ if (person) {
+ this.observe(person.uuid, { version: person.version, properties: person.properties })
+ }
+ }
+
+ private fail(hold: boolean, label: string, error: Error): Promise<never> {
+ if (!hold) {
+ return Promise.reject(error)
+ }
+ return new Promise((_, reject) => this.held.push({ label, deliver: () => reject(error) }))
+ }
+
+ private deliver<T>(hold: boolean, label: string, value: T, onDeliver: () => void): Promise<T> {
+ const answer = (): void => {
+ this.writes.push(`answer@${this.step} ${label}`)
+ onDeliver()
+ }
+ if (!hold) {
+ answer()
+ return Promise.resolve(value)
+ }
+ return new Promise((resolve) =>
+ this.held.push({
+ label,
+ deliver: () => {
+ answer()
+ resolve(value)
+ },
+ })
+ )
+ }
+
+ private noteRead(label: string, persons: (InternalPerson | undefined)[]): void {
+ const rows = persons.flatMap((person) => (person ? [`${person.uuid} v${person.version}`] : []))
+ this.writes.push(`read@${this.step} ${label} -> ${rows.join(', ') || 'none'}`)
+ }
+}
+
+/**
+ * Drift: keys where the view differs from the newest row the store has received, pending keys
+ * aside. Another pod's value that arrived in a row this pod's own write returned counts, so this
+ * measures the versioned-base design's promise, which the branch does not make.
+ */
+function viewDrift(store: BatchWritingPersonsStore, fake: FakePersonRepository): string[] {
+ const disagreements: string[] = []
+ for (const row of fake.rows.values()) {
+ const entry = store.getCachedPersonForUpdateByPersonId(row.team_id, row.id)
+ const seen = fake.newestDelivered.get(row.uuid)
+ if (!entry || !seen) {
+ continue
+ }
+ const view = toInternalPerson(entry).properties
+ const pending = new Set([
+ ...Object.keys(entry.properties_to_set),
+ ...Object.keys(setOnceOf(entry)),
+ ...entry.properties_to_unset,
+ ])
+ for (const key of new Set([...Object.keys(view), ...Object.keys(seen.properties)])) {
+ if (pending.has(key) || isEqual(view[key], seen.properties[key])) {
+ continue
+ }
+ disagreements.push(
+ `${row.uuid}.${key}: view=${JSON.stringify(view[key])} row@v${seen.version}=${JSON.stringify(seen.properties[key])}`
+ )
+ }
+ }
+ return disagreements
+}
+
+/**
+ * For each key this pod wrote and has nothing pending for, the view shows the value this pod's newest
+ * landed write left in the row, or the value in a newer row the store has received since.
+ */
+function cacheRowDisagreements(store: BatchWritingPersonsStore, fake: FakePersonRepository): string[] {
+ const disagreements: string[] = []
+ for (const row of fake.rows.values()) {
+ const entry = store.getCachedPersonForUpdateByPersonId(row.team_id, row.id)
+ const landed = fake.podLanded.get(row.uuid)
+ if (!entry || !landed) {
+ continue
+ }
+ const view = toInternalPerson(entry).properties
+ const pending = new Set([
+ ...Object.keys(entry.properties_to_set),
+ ...Object.keys(setOnceOf(entry)),
+ ...entry.properties_to_unset,
+ ])
+ const seen = fake.newestDelivered.get(row.uuid)
+ for (const [key, landing] of landed) {
+ const expected = seen && seen.version >= landing.version ? seen.properties[key] : landing.value
+ if (pending.has(key) || isEqual(view[key], expected)) {
+ continue
+ }
+ disagreements.push(
+ `${row.uuid}.${key}: view=${JSON.stringify(view[key])} expected=${JSON.stringify(expected)}`
+ )
+ }
+ }
+ return disagreements
+}
+
+function mulberry32(seed: number): () => number {
+ let state = seed >>> 0
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0
+ let t = state
+ t = Math.imul(t ^ (t >>> 15), t | 1)
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+const setOps = (set: Record<string, unknown>, forced = true, unset: string[] = []): EventOps => ({
+ set,
+ setOnce: {},
+ unset,
+ denied: false,
+ shouldForceUpdate: forced,
+ eventName: '$set',
+})
+
+const RESETS = process.env.MODEL_RESETS === '1'
+const ASSERT = process.env.MODEL_MODE === 'assert'
+/** Ablation of the per-key statement: the fake applies every write as master's full snapshot. */
+const SNAPSHOT_SQL = process.env.MODEL_SQL === 'snapshot'
+
+// The version-checked mode sleeps a millisecond between retries, so its ticks wait out that timer to stay deterministic.
+const tick = (): Promise<void> =>
+ ASSERT ? new Promise((resolve) => setTimeout(resolve, 2)) : new Promise((resolve) => setImmediate(resolve))
+
+/** A key the update filter skips unless the event forces the write or the key is new on the person. */
+const FILTERED_KEY = [...FILTERED_PERSON_UPDATE_PROPERTIES][0]
+
+const outputs = () =>
+ createMockIngestionOutputs<
+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT | PersonMergeEventsOutput
+ >()
+
+type SeedResult = {
+ log: string[]
+ disagreements: string[]
+ leftoverPending: string[]
+ lost: string[]
+ drift: string[]
+ replayed: string[]
+ erased: string[]
+ idle: string[]
+ leaks: string[]
+ dump: string[]
+}
+
+/** A read the store began and never ended keeps the drop record growing for the life of the process. */
+function readsLeftInFlight(store: BatchWritingPersonsStore): string[] {
+ const size = (store as unknown as { personCache: { readsInFlight: Map<number, number> } }).personCache.readsInFlight
+ .size
+ return size > 0 ? [`${size} reads left in flight`] : []
+}
+
+/** Another pod's last write to a key this pod never carried on that row must still stand. */
+function erasedByThisPod(fake: FakePersonRepository): string[] {
+ const erased: string[] = []
+ for (const row of fake.rows.values()) {
+ const carried = fake.podCarried.get(row.uuid) ?? new Set<string>()
+ for (const [key, value] of fake.otherPodLast.get(row.uuid) ?? []) {
+ if (!carried.has(key) && !isEqual(row.properties[key], value)) {
+ erased.push(
+ `${row.uuid}.${key}: row=${JSON.stringify(row.properties[key])} other=${JSON.stringify(value)}`
+ )
+ }
+ }
+ }
+ return erased
+}
+
+/** Rows, their commit history, what this pod landed, and every cache entry, for reading one seed by hand. */
+function dumpState(store: BatchWritingPersonsStore, fake: FakePersonRepository): string[] {
+ const lines: string[] = []
+ for (const row of fake.rows.values()) {
+ lines.push(`row ${row.uuid} id=${row.id} v${row.version} ${JSON.stringify(row.properties)}`)
+ }
+ for (const [uuid, history] of fake.committed) {
+ for (const [key, values] of history) {
+ lines.push(`history ${uuid}.${key}: ${values.map(({ value }) => JSON.stringify(value)).join(' > ')}`)
+ }
+ }
+ for (const [uuid, landed] of fake.podLanded) {
+ for (const [key, { value, seq }] of landed) {
+ lines.push(`landed ${uuid}.${key}=${JSON.stringify(value)} #${seq}`)
+ }
+ }
+ lines.push(...fake.writes)
+ for (const [cacheKey, entry] of store.getUpdateCache()) {
+ if (!entry) {
+ lines.push(`entry ${cacheKey}: null`)
+ continue
+ }
+ lines.push(
+ `entry ${cacheKey} uuid=${entry.uuid} view=${JSON.stringify(toInternalPerson(entry).properties)} set=${JSON.stringify(entry.properties_to_set)} setOnce=${JSON.stringify(setOnceOf(entry))} unset=${JSON.stringify(entry.properties_to_unset)} dirty=${entry.needs_write} identified=${entry.is_identified}/${entry.original_is_identified} v${entry.version}`
+ )
+ }
+ return lines
+}
+
+/**
+ * One seeded interleaving: this pod's events, prefetches and flushes against other pods' writes and
+ * merges, with held answers released in random order. Flushes never overlap, as in the pipeline.
+ */
+async function runSeed(seed: number, steps: number, log: string[]): Promise<SeedResult> {
+ const rand = mulberry32(seed)
+ const pick = <T>(items: T[]): T => items[Math.floor(rand() * items.length)]
+ const fake = new FakePersonRepository()
+ const store = new BatchWritingPersonsStore(fake as unknown as PersonRepository, outputs(), {
+ dbWriteMode: ASSERT ? 'ASSERT_VERSION' : 'NO_ASSERT',
+ optimisticUpdateRetryInterval: 1,
+ })
+ const distinctIds: Record<string, string[]> = { P1: ['a1', 'a2'], P2: ['b1', 'b2'], P3: ['c1', 'c2'] }
+ for (const [uuid, ids] of Object.entries(distinctIds)) {
+ fake.addPerson(uuid, ids, { k1: 'seed' })
+ }
+ const allIds = Object.values(distinctIds).flat()
+ const keys = ['k1', 'k2', FILTERED_KEY]
+ const outstanding: Promise<unknown>[] = []
+ const intents: {
+ distinctId: string
+ uuid: string
+ key: string
+ value: string | undefined
+ window: number
+ optional: boolean
+ carried?: number
+ }[] = []
+ let flushesInFlight = 0
+ let batch = 0
+ for (let step = 0; step < steps; step++) {
+ fake.step = step
+ const op = pick([
+ 'event',
+ 'event',
+ 'event',
+ 'unset',
+ 'otherPod',
+ 'otherUnset',
+ 'mergeAway',
+ 'podMerge',
+ 'prefetch',
+ 'flush',
+ 'release',
+ 'release',
+ 'fetchError',
+ ])
+ if (op === 'fetchError') {
+ // One read fails as a transient repository error, consumed here so it cannot fail a flush's re-target,
+ // which the pipeline would answer by retrying the whole batch.
+ const distinctId = pick(allIds)
+ const heldPrefetch = fake.labels().indexOf(`prefetch:${distinctId}`)
+ if (heldPrefetch >= 0) {
+ fake.release(heldPrefetch)
+ }
+ fake.fetchFailures = 1
+ const person = await store.fetchForUpdate(1, distinctId, batch).catch(() => undefined)
+ fake.fetchFailures = 0
+ log.push(person ? `read ${distinctId} served from cache` : `read failed ${distinctId}`)
+ } else if (op === 'unset') {
+ const distinctId = pick(allIds)
+ const heldPrefetch = fake.labels().indexOf(`prefetch:${distinctId}`)
+ if (heldPrefetch >= 0) {
+ log.push(`release prefetch:${distinctId}`)
+ fake.release(heldPrefetch)
+ }
+ const person = await store.fetchForUpdate(1, distinctId, batch).catch(() => undefined)
+ if (!person) {
+ log.push(`read failed ${distinctId}`)
+ await tick()
+ continue
+ }
+ const key = pick(keys)
+ await store.applyEventOps(person, setOps({}, true, [key]), distinctId, batch)
+ // An unset of a key the view does not hold is a no-op by design.
+ const optional = !Object.hasOwn(person!.properties, key)
+ intents.push({ distinctId, uuid: person!.uuid, key, value: undefined, window: batch, optional })
+ log.push(`unset ${distinctId} ${key}`)
+ } else if (op === 'otherUnset') {
+ const uuid = pick([...fake.rows.keys()])
+ const key = pick(keys)
+ fake.otherPodUnset(uuid, key)
+ log.push(`other ${uuid} unset ${key}`)
+ } else if (op === 'podMerge') {
+ // This pod's merge, as the store sees it: the ids move, the outcome is written to the survivor inside
+ // the transaction with the carried keys as set-once, the source row goes, and after the commit the
+ // survivor's entry takes the row and the source's clears.
+ const alive = [...fake.rows.keys()]
+ const idOf = (uuid: string): string =>
+ [...fake.distinctToUuid].find(([, mapped]) => mapped === uuid)![0].slice(2)
+ // The merge resolves both persons through the store; a stale entry there makes it read a missing
+ // row at delete and retry, so the driver only merges what the store and the rows agree on.
+ const fresh = async (uuid: string): Promise<boolean> => {
+ const distinctId = idOf(uuid)
+ const heldPrefetch = fake.labels().indexOf(`prefetch:${distinctId}`)
+ if (heldPrefetch >= 0) {
+ log.push(`release prefetch:${distinctId}`)
+ fake.release(heldPrefetch)
+ }
+ const person = await store.fetchForUpdate(1, distinctId, batch).catch(() => undefined)
+ return person?.uuid === uuid
+ }
+ if (alive.length > 1 && (await fresh(alive[0])) && (await fresh(alive[1]))) {
+ const sourceUuid = pick(alive.slice(0, 2))
+ const targetUuid = alive.slice(0, 2).find((uuid) => uuid !== sourceUuid)!
+ const source = fake.rows.get(sourceUuid)!
+ const target = fake.rows.get(targetUuid)!
+ const sourceIds = [...fake.distinctToUuid]
+ .filter(([, uuid]) => uuid === sourceUuid)
+ .map(([key]) => key.slice(key.indexOf(':') + 1))
+ const sourcePending = store.pendingChanges(1, source.id)
+ const view = (
+ row: InternalPerson,
+ pending = store.pendingChanges(1, row.id)
+ ): Record<string, unknown> => {
+ const merged = { ...pending?.toSetOnce, ...row.properties, ...pending?.toSet }
+ pending?.toUnset.forEach((key) => delete merged[key])
+ return merged
+ }
+ const targetView = view(target)
+ const sourceView = view(source, sourcePending)
+ const carried = Object.fromEntries(
+ Object.entries(sourceView).filter(([key]) => !Object.hasOwn(targetView, key))
+ )
+ // The survivor's value wins, so the source's unflushed changes to keys it holds are dropped by
+ // design; the rest move to the survivor as gap-fills.
+ for (const intent of intents) {
+ // A gap the survivor's own pending unset left is filled from the source, superseding the unset.
+ if (
+ intent.uuid === targetUuid &&
+ intent.value === undefined &&
+ Object.hasOwn(carried, intent.key)
+ ) {
+ intent.optional = true
+ }
+ if (intent.uuid !== sourceUuid) {
+ continue
+ }
+ intent.uuid = targetUuid
+ if (Object.hasOwn(targetView, intent.key)) {
+ intent.optional = true
+ } else if (Object.hasOwn(carried, intent.key)) {
+ intent.carried = fake.clock
+ }
+ }
+ const targetDistinctId = idOf(targetUuid)
+ // The merge sees the target as this pod does: the row with its pending changes applied.
+ const targetEntry = store.getCachedPersonForUpdateByPersonId(1, target.id)
+ const targetPerson = targetEntry
+ ? toInternalPerson(targetEntry)
+ : { ...target, properties: { ...target.properties } }
+ // A key the survivor's pending unset hides goes as a set, as the merge does, or the unset would win.
+ const targetPending = store.pendingChanges(1, target.id)
+ const hidden = new Set(targetPending?.toUnset ?? [])
+ const outcome: MergePersonUpdate = {
+ properties: Object.fromEntries(Object.entries(carried).filter(([key]) => hidden.has(key))),
+ properties_to_set_once: Object.fromEntries(
+ Object.entries(carried).filter(([key]) => !hidden.has(key))
+ ),
+ is_identified: true,
+ }
+ await store.moveDistinctIds(
+ { ...source },
+ targetPerson,
+ targetDistinctId,
+ undefined,
+ fake as unknown as Parameters<typeof store.moveDistinctIds>[4],
+ batch
+ )
+ const [row, , written] = await store.updatePersonForMerge(
+ targetPerson,
+ outcome,
+ targetDistinctId,
+ fake.tx
+ )
+ log.push(`podMerge ${sourceUuid}->${targetUuid} carried=${Object.keys(carried).join(',') || '-'}`)
+ // A read of a moved id that began before the merge returns the source until the commit, so an event on
+ // that id can reach the source's entry after the merge read its pending changes.
+ const heldRead = sourceIds
+ .map((distinctId) => ({ distinctId, index: fake.labels().indexOf(`prefetch:${distinctId}`) }))
+ .find(({ index }) => index >= 0)
+ if (heldRead) {
+ log.push(`release prefetch:${heldRead.distinctId}`)
+ fake.release(heldRead.index)
+ const person = await store.fetchForUpdate(1, heldRead.distinctId, batch)
+ const key = pick(keys)
+ const value = `m${step}`
+ await store.applyEventOps(person!, setOps({ [key]: value }), heldRead.distinctId, batch)
+ // Recorded on the entry that took it, where a later event on the same id supersedes it.
+ const landedOn = store.pendingChanges(1, source.id)?.toSet[key] === value ? sourceUuid : targetUuid
+ intents.push({
+ distinctId: heldRead.distinctId,
+ uuid: landedOn,
+ key,
+ value,
+ window: batch,
+ optional: false,
+ })
+ log.push(`event ${heldRead.distinctId} ${key}=${value} on ${landedOn} before the release`)
+ }
+ fake.rows.delete(sourceUuid)
+ if (written) {
+ store.takeMergedRow(row, targetDistinctId, outcome, targetPending, batch)
+ }
+ store.releaseMergedSource(1, source.id, sourcePending)
+ }
+ } else if (op === 'event') {
+ const distinctId = pick(allIds)
+ // An update read waits on a held prefetch of the same id, and the driver could not release it while waiting.
+ const heldPrefetch = fake.labels().indexOf(`prefetch:${distinctId}`)
+ if (heldPrefetch >= 0) {
+ log.push(`release prefetch:${distinctId}`)
+ fake.release(heldPrefetch)
+ }
+ const person = await store.fetchForUpdate(1, distinctId, batch).catch(() => undefined)
+ if (!person) {
+ log.push(`read failed ${distinctId}`)
+ await tick()
+ continue
+ }
+ const key = pick(keys)
+ const forced = pick([true, true, false])
+ // With MODEL_RESETS, sometimes a value the key held before, so a change can go back to an earlier
+ // value; the replay oracle is then off, because a re-set and a replay look the same by value.
+ const earlier = intents
+ .filter((intent) => intent.key === key && intent.value !== undefined)
+ .map((intent) => intent.value as string)
+ const value = RESETS && earlier.length > 0 && rand() < 0.25 ? pick(earlier) : `e${step}`
+ await store.applyEventOps(person!, setOps({ [key]: value }, forced), distinctId, batch)
+ // An unforced change to a filtered key writes nothing on its own, so it may never land.
+ const optional = !forced && key === FILTERED_KEY
+ intents.push({ distinctId, uuid: person!.uuid, key, value, window: batch, optional })
+ log.push(`event${forced ? '' : ' (unforced)'} ${distinctId} ${key}=${value}`)
+ } else if (op === 'otherPod') {
+ const uuid = pick([...fake.rows.keys()])
+ const key = pick(keys)
+ fake.otherPodSet(uuid, { [key]: `o${step}` })
+ log.push(`other ${uuid} ${key}=o${step}`)
+ } else if (op === 'mergeAway') {
+ const alive = [...fake.rows.keys()]
+ if (alive.length > 1) {
+ const source = pick(alive)
+ const target = pick(alive.filter((uuid) => uuid !== source))
+ fake.mergeAway(source, target)
+ log.push(`merge ${source}->${target}`)
+ }
+ } else if (op === 'prefetch') {
+ const distinctId = pick(allIds)
+ fake.holdFetches = true
+ outstanding.push(store.prefetchPersons([{ teamId: 1, distinctId, batchId: batch + 1 }]))
+ fake.holdFetches = false
+ log.push(`prefetch ${distinctId}`)
+ } else if (op === 'flush') {
+ if (flushesInFlight === 0) {
+ const flushed = batch
+ batch++
+ flushesInFlight++
+ fake.holdWrites = true
+ // The pipeline releases a batch once its flush completes, which is when eviction runs.
+ outstanding.push(
+ store.flush().finally(() => {
+ flushesInFlight--
+ store.releaseBatch(flushed)
+ })
+ )
+ log.push('flush')
+ }
+ } else if (fake.held.length > 0) {
+ const index = Math.floor(rand() * fake.held.length)
+ log.push(`release ${fake.labels()[index]}`)
+ fake.release(index)
+ }
+ await tick()
+ }
+ fake.holdWrites = false
+ fake.holdFetches = false
+ while (fake.held.length > 0 || flushesInFlight > 0) {
+ fake.releaseAll()
+ await tick()
+ }
+ await Promise.all(outstanding)
+ await store.flush()
+ const disagreements = cacheRowDisagreements(store, fake)
+ const leftoverPending: string[] = []
+ for (const row of fake.rows.values()) {
+ const entry = store.getCachedPersonForUpdateByPersonId(row.team_id, row.id)
+ if (!entry) {
+ continue
+ }
+ const pending = [
+ ...Object.keys(entry.properties_to_set),
+ ...Object.keys(setOnceOf(entry)),
+ ...entry.properties_to_unset,
+ ].filter((key) => key !== FILTERED_KEY)
+ if (pending.length > 0) {
+ leftoverPending.push(`${row.uuid} pending ${pending.join(',')}`)
+ }
+ }
+ // Sets of one key on one person coalesce, so only the last per person and key must have reached
+ // some row at some point, whatever overwrote it later.
+ const histories = [...fake.committed.values()]
+ const lastPerGroup = new Map<string, (typeof intents)[number]>()
+ for (const intent of intents) {
+ lastPerGroup.set(`${intent.uuid}|${intent.key}`, intent)
+ }
+ // A gap-fill that another pod's value beat to the row is a race, not a loss; a gap nobody filled after the
+ // merge is a loss. An unset is also satisfied when the person the id now names simply lacks the key.
+ const heldSince = (uuid: string, key: string, since: number): boolean =>
+ (fake.committed.get(uuid)?.get(key) ?? []).some(({ value, at }) => value !== undefined && at >= since)
+ const rowFor = (uuid: string, distinctId: string): InternalPerson | undefined =>
+ fake.rows.get(uuid) ?? fake.rows.get(fake.distinctToUuid.get(`1:${distinctId}`) ?? '')
+ const lost = [...lastPerGroup.values()]
+ .filter(({ optional }) => !optional)
+ .filter(
+ ({ key, value }) =>
+ !histories.some((history) => history.get(key)?.some((held) => isEqual(held.value, value)))
+ )
+ .filter(({ key, value, uuid, distinctId }) => {
+ const row = rowFor(uuid, distinctId)
+ return !(value === undefined && row !== undefined && !Object.hasOwn(row.properties, key))
+ })
+ .filter(
+ ({ carried, uuid, key, distinctId }) =>
+ carried === undefined || !heldSince(rowFor(uuid, distinctId)?.uuid ?? uuid, key, carried)
+ )
+ .map(({ distinctId, key, value }) => `lost ${key}=${value} (event ${distinctId})`)
+ const drift = viewDrift(store, fake)
+ const erased = erasedByThisPod(fake)
+ const leaks = readsLeftInFlight(store)
+ const dump = dumpState(store, fake)
+ dump.push(
+ ...intents.map(
+ (intent) =>
+ `intent ${intent.distinctId}->${intent.uuid} ${intent.key}=${intent.value} w${intent.window}${intent.optional ? ' optional' : ''}${intent.carried === undefined ? '' : ` carried@${intent.carried}`}`
+ )
+ )
+ await store.shutdown().catch(() => undefined)
+ return {
+ log,
+ disagreements,
+ leftoverPending,
+ lost,
+ drift,
+ replayed: [...fake.replayed],
+ erased,
+ idle: [...fake.idleWrites],
+ leaks,
+ dump,
+ }
+}
+
+describe('BatchWritingPersonsStore against a row model', () => {
+ let fake: FakePersonRepository
+ let store: BatchWritingPersonsStore
+
+ beforeEach(() => {
+ fake = new FakePersonRepository()
+ store = new BatchWritingPersonsStore(
+ fake as unknown as PersonRepository,
+ createMockIngestionOutputs<
+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT | PersonMergeEventsOutput
+ >()
+ )
+ })
+
+ afterEach(async () => {
+ fake.holdWrites = false
+ fake.holdFetches = false
+ fake.releaseAll()
+ try {
+ await store.flush()
+ } catch {
+ // a test may leave a write that cannot land
+ }
+ try {
+ await store.shutdown()
+ } catch {
+ // a test may leave the cache dirty
+ }
+ })
+
+ it("a source's write re-targeted after the survivor's own write leaves the survivor's view on the row", async () => {
+ fake.addPerson('T', ['t'], {})
+ fake.addPerson('S', ['s'], {})
+ const target = await store.fetchForUpdate(1, 't', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(target!, { k: 'B' }, [], {}, 't')
+ const source = await store.fetchForUpdate(1, 's', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'A' }, [], {}, 's')
+ fake.mergeAway('S', 'T')
+
+ await store.flush()
+
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'A' })
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ it('a read through a new distinct id answers the view this pod holds under another', async () => {
+ fake.addPerson('P', ['d1', 'd2'], {})
+ const person = await store.fetchForUpdate(1, 'd1', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(person!, { k: 'A' }, [], {}, 'd1')
+
+ expect((await store.fetchForUpdate(1, 'd2', 0))!.properties).toEqual({ k: 'A' })
+ })
+
+ it('an unforced repeat of a pending value leaves the entry clean', async () => {
+ fake.addPerson('P', ['d1'], { [FILTERED_KEY]: 'old' })
+ const person = await store.fetchForUpdate(1, 'd1', 0)
+ await store.applyEventOps(person!, setOps({ [FILTERED_KEY]: 'x' }, false), 'd1', 0)
+ await store.flush()
+ await store.applyEventOps(
+ (await store.fetchForUpdate(1, 'd1', 0))!,
+ setOps({ [FILTERED_KEY]: 'x' }, false),
+ 'd1',
+ 0
+ )
+
+ expect(store.getCachedPersonForUpdateByPersonId(1, person!.id)?.needs_write).toBe(false)
+ })
+
+ it('a forced $set of a value an unforced event left pending writes it', async () => {
+ fake.addPerson('P', ['d1'], { [FILTERED_KEY]: 'old' })
+ const person = await store.fetchForUpdate(1, 'd1', 0)
+ await store.applyEventOps(person!, setOps({ [FILTERED_KEY]: 'x' }, false), 'd1', 0)
+ await store.applyEventOps((await store.fetchForUpdate(1, 'd1', 0))!, setOps({ [FILTERED_KEY]: 'x' }), 'd1', 0)
+
+ await store.flush()
+
+ expect(fake.rows.get('P')!.properties).toEqual({ [FILTERED_KEY]: 'x' })
+ })
+
+ it("a fetch that read the row before this pod's write landed does not put the old value back", async () => {
+ fake.addPerson('P', ['d1', 'd2'], { k: 'old' })
+ const person = await store.fetchForUpdate(1, 'd1', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(person!, { k: 'new' }, [], {}, 'd1')
+ fake.holdFetches = true
+ const prefetching = store.prefetchPersons([{ teamId: 1, distinctId: 'd2', batchId: 1 }])
+ expect(fake.labels()).toEqual(['prefetch:d2'])
+
+ await store.flush()
+ fake.releaseAll()
+ await prefetching
+
+ expect(fake.rows.get('P')!.properties).toEqual({ k: 'new' })
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ it("a row read that arrives while this pod's write answer is out leaves nothing for the next flush to send", async () => {
+ fake.addPerson('P', ['d1', 'd2'], {})
+ const person = await store.fetchForUpdate(1, 'd1', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(person!, {}, [], { is_identified: true }, 'd1')
+ fake.holdWrites = true
+ const flushing = store.flush()
+ await fake.settle(() => fake.labels().length === 1)
+ // The row already holds the write; a read of it through another id lands before the answer does.
+ await store.prefetchPersons([{ teamId: 1, distinctId: 'd2', batchId: 1 }])
+ fake.releaseAll()
+ await flushing
+ fake.holdWrites = false
+ // A repeat identify changes nothing the row does not already hold.
+ await store.updatePersonWithPropertiesDiffForUpdate(person!, {}, [], { is_identified: true }, 'd1')
+
+ await store.flush()
+
+ expect(fake.updatePersonsBatch).toHaveBeenCalledTimes(1)
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ it('a re-targeted write carries the last_seen_at an event advanced on the live entry after the flush snapshot', async () => {
+ const seen = DateTime.fromISO('2026-01-02T00:00:00Z', { zone: 'utc' })
+ fake.addPerson('T', ['t'], {})
+ fake.addPerson('S', ['s'], {})
+ await store.fetchForUpdate(1, 't', 0)
+ const source = await store.fetchForUpdate(1, 's', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'A' }, [], {}, 's')
+ fake.mergeAway('S', 'T')
+ fake.holdWrites = true
+ const flushing = store.flush()
+ await fake.settle(() => fake.labels().length === 1)
+ await store.updatePersonWithPropertiesDiffForUpdate(source!, {}, [], { last_seen_at: seen }, 's')
+ fake.holdWrites = false
+ fake.releaseAll()
+ await flushing
+
+ expect(fake.rows.get('T')!.last_seen_at?.toISO()).toBe(seen.toISO())
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ /** The merge's survivor write under its transaction, and the survivor's entry taking the row at the commit. */
+ const mergeInto = async (
+ target: InternalPerson,
+ update: MergePersonUpdate,
+ distinctId: string
+ ): Promise<() => void> => {
+ const read = store.pendingChanges(1, target.id)
+ const [row, , written] = await store.updatePersonForMerge(target, update, distinctId, fake.tx)
+ return () => {
+ if (written) {
+ store.takeMergedRow(row, distinctId, update, read, 0)
+ }
+ }
+ }
+
+ it("an event that reaches a source's entry after the merge read its pending changes lands on the survivor", async () => {
+ fake.addPerson('S', ['s1', 's2'], {})
+ fake.addPerson('T', ['t'], {})
+ const source = await store.fetchForUpdate(1, 's1', 0)
+ const target = await store.fetchForUpdate(1, 't', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'early' }, [], {}, 's1')
+ // A read of s2 that began before the merge returns the source until the commit.
+ fake.holdFetches = true
+ const reading = store.fetchForUpdate(1, 's2', 0)
+ fake.holdFetches = false
+ // The merge as person-merge-postgres orders it: move, read the pending changes, write the survivor,
+ // delete, commit, take the row, release.
+ await store.moveDistinctIds(
+ source!,
+ target!,
+ 't',
+ undefined,
+ fake as unknown as Parameters<typeof store.moveDistinctIds>[4],
+ 0
+ )
+ const read = store.pendingChanges(1, source!.id)
+ const committed = await mergeInto(target!, { properties_to_set_once: read!.toSet, is_identified: true }, 't')
+ fake.releaseAll()
+ const stale = await reading
+ expect(stale!.uuid).toBe('S')
+ await store.applyEventOps(stale!, setOps({ j: 'late' }), 's2', 0)
+ fake.rows.delete('S')
+ committed()
+ store.releaseMergedSource(1, source!.id, read)
+ // The leftover waits for the re-target, but the moved id already reads the survivor.
+ expect((await store.fetchForUpdate(1, 's2', 0))!.uuid).toBe('T')
+
+ await store.flush()
+
+ expect(fake.rows.get('T')!.properties).toEqual({ k: 'early', j: 'late' })
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ it('a read of a moved id that answers after the release does not bring the source back', async () => {
+ fake.addPerson('S', ['s1', 's2', 's3'], {})
+ fake.addPerson('T', ['t'], {})
+ const source = await store.fetchForUpdate(1, 's1', 0)
+ const target = await store.fetchForUpdate(1, 't', 0)
+ fake.holdFetches = true
+ const readingS2 = store.fetchForUpdate(1, 's2', 0)
+ const readingS3 = store.fetchForUpdate(1, 's3', 0)
+ fake.holdFetches = false
+ await store.moveDistinctIds(
+ source!,
+ target!,
+ 't',
+ undefined,
+ fake as unknown as Parameters<typeof store.moveDistinctIds>[4],
+ 0
+ )
+ const read = store.pendingChanges(1, source!.id)
+ const committed = await mergeInto(target!, { is_identified: true }, 't')
+ // One read answers inside the window and carries an event onto the source's entry, so the release keeps
+ // it; the other answers after the release.
+ fake.release(0)
+ await store.applyEventOps((await readingS2)!, setOps({ j: 'late' }), 's2', 0)
+ fake.rows.delete('S')
+ committed()
+ store.releaseMergedSource(1, source!.id, read)
+ fake.releaseAll()
+
+ expect((await readingS3)!.uuid).toBe('T')
+ })
+
+ it.each([
+ [
+ 'nobody owns its distinct id',
+ setOps({ j: 'late' }),
+ (fake: FakePersonRepository) => fake.distinctToUuid.delete('1:s1'),
+ ],
+ ['the flush would not write it', setOps({ [FILTERED_KEY]: 'x' }, false), () => undefined],
+ ])('a kept source entry is evicted once %s', async (_case, leftover, arrange) => {
+ // A changed filtered key is a leftover the flush ignores; a new one would write.
+ fake.addPerson('S', ['s1', 's2'], { [FILTERED_KEY]: 'old' })
+ fake.addPerson('T', ['t'], {})
+ const source = await store.fetchForUpdate(1, 's1', 0)
+ const target = await store.fetchForUpdate(1, 't', 0)
+ fake.holdFetches = true
+ const reading = store.fetchForUpdate(1, 's2', 0)
+ fake.holdFetches = false
+ await store.moveDistinctIds(
+ source!,
+ target!,
+ 't',
+ undefined,
+ fake as unknown as Parameters<typeof store.moveDistinctIds>[4],
+ 0
+ )
+ const read = store.pendingChanges(1, source!.id)
+ const committed = await mergeInto(target!, { is_identified: true }, 't')
+ fake.releaseAll()
+ await store.applyEventOps((await reading)!, leftover, 's2', 0)
+ fake.rows.delete('S')
+ committed()
+ store.releaseMergedSource(1, source!.id, read)
+ arrange(fake)
+
+ await store.flush()
+
+ expect(store.getCachedPersonForUpdateByPersonId(1, source!.id)).toBeUndefined()
+ })
+
+ it("a merge's release drops a source's entry once every change it held is carried", async () => {
+ fake.addPerson('S', ['s1'], {})
+ fake.addPerson('T', ['t'], {})
+ const source = await store.fetchForUpdate(1, 's1', 0)
+ const target = await store.fetchForUpdate(1, 't', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'early' }, [], {}, 's1')
+ await store.moveDistinctIds(
+ source!,
+ target!,
+ 't',
+ undefined,
+ fake as unknown as Parameters<typeof store.moveDistinctIds>[4],
+ 0
+ )
+ const read = store.pendingChanges(1, source!.id)
+ const committed = await mergeInto(target!, { properties_to_set_once: read!.toSet, is_identified: true }, 't')
+ fake.rows.delete('S')
+ committed()
+
+ store.releaseMergedSource(1, source!.id, read)
+
+ expect(store.getCachedPersonForUpdateByPersonId(1, source!.id)).toBeUndefined()
+ })
+
+ it("two sources re-targeted onto one survivor whose results return in reverse order leave the survivor's view on the row", async () => {
+ fake.addPerson('T', ['t'], {})
+ fake.addPerson('S1', ['s1'], {})
+ fake.addPerson('S2', ['s2'], {})
+ await store.fetchForUpdate(1, 't', 0)
+ const source1 = await store.fetchForUpdate(1, 's1', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source1!, { k: 'A' }, [], {}, 's1')
+ const source2 = await store.fetchForUpdate(1, 's2', 0)
+ await store.updatePersonWithPropertiesDiffForUpdate(source2!, { k: 'C' }, [], {}, 's2')
+ fake.mergeAway('S1', 'T')
+ fake.mergeAway('S2', 'T')
+ fake.holdWrites = true
+
+ const flushing = store.flush()
+ await fake.settle(() => fake.labels().length === 1)
+ fake.release()
+ // Both sources fail the batch and retry alone; each retry finds no row.
+ await fake.settle(() => fake.labels().length === 2)
+ fake.releaseAll()
+ // Each refresh re-targets onto T and writes; the second call commits last.
+ await fake.settle(() => fake.labels().length === 2)
+ const committedLast = fake.rows.get('T')!.properties.k
+ fake.release(1)
+ fake.release(0)
+ await flushing
+
+ expect(fake.rows.get('T')!.properties.k).toBe(committedLast)
+ expect(cacheRowDisagreements(store, fake)).toEqual([])
+ })
+
+ it('one seed in full, when MODEL_SEED names it', async () => {
+ const seed = Number(process.env.MODEL_SEED ?? 0)
+ if (seed === 0) {
+ return
+ }
+ const log: string[] = []
+ const result = await runSeed(seed, Number(process.env.MODEL_STEPS ?? 24), log)
+ process.stdout.write(
+ [
+ `seed ${seed}`,
+ ...log.map((line, index) => ` ${index}: ${line}`),
+ ...result.dump.map((line) => ` ${line}`),
+ ...result.disagreements.map((line) => ` DISAGREE ${line}`),
+ ...result.lost.map((line) => ` LOST ${line}`),
+ ...result.drift.map((line) => ` DRIFT ${line}`),
+ ...result.replayed.map((line) => ` REPLAY ${line}`),
+ ...result.erased.map((line) => ` ERASED ${line}`),
+ ...result.idle.map((line) => ` IDLE ${line}`),
+ ...result.leaks.map((line) => ` LEAK ${line}`),
+ '',
+ ].join('\n')
+ )
+ })
+
+ it('random interleavings leave every cached view on its row once all writes land', async () => {
+ const failures: string[] = []
+ const byKind = {
+ disagreements: 0,
+ leftoverPending: 0,
+ lost: 0,
+ replayed: 0,
+ erased: 0,
+ idle: 0,
+ leaks: 0,
+ errors: 0,
+ drift: 0,
+ }
+ const seeds = Number(process.env.MODEL_SEEDS ?? 200)
+ const steps = Number(process.env.MODEL_STEPS ?? 24)
+ for (let seed = 1; seed <= seeds; seed++) {
+ const log: string[] = []
+ let problems: string[]
+ try {
+ const result = await Promise.race([
+ runSeed(seed, steps, log),
+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error('hung')), 10_000).unref()),
+ ])
+ problems = [
+ ...result.disagreements,
+ ...result.leftoverPending,
+ ...result.lost,
+ ...(RESETS ? [] : result.replayed),
+ ...result.erased,
+ ...result.idle,
+ ...result.leaks,
+ ]
+ byKind.disagreements += result.disagreements.length > 0 ? 1 : 0
+ byKind.leftoverPending += result.leftoverPending.length > 0 ? 1 : 0
+ byKind.lost += result.lost.length > 0 ? 1 : 0
+ byKind.replayed += result.replayed.length > 0 ? 1 : 0
+ byKind.erased += result.erased.length > 0 ? 1 : 0
+ byKind.idle += result.idle.length > 0 ? 1 : 0
+ byKind.leaks += result.leaks.length > 0 ? 1 : 0
+ byKind.drift += result.drift.length > 0 ? 1 : 0
+ } catch (error) {
+ problems = [String(error)]
+ byKind.errors += 1
+ }
+ if (problems.length > 0) {
+ failures.push(`seed ${seed}: ${problems.join('; ')}\n ${log.join(' | ')}`)
+ }
+ }
+ process.stdout.write(`byKind ${JSON.stringify(byKind)}\n`)
+ process.stdout.write(failures.map((failure) => `FAIL ${failure.split('\n')[0]}`).join('\n') + '\n')
+ expect({ failing: failures.length, byKind, first: failures.slice(0, 5) }).toEqual({
+ failing: 0,
+ byKind: {
+ disagreements: 0,
+ leftoverPending: 0,
+ lost: 0,
+ replayed: RESETS ? expect.any(Number) : 0,
+ erased: 0,
+ idle: 0,
+ leaks: 0,
+ errors: 0,
+ drift: expect.any(Number),
+ },
+ first: [],
+ })
+ }, 300_000)
+})
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 5469b5d3a4f6..8b36c23bc59f 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
@@ -7,7 +7,8 @@ import {
personProfileBatchUpdateOutcomeCounter,
personPropertyKeyUpdateCounter,
} from '~/common/persons/metrics'
-import { fromInternalPerson } from '~/common/persons/person-update-batch'
+import { fromInternalPerson, toInternalPerson } from '~/common/persons/person-update-batch'
+import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
import { DependencyUnavailableError, MessageSizeTooLarge } from '~/common/utils/db/error'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
@@ -138,6 +139,7 @@ describe('BatchWritingPersonStore', () => {
updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
createPerson: jest.fn().mockResolvedValue([person, []]),
updatePerson: jest.fn().mockResolvedValue([person, [], false]),
+ handleOversizedPersonProperties: jest.fn(),
updatePersonAssertVersion: jest.fn().mockResolvedValue([person.version + 1, []]),
updatePersonsBatch: jest.fn().mockImplementation((updates) => {
// Return a map with success for each update
@@ -146,7 +148,8 @@ describe('BatchWritingPersonStore', () => {
results.set(update.uuid, {
success: true,
version: update.version + 1,
- kafkaMessage: undefined,
+ kafkaMessage: {},
+ person: toInternalPerson(update),
})
}
return Promise.resolve(results)
@@ -173,6 +176,8 @@ describe('BatchWritingPersonStore', () => {
claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),
releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),
isPersonLive: jest.fn().mockResolvedValue(true),
+ readMergeRows: jest.fn().mockResolvedValue([]),
+ updatePersonsBatch: jest.fn().mockResolvedValue(new Map()),
addDistinctId: jest.fn().mockResolvedValue([]),
moveDistinctIds: jest.fn().mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
moveDistinctIdsFromPersons: jest
@@ -244,7 +249,7 @@ describe('BatchWritingPersonStore', () => {
const cache = personStore.getUpdateCache()
const cachedUpdate = cache.get(`${teamId}:${person.id}`)!
expect(cachedUpdate.properties).toEqual({ test: 'test' })
- expect(cachedUpdate.properties_to_set).toEqual({ test: 'test' })
+ expect(cachedUpdate.properties_to_set).toEqual({})
expect(cachedUpdate.properties_to_unset).toEqual(['value_to_unset'])
expect(cachedUpdate.needs_write).toBe(true)
@@ -280,7 +285,7 @@ describe('BatchWritingPersonStore', () => {
// Check cache - property should be in properties_to_set and NOT in properties_to_unset
const cache = personStore.getUpdateCache()
const cachedUpdate = cache.get(`${teamId}:${person.id}`)!
- expect(cachedUpdate.properties_to_set).toEqual({ test: 'test', prop_to_toggle: 'new_value' })
+ expect(cachedUpdate.properties_to_set).toEqual({ prop_to_toggle: 'new_value' })
expect(cachedUpdate.properties_to_unset).toEqual([])
await personStore.flush()
@@ -291,7 +296,7 @@ describe('BatchWritingPersonStore', () => {
expect.arrayContaining([
expect.objectContaining({
uuid: person.uuid,
- properties_to_set: { test: 'test', prop_to_toggle: 'new_value' },
+ properties_to_set: { prop_to_toggle: 'new_value' },
properties_to_unset: [],
}),
])
@@ -316,7 +321,7 @@ describe('BatchWritingPersonStore', () => {
// Check cache - property should be in properties_to_unset and NOT in properties_to_set
const cache = personStore.getUpdateCache()
const cachedUpdate = cache.get(`${teamId}:${person.id}`)!
- expect(cachedUpdate.properties_to_set).toEqual({ test: 'test' })
+ expect(cachedUpdate.properties_to_set).toEqual({})
expect(cachedUpdate.properties_to_unset).toEqual(['prop_to_toggle'])
await personStore.flush()
@@ -333,7 +338,7 @@ describe('BatchWritingPersonStore', () => {
)
})
- it('should remove person from caches when deleted', async () => {
+ it('deletes the cached person and leaves the caches for the merge to clear after its commit', async () => {
const mockRepo = createMockRepository()
const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
@@ -359,11 +364,11 @@ describe('BatchWritingPersonStore', () => {
})
)
- // Validate cache
+ // The transaction may still roll back, so the caches stay.
updateCache = personStore.getUpdateCache()
checkCache = personStore.getCheckCache()
- expect(updateCache.get(`${teamId}:${person.id}`)).toBeUndefined()
- expect(checkCache.get(`${teamId}:${person.id}`)).toBeUndefined()
+ expect(updateCache.get(`${teamId}:${person.id}`)).toBeDefined()
+ expect(checkCache.get(`${teamId}:test`)).toBeDefined()
})
it('should flush person updates with default NO_ASSERT mode', async () => {
@@ -395,7 +400,7 @@ describe('BatchWritingPersonStore', () => {
expect(mockRepo.updatePersonAssertVersion).toHaveBeenCalled()
expect(mockRepo.fetchPerson).toHaveBeenCalled() // Called during conflict resolution
- expect(mockRepo.updatePerson).toHaveBeenCalled() // Fallback
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([expect.objectContaining({ uuid: person.uuid })]) // Fallback
})
it('should merge multiple updates for same person', async () => {
@@ -518,7 +523,7 @@ describe('BatchWritingPersonStore', () => {
expect(testMockRepo.updatePersonAssertVersion).toHaveBeenCalledTimes(3)
expect(testMockRepo.fetchPerson).toHaveBeenCalledTimes(2) // Called for each conflict
- expect(testMockRepo.updatePerson).not.toHaveBeenCalled() // Shouldn't fallback if retries succeed
+ expect(testMockRepo.updatePersonsBatch).not.toHaveBeenCalled() // Shouldn't fallback if retries succeed
})
it('should fallback to direct update after max retries', async () => {
@@ -536,7 +541,7 @@ describe('BatchWritingPersonStore', () => {
// Should try optimistic update multiple times based on config (1 initial + 5 retries = 6 total)
expect(mockRepo.updatePersonAssertVersion).toHaveBeenCalledTimes(6) // default max retries
- expect(mockRepo.updatePerson).toHaveBeenCalledTimes(1) // fallback
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1) // fallback
})
it('should merge properties during conflict resolution', async () => {
@@ -565,20 +570,13 @@ describe('BatchWritingPersonStore', () => {
await personStore.flush()
- // Verify the direct update was called with merged properties
- expect(mockRepo.updatePerson).toHaveBeenCalledWith(
+ // The fallback writes only this pod's own sets, on the version it re-read.
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([
expect.objectContaining({
- version: 3, // Should use latest version
+ version: 3,
+ properties_to_set: { new_prop: 'new_value', shared_prop: 'new_value' },
}),
- expect.objectContaining({
- properties: {
- existing_prop: 'existing_value',
- new_prop: 'new_value',
- shared_prop: 'new_value',
- },
- }),
- 'updatePersonNoAssert'
- )
+ ])
})
it('should handle database errors gracefully during flush', async () => {
@@ -630,19 +628,14 @@ describe('BatchWritingPersonStore', () => {
return Promise.resolve(results)
})
- // Mock fallback to also fail
- const originalUpdatePerson = mockRepo.updatePerson
- mockRepo.updatePerson = jest.fn().mockRejectedValue(new Error('Database error'))
-
try {
await expect(personStore.flush()).rejects.toThrow('Database error')
} finally {
mockRepo.updatePersonsBatch = originalUpdatePersonsBatch
- mockRepo.updatePerson = originalUpdatePerson
}
})
- it('should handle clearing cache for different team IDs', async () => {
+ it('should handle clearing cache for different team IDs', () => {
const mockRepo = createMockRepository()
const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
const person2 = { ...person, id: 'person2-id', uuid: 'person2-uuid', team_id: 2 }
@@ -658,14 +651,8 @@ describe('BatchWritingPersonStore', () => {
personStore.setDistinctIdToPersonId(person.team_id, 'test', person.id)
personStore.setDistinctIdToPersonId(person2.team_id, 'test', person2.id)
- // Delete person from team 1
- await personStore.deletePerson(person, 'test')
- expect(mockRepo.deletePerson).toHaveBeenCalledWith(
- expect.objectContaining({
- ...person,
- properties: { test: 'test' },
- })
- )
+ // Clear team 1's person, the way the merge does after its commit
+ personStore.clearAllCachesForPersonId(person.team_id, person.id)
// Only team 1 entries should be removed
expect(updateCache.has(`${person.team_id}:${person.id}`)).toBe(false)
@@ -719,18 +706,20 @@ describe('BatchWritingPersonStore', () => {
})
it('should handle MessageSizeTooLarge errors and capture warning', async () => {
- // Mock batch update to fail for this person, then fallback to fail with MessageSizeTooLarge
- mockRepo.updatePersonsBatch = jest.fn().mockImplementation((updates) => {
- const results = new Map()
- for (const update of updates) {
- results.set(update.uuid, {
- success: false,
- error: new Error('batch failed'),
- })
- }
- return Promise.resolve(results)
- })
- mockRepo.updatePerson = jest.fn().mockRejectedValue(new MessageSizeTooLarge('test', new Error('test')))
+ // Mock batch update to fail for this person, then the fallback write to fail with MessageSizeTooLarge
+ mockRepo.updatePersonsBatch = jest
+ .fn()
+ .mockImplementationOnce((updates) => {
+ const results = new Map()
+ for (const update of updates) {
+ results.set(update.uuid, {
+ success: false,
+ error: new Error('batch failed'),
+ })
+ }
+ return Promise.resolve(results)
+ })
+ .mockRejectedValue(new MessageSizeTooLarge('test', new Error('test')))
// Add a person update to cache
await personStore.updatePersonWithPropertiesDiffForUpdate(person, { new_value: 'new_value' }, [], {}, 'test')
@@ -777,19 +766,20 @@ describe('BatchWritingPersonStore', () => {
maxOptimisticUpdateRetries: 5,
})
- // Mock batch update to fail
- mockRepo.updatePersonsBatch = jest.fn().mockImplementation((updates) => {
- const results = new Map()
- for (const update of updates) {
- results.set(update.uuid, {
- success: false,
- error: new Error('Batch failed'),
- })
- }
- return Promise.resolve(results)
- })
- // Mock fallback to also fail
- mockRepo.updatePerson = jest.fn().mockRejectedValue(new Error('Database error'))
+ // Mock the batch update to fail, then every fallback write to fail too
+ mockRepo.updatePersonsBatch = jest
+ .fn()
+ .mockImplementationOnce((updates) => {
+ const results = new Map()
+ for (const update of updates) {
+ results.set(update.uuid, {
+ success: false,
+ error: new Error('Batch failed'),
+ })
+ }
+ return Promise.resolve(results)
+ })
+ .mockRejectedValue(new Error('Database error'))
await personStore.updatePersonWithPropertiesDiffForUpdate(
person,
@@ -800,8 +790,9 @@ describe('BatchWritingPersonStore', () => {
)
await expect(personStore.flush()).rejects.toThrow('Database error')
- expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)
- expect(mockRepo.updatePerson).toHaveBeenCalled() // Fallback was attempted
+ expect(mockRepo.updatePersonsBatch).toHaveBeenLastCalledWith([
+ expect.objectContaining({ uuid: person.uuid }),
+ ])
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
})
@@ -810,6 +801,7 @@ describe('BatchWritingPersonStore', () => {
dbWriteMode: 'NO_ASSERT',
useBatchUpdates: false,
})
+ const person2 = { ...person, id: '2', uuid: '2' }
await personStore.updatePersonWithPropertiesDiffForUpdate(
person,
@@ -818,14 +810,118 @@ describe('BatchWritingPersonStore', () => {
{},
'test'
)
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
+ person2,
+ { new_value: 'new_value' },
+ [],
+ {},
+ 'test2'
+ )
await personStore.flush()
- // Individual mode should call updatePerson, not updatePersonsBatch
- expect(mockRepo.updatePerson).toHaveBeenCalledTimes(1)
- expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(2)
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([
+ expect.objectContaining({ uuid: person.uuid }),
+ ])
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([
+ expect.objectContaining({ uuid: person2.uuid }),
+ ])
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
})
+ it.each([
+ ['repairs a row already over the limit', true],
+ ['rejects a write that would push the row over the limit', false],
+ ])('an individual write rejected for size %s', async (_case, oversized) => {
+ const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs, {
+ dbWriteMode: 'NO_ASSERT',
+ useBatchUpdates: false,
+ })
+ mockRepo.updatePersonsBatch = jest.fn().mockImplementation((updates: any[]) =>
+ Promise.resolve(
+ new Map(
+ updates.map((u: any) => [
+ u.uuid,
+ {
+ success: false,
+ error: new PersonPropertiesSizeViolationError('too large', u.team_id, u.id),
+ },
+ ])
+ )
+ )
+ )
+ mockRepo.handleOversizedPersonProperties = oversized
+ ? jest.fn().mockResolvedValue([person, [], false])
+ : jest
+ .fn()
+ .mockRejectedValue(new PersonPropertiesSizeViolationError('too large', teamId, person.id))
+
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { new_value: 'v' }, [], {}, 'test')
+ await personStore.flush()
+
+ expect(mockRepo.handleOversizedPersonProperties).toHaveBeenCalledWith(
+ expect.objectContaining({ id: person.id }),
+ expect.objectContaining({ properties: expect.objectContaining({ new_value: 'v' }) })
+ )
+ // The store never writes the whole person itself; only the repository's trim does.
+ expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ const sizeWarnings = jest
+ .mocked(emitIngestionWarning)
+ .mock.calls.filter(([, , warning]) => warning.type === 'person_properties_size_violation')
+ expect(sizeWarnings).toHaveLength(oversized ? 0 : 1)
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)?.properties_to_set).toEqual({
+ new_value: 'v',
+ })
+ })
+
+ it('a batch rejected for size falls back per person, so the others still land', async () => {
+ const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs, {
+ dbWriteMode: 'NO_ASSERT',
+ })
+ const person2 = { ...person, id: '2', uuid: '2' }
+ // The statement fails as a whole, so the repository marks every row; alone, only the oversized
+ // person's write fails.
+ mockRepo.updatePersonsBatch = jest.fn().mockImplementation((updates: any[]) =>
+ Promise.resolve(
+ new Map(
+ updates.map((u: any) => [
+ u.uuid,
+ updates.length > 1 || u.uuid === person.uuid
+ ? {
+ success: false,
+ error: new PersonPropertiesSizeViolationError('too large', u.team_id, u.id),
+ }
+ : {
+ success: true,
+ version: 2,
+ kafkaMessage: {},
+ person: { ...person2, properties: { small: 'y' } },
+ },
+ ])
+ )
+ )
+ )
+ mockRepo.handleOversizedPersonProperties = jest
+ .fn()
+ .mockRejectedValue(new PersonPropertiesSizeViolationError('too large', teamId, person.id))
+
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { big: 'x' }, [], {}, 'test')
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person2, { small: 'y' }, [], {}, 'test2')
+ await personStore.flush()
+
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([
+ expect.objectContaining({ uuid: person2.uuid }),
+ ])
+ expect(mockRepo.handleOversizedPersonProperties).toHaveBeenCalledWith(
+ expect.objectContaining({ id: person.id }),
+ expect.anything()
+ )
+ const sizeWarnings = jest
+ .mocked(emitIngestionWarning)
+ .mock.calls.filter(([, , warning]) => warning.type === 'person_properties_size_violation')
+ expect(sizeWarnings).toHaveLength(1)
+ })
+
it('should retry individual updates on error when useBatchUpdates is false', async () => {
const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs, {
dbWriteMode: 'NO_ASSERT',
@@ -834,14 +930,18 @@ describe('BatchWritingPersonStore', () => {
optimisticUpdateRetryInterval: 1,
})
- // Mock updatePerson to fail twice then succeed
+ // Mock the write to fail twice then succeed
let callCount = 0
- mockRepo.updatePerson = jest.fn().mockImplementation(() => {
+ mockRepo.updatePersonsBatch = jest.fn().mockImplementation((updates) => {
callCount++
if (callCount <= 2) {
return Promise.reject(new Error('Temporary error'))
}
- return Promise.resolve([person, []])
+ return Promise.resolve(
+ new Map(
+ updates.map((update: any) => [update.uuid, { success: true, version: update.version + 1 }])
+ )
+ )
})
await personStore.updatePersonWithPropertiesDiffForUpdate(
@@ -854,8 +954,7 @@ describe('BatchWritingPersonStore', () => {
await personStore.flush()
// Should have retried
- expect(mockRepo.updatePerson).toHaveBeenCalledTimes(3)
- expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(3)
})
})
@@ -877,10 +976,27 @@ describe('BatchWritingPersonStore', () => {
await personStore.flush()
expect(mockRepo.updatePersonAssertVersion).toHaveBeenCalledTimes(1)
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
expect(mockPostgres.transaction).not.toHaveBeenCalled()
})
+ it('a successful version-checked write retires what it carried', async () => {
+ const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs, {
+ dbWriteMode: 'ASSERT_VERSION',
+ })
+ mockRepo.updatePersonAssertVersion = jest.fn().mockResolvedValue([5, []])
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { new_value: 'v' }, [], {}, 'test')
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, {}, ['gone'], {}, 'test')
+
+ await personStore.flush()
+
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toMatchObject({
+ properties: expect.objectContaining({ new_value: 'v' }),
+ properties_to_set: {},
+ properties_to_unset: [],
+ })
+ })
+
it('should retry on version conflicts and eventually fallback', async () => {
const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs, {
dbWriteMode: 'ASSERT_VERSION',
@@ -900,7 +1016,7 @@ describe('BatchWritingPersonStore', () => {
await personStore.flush()
expect(mockRepo.updatePersonAssertVersion).toHaveBeenCalledTimes(3) // 1 initial + 2 retries
- expect(mockRepo.updatePerson).toHaveBeenCalledTimes(1) // fallback
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1) // fallback
})
it('should handle MessageSizeTooLarge in ASSERT_VERSION mode', async () => {
@@ -930,7 +1046,7 @@ describe('BatchWritingPersonStore', () => {
},
pipelineStep: 'person-store',
})
- expect(mockRepo.updatePerson).not.toHaveBeenCalled() // No fallback for MessageSizeTooLarge
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled() // No fallback for MessageSizeTooLarge
})
})
@@ -1041,8 +1157,8 @@ describe('BatchWritingPersonStore', () => {
// Verify fetchPerson was called once during conflict resolution
expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)
- // Since the second retry succeeds, there should be no fallback to updatePerson
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ // Since the second retry succeeds, there should be no fallback write
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
// Verify the second call to updatePersonAssertVersion had the merged properties
expect(mockRepo.updatePersonAssertVersion).toHaveBeenLastCalledWith(
@@ -1112,7 +1228,6 @@ describe('BatchWritingPersonStore', () => {
initial_prop: 'initial_value',
}) // Original properties from database
expect(cacheValue?.properties_to_set).toEqual({
- initial_prop: 'initial_value',
prop_from_distinctId1: 'value1',
prop_from_distinctId2: 'value2',
}) // Properties to set
@@ -1130,7 +1245,6 @@ describe('BatchWritingPersonStore', () => {
expect.objectContaining({
id: sharedPerson.id,
properties_to_set: {
- initial_prop: 'initial_value',
prop_from_distinctId1: 'value1',
prop_from_distinctId2: 'value2',
},
@@ -1139,6 +1253,31 @@ describe('BatchWritingPersonStore', () => {
)
})
+ it('flushes only the sets this batch made, never the snapshot it read', async () => {
+ const mockRepo = createMockRepository()
+ const row = { ...person, properties: { kept: 'row value', shared: 'row value' } }
+ mockRepo.fetchPerson = jest.fn().mockResolvedValue(row)
+ const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
+
+ const viaFirst = await personStore.fetchForUpdate(teamId, 'first-id', 0)
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
+ viaFirst!,
+ { shared: 'batch value' },
+ [],
+ {},
+ 'first-id'
+ )
+ // A second distinct id of the same person reads the row again, with the pre-batch value of `shared`.
+ const viaSecond = await personStore.fetchForUpdate(teamId, 'second-id', 0)
+ await personStore.updatePersonWithPropertiesDiffForUpdate(viaSecond!, { other: 'value' }, [], {}, 'second-id')
+
+ await personStore.flush()
+
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([
+ expect.objectContaining({ properties_to_set: { shared: 'batch value', other: 'value' } }),
+ ])
+ })
+
it('should handle set/unset conflicts when merging updates for same person via different distinct IDs', async () => {
// This test validates that when two distinct IDs point to the same person,
// and one unsets a property while the other sets it, the conflict is resolved correctly
@@ -1182,7 +1321,6 @@ describe('BatchWritingPersonStore', () => {
expect(cacheValue).toBeDefined()
// The set should win - property should be in properties_to_set and NOT in properties_to_unset
expect(cacheValue?.properties_to_set).toEqual({
- existing_prop: 'existing_value',
conflicting_prop: 'new_value',
})
expect(cacheValue?.properties_to_unset).toEqual([])
@@ -1195,7 +1333,6 @@ describe('BatchWritingPersonStore', () => {
expect.arrayContaining([
expect.objectContaining({
properties_to_set: {
- existing_prop: 'existing_value',
conflicting_prop: 'new_value',
},
properties_to_unset: [],
@@ -1246,9 +1383,7 @@ describe('BatchWritingPersonStore', () => {
expect(cacheValue).toBeDefined()
// The unset should win - property should be in properties_to_unset and NOT in properties_to_set
- expect(cacheValue?.properties_to_set).toEqual({
- existing_prop: 'existing_value',
- })
+ expect(cacheValue?.properties_to_set).toEqual({})
expect(cacheValue?.properties_to_unset).toEqual(['conflicting_prop'])
await personStore.flush()
@@ -1258,9 +1393,7 @@ describe('BatchWritingPersonStore', () => {
expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
- properties_to_set: {
- existing_prop: 'existing_value',
- },
+ properties_to_set: {},
properties_to_unset: ['conflicting_prop'],
}),
])
@@ -1368,16 +1501,18 @@ describe('BatchWritingPersonStore', () => {
fromInternalPerson(targetPerson, 'target-distinct')
)
- // Step 2: Update target person with merged properties (simulating updatePersonForMerge)
- const mergeUpdate = {
- properties: {
+ // Step 2: Queue changes on the target person
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
+ targetPerson,
+ {
source_prop: 'source_value',
rich_property: 'rich_value',
merged_from_source: 'merged_value',
},
- is_identified: true,
- }
- await personStore.updatePersonForMerge(targetPerson, mergeUpdate, 'target-distinct')
+ [],
+ { is_identified: true },
+ 'target-distinct'
+ )
// Verify the merge worked - check the final computed result
const cacheAfterMerge = personStore.getCachedPersonForUpdateByDistinctId(teamId, 'target-distinct')
@@ -1389,8 +1524,6 @@ describe('BatchWritingPersonStore', () => {
source_prop: 'source_value',
rich_property: 'rich_value',
merged_from_source: 'merged_value',
- target_prop: 'target_value',
- existing_target_prop: 'existing_target_value',
}) // Properties to set
expect(cacheAfterMerge?.properties_to_unset).toEqual([]) // Properties to unset
expect(cacheAfterMerge?.is_identified).toBe(true)
@@ -1414,8 +1547,6 @@ describe('BatchWritingPersonStore', () => {
source_prop: 'source_value',
rich_property: 'rich_value',
merged_from_source: 'merged_value',
- target_prop: 'target_value',
- existing_target_prop: 'existing_target_value',
})
expect(cacheAfterMove?.properties_to_unset).toEqual([])
expect(cacheAfterMove?.is_identified).toBe(true)
@@ -1468,7 +1599,7 @@ describe('BatchWritingPersonStore', () => {
expect(cacheAfterMove?.distinct_id).toBe('target-distinct')
})
- it('should clear source person cache', async () => {
+ it('leaves the source person cached for the merge to clear after its commit', async () => {
const mockRepo = createMockRepository()
const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
@@ -1493,19 +1624,25 @@ describe('BatchWritingPersonStore', () => {
fromInternalPerson(sourcePerson, 'source-distinct')
)
+ personStore.setCheckCachedPerson(teamId, 'source-distinct', sourcePerson)
+
// Verify source cache exists
expect(personStore.getCachedPersonForUpdateByPersonId(teamId, sourcePerson.id)).toBeDefined()
// Move distinct IDs
const tx = createMockTransaction() as any
+ tx.moveDistinctIds.mockResolvedValue({ success: true, messages: [], distinctIdsMoved: ['source-distinct'] })
await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx, 0)
+ // A moved id no longer checks as the source.
+ expect(personStore.getCheckCache().has(`${teamId}:source-distinct`)).toBe(false)
+
// Verify the repository method was called
expect(tx.moveDistinctIds).toHaveBeenCalledTimes(1)
expect(tx.moveDistinctIds).toHaveBeenCalledWith(sourcePerson, targetPerson, undefined)
- // Verify source cache is cleared
- expect(personStore.getCachedPersonForUpdateByPersonId(teamId, sourcePerson.id)).toBeUndefined()
+ // The transaction may still roll back, so the source's entry and its pending stay.
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, sourcePerson.id)).toBeDefined()
})
it('should handle complex merge scenario with multiple properties', async () => {
@@ -1543,27 +1680,26 @@ describe('BatchWritingPersonStore', () => {
fromInternalPerson(targetPerson, 'target-distinct')
)
- // Step 2: Multiple merge operations
- await personStore.updatePersonForMerge(
+ // Step 2: Multiple queued changes
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
targetPerson,
{
- properties: {
- source_prop: 'source_value',
- shared_prop: 'updated_value', // This should override
- },
- is_identified: true,
+ source_prop: 'source_value',
+ shared_prop: 'updated_value', // This should override
},
+ [],
+ { is_identified: true },
'target-distinct'
)
- await personStore.updatePersonForMerge(
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
targetPerson,
{
- properties: {
- additional_prop: 'additional_value',
- source_only: 'source_only_value',
- },
+ additional_prop: 'additional_value',
+ source_only: 'source_only_value',
},
+ [],
+ {},
'target-distinct'
)
@@ -1588,8 +1724,6 @@ describe('BatchWritingPersonStore', () => {
shared_prop: 'updated_value',
additional_prop: 'additional_value',
source_only: 'source_only_value',
- target_only: 'target_only_value',
- target_prop: 'target_value',
})
expect(finalCache?.properties_to_unset).toEqual([])
})
@@ -1699,7 +1833,7 @@ describe('BatchWritingPersonStore', () => {
// Flush should skip the database write since only filtered properties changed
await personStore.flush()
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
// Verify metrics
@@ -1736,7 +1870,7 @@ describe('BatchWritingPersonStore', () => {
// Flush should skip the database write
await personStore.flush()
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
// Verify metrics
@@ -1934,7 +2068,7 @@ describe('BatchWritingPersonStore', () => {
// Flush should NOT write to database - all properties are filtered
await personStore.flush()
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
// Verify metrics - should be 'ignored' since all properties are filtered
@@ -2242,7 +2376,7 @@ describe('BatchWritingPersonStore', () => {
// Flush should NOT write to database - all events are normal with only filtered properties
await personStore.flush()
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
// Verify metrics - should be 'ignored' since all properties are filtered and no force_update
@@ -2311,7 +2445,6 @@ describe('BatchWritingPersonStore', () => {
// Should NOT write because nothing changed
expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
- expect(mockRepo.updatePerson).not.toHaveBeenCalled()
})
it('should take the newer last_seen_at when multiple updates occur', async () => {
@@ -2928,13 +3061,102 @@ describe('BatchWritingPersonStore', () => {
// No second fetch — persistent cache had the person
expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)
- // Second flush writes the accumulated state — which includes the
- // batch 1 changes still in the cache (`a`, `b`) merged with batch
- // 2 changes (`c` added, `a` unset).
+ // Batch 1's sets landed and left pending; the second flush sends only batch 2's changes.
expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(2)
const secondCallPayload = mockRepo.updatePersonsBatch.mock.calls[1][0][0]
- expect(secondCallPayload.properties_to_set).toEqual(expect.objectContaining({ b: '2', c: '3' }))
- expect(secondCallPayload.properties_to_unset).toContain('a')
+ expect(secondCallPayload.properties_to_set).toEqual({ c: '3' })
+ expect(secondCallPayload.properties_to_unset).toEqual(['a'])
+ expect(secondCallPayload.properties).toEqual(expect.objectContaining({ a: '1', b: '2' }))
+ })
+
+ const heldWrite = (): (() => void) => {
+ let release!: () => void
+ mockRepo.updatePersonsBatch.mockImplementationOnce(
+ (updates: any[]) =>
+ new Promise((resolve) => {
+ release = () =>
+ resolve(
+ new Map(
+ updates.map((u: any) => [
+ u.uuid,
+ {
+ success: true,
+ version: u.version + 1,
+ kafkaMessage: {},
+ person: toInternalPerson(u),
+ },
+ ])
+ )
+ )
+ })
+ )
+ return () => release()
+ }
+
+ it('a landed write retires what it carried and keeps a key changed while it was out', async () => {
+ const personStore = getPersonsStore()
+ await personStore.fetchForUpdate(teamId, 'distinct_id_1', 0)
+ await personStore.updatePersonWithPropertiesDiffForUpdate(
+ person,
+ { a: '1', b: '1' },
+ [],
+ {},
+ 'distinct_id_1'
+ )
+
+ const release = heldWrite()
+ const flushing = personStore.flush()
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { b: '2' }, [], {}, 'distinct_id_1')
+ release()
+ await flushing
+
+ const entry = personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)
+ expect(entry?.properties_to_set).toEqual({ b: '2' })
+ expect(entry?.properties).toEqual(expect.objectContaining({ a: '1' }))
+ })
+
+ it('a write that lands through the fallback retires what it carried', async () => {
+ const personStore = getPersonsStore()
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { a: '1' }, [], {}, 'distinct_id_1')
+ mockRepo.updatePersonsBatch.mockImplementationOnce((updates: any[]) =>
+ Promise.resolve(
+ new Map(updates.map((u: any) => [u.uuid, { success: false, error: new Error('batch failed') }]))
+ )
+ )
+
+ await personStore.flush()
+
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)?.properties_to_set).toEqual({})
+ })
+
+ it('a row read that throws leaves no read in flight', async () => {
+ const personStore = getPersonsStore()
+ mockRepo.fetchPerson.mockRejectedValueOnce(new Error('persons postgres unavailable'))
+ await expect(personStore.fetchForUpdate(teamId, 'distinct_id_1', 0)).rejects.toThrow('unavailable')
+ mockRepo.fetchPersonsForUpdateByDistinctIds.mockRejectedValueOnce(new Error('persons postgres unavailable'))
+ await expect(personStore.fetchPersonsForUpdateByDistinctIds(teamId, ['distinct_id_1'], 0)).rejects.toThrow(
+ 'unavailable'
+ )
+ mockRepo.fetchPerson.mockRejectedValueOnce(new Error('persons postgres unavailable'))
+ await expect(personStore.fetchForChecking(teamId, 'distinct_id_2', 0)).rejects.toThrow('unavailable')
+
+ expect((personStore as any).personCache.readsInFlight.size).toBe(0)
+ })
+
+ it('two entries sharing a uuid in one flush retire nothing', async () => {
+ const personStore = getPersonsStore()
+ const zombie = { ...person, id: '99' }
+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { a: '1' }, [], {}, 'distinct_id_1')
+ await personStore.updatePersonWithPropertiesDiffForUpdate(zombie, { b: '1' }, [], {}, 'distinct_id_2')
+
+ await personStore.flush()
+
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)?.properties_to_set).toEqual({
+ a: '1',
+ })
+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, zombie.id)?.properties_to_set).toEqual({
+ b: '1',
+ })
})
it('two distinct_ids pointing to the same person share a single cache entry across batches', async () => {
@@ -3290,13 +3512,8 @@ describe('BatchWritingPersonStore', () => {
expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-property')).toBeUndefined()
})
- it('tracks merge-update cache writes made under a batch', async () => {
- await personStore.updatePersonForMerge(
- person,
- { properties: { merge_marker: 'tracked' } },
- 'batch-bound-merge',
- 0
- )
+ it('tracks the row a merge installs under a batch', async () => {
+ personStore.takeMergedRow(person, 'batch-bound-merge', { properties: { merge_marker: 'tracked' } }, null, 0)
expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-merge')).toBeDefined()
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 26b1327db34c..1eabad18b2fa 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -1,3 +1,4 @@
+import { isEqual } from 'lodash'
import { DateTime } from 'luxon'
import pLimit from 'p-limit'
@@ -21,7 +22,13 @@ import {
totalPersonUpdateLatencyPerBatchHistogram,
} from '~/common/persons/metrics'
import { isFilteredPersonUpdateProperty } from '~/common/persons/person-property-utils'
-import { PersonUpdate, fromInternalPerson, toInternalPerson } from '~/common/persons/person-update-batch'
+import {
+ MergePersonUpdate,
+ PendingPersonChanges,
+ PersonUpdate,
+ fromInternalPerson,
+ toInternalPerson,
+} from '~/common/persons/person-update-batch'
import {
InternalPersonWithDistinctId,
LifecycleMarkPerson,
@@ -42,9 +49,11 @@ import { PersonBatchWritingDbWriteMode } from '~/ingestion/config'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
+import { BatchWritingPersonsCache, hasLanes, retireCarried, takeRow } from './batch-writing-persons-cache'
import { MergeMappingDebounce } from './merge-mapping-debounce'
import { PersonOutputs } from './person-context'
import { PostgresMergePolicy, PostgresPersonMerge } from './person-merge-postgres'
+import { MergeOutcomeOversizedError } from './person-merge-types'
import {
EventOps,
applyEventPropertyUpdates,
@@ -69,6 +78,7 @@ type MethodName =
| 'claimLifecycleMarks'
| 'releaseLifecycleMarks'
| 'isPersonLive'
+ | 'readMergeRows'
| 'addDistinctId'
| 'moveDistinctIds'
| 'moveDistinctIdsFromPersons'
@@ -77,9 +87,8 @@ type MethodName =
| 'fetchPersonDistinctIds'
| 'updateCohortsAndFeatureFlagsForMerge'
| 'updateCohortsAndFeatureFlagsForMergeBatch'
- | 'addPersonUpdateToBatch'
-type UpdateType = 'updatePersonAssertVersion' | 'updatePersonNoAssert'
+type UpdateType = 'updatePersonAssertVersion' | 'updatePersonNoAssert' | 'updatePersonForMerge'
interface PersonUpdateResult {
success: boolean
@@ -116,6 +125,8 @@ export interface BatchWritingPersonsStoreOptions {
metricEmissionIntervalMs: number
/** Teams on the new-world merge behavior (lifecycle-mark claims plus tombstone deletes); '*' for all. */
mergeTombstoneTeamAllowlist: string
+ /** Teams whose merges lock the person rows and write the survivor in the transaction; others queue it for the flush. */
+ mergeLockedOutcomeTeamAllowlist: string
/** Gate, partition count, and team allowlist ('*' for all) for the cross-partition merge-event producer. */
mergeEventsEnabled: boolean
mergeEventsPartitionCount: number
@@ -135,6 +146,7 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {
updateAllProperties: false,
metricEmissionIntervalMs: 30_000,
mergeTombstoneTeamAllowlist: '',
+ mergeLockedOutcomeTeamAllowlist: '*',
mergeEventsEnabled: false,
mergeEventsPartitionCount: 64,
mergeEventsTeamAllowlist: '',
@@ -143,406 +155,20 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {
mergeNoopMappingEmissionTtlMs: 60 * 60 * 1000,
}
-interface CacheMetrics {
- updateCacheHits: number
- updateCacheMisses: number
- checkCacheHits: number
- checkCacheMisses: number
-}
-
-class BatchWritingPersonsCache {
- private personCheckCache = new Map<string, InternalPerson | null>()
- private distinctIdToPersonId = new Map<string, string>()
- private personUpdateCache = new Map<string, PersonUpdate | null>()
- private batchDistinctKeys = new Map<number, Set<string>>()
- private distinctKeyRefCount = new Map<string, number>()
- private deferredEvictions = new Set<string>()
- private pendingPrefetchesByBatchId = new Map<number, number>()
- private releasedBatchIdsWithPendingPrefetch = new Set<number>()
- private cacheMetrics: CacheMetrics = {
- updateCacheHits: 0,
- updateCacheMisses: 0,
- checkCacheHits: 0,
- checkCacheMisses: 0,
- }
-
- obtainForBatchId(batchId: number): BatchBoundPersonsCache {
- return new BatchBoundPersonsCache(this, batchId)
- }
-
- getCheckCache(): Map<string, InternalPerson | null> {
- return this.personCheckCache
- }
-
- getUpdateCache(): Map<string, PersonUpdate | null> {
- return this.personUpdateCache
- }
-
- getDistinctIdToPersonIdCache(): Map<string, string> {
- return this.distinctIdToPersonId
- }
-
- getBatchDistinctKeys(): Map<number, Set<string>> {
- return this.batchDistinctKeys
- }
-
- getDistinctKeyRefCount(): Map<string, number> {
- return this.distinctKeyRefCount
- }
-
- getCacheMetrics(): CacheMetrics {
- return this.cacheMetrics
- }
-
- resetMetrics(): void {
- this.cacheMetrics = {
- updateCacheHits: 0,
- updateCacheMisses: 0,
- checkCacheHits: 0,
- checkCacheMisses: 0,
- }
- }
-
- getUpdateCacheValues(): IterableIterator<PersonUpdate | null> {
- return this.personUpdateCache.values()
- }
-
- getUpdateCacheEntries(): IterableIterator<[string, PersonUpdate | null]> {
- return this.personUpdateCache.entries()
- }
-
- getFlushStats(): BatchWritingStoreFlushStats {
- const dirtyPersonKeys = new Set<string>()
- for (const [personKey, update] of this.personUpdateCache.entries()) {
- if (update?.needs_write) {
- dirtyPersonKeys.add(personKey)
- }
- }
-
- const referencedBatchIds = new Set<number>()
- for (const [batchId, distinctKeys] of this.batchDistinctKeys.entries()) {
- for (const distinctKey of distinctKeys) {
- const personId = this.distinctIdToPersonId.get(distinctKey)
- if (!personId) {
- continue
- }
-
- const separatorIndex = distinctKey.indexOf(':')
- const teamId = distinctKey.slice(0, separatorIndex)
- if (dirtyPersonKeys.has(`${teamId}:${personId}`)) {
- referencedBatchIds.add(batchId)
- break
- }
- }
- }
-
- return {
- dirtyEntryCount: dirtyPersonKeys.size,
- referencedBatchCount: referencedBatchIds.size,
- cacheEntryCount: this.personUpdateCache.size,
- }
- }
-
- getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {
- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
- const result = this.personCheckCache.get(cacheKey)
- if (result !== undefined) {
- this.cacheMetrics.checkCacheHits++
- return result === null
- ? null
- : {
- ...result,
- properties: { ...result.properties },
- created_at: result.created_at,
- }
- }
-
- this.cacheMetrics.checkCacheMisses++
- return result
- }
-
- getCachedPersonForUpdateByPersonId(teamId: number, personId: string | undefined): PersonUpdate | null | undefined {
- if (personId === undefined) {
- this.cacheMetrics.updateCacheMisses++
- return undefined
- }
-
- const result = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, personId))
- if (result !== undefined) {
- this.cacheMetrics.updateCacheHits++
- if (result === null) {
- return null
- }
-
- return {
- ...result,
- properties: { ...result.properties },
- properties_to_set: { ...result.properties_to_set },
- properties_to_unset: [...result.properties_to_unset],
- }
- }
-
- this.cacheMetrics.updateCacheMisses++
- return undefined
- }
-
- getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {
- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
- const personId = this.distinctIdToPersonId.get(cacheKey)
-
- return this.getCachedPersonForUpdateByPersonId(teamId, personId)
- }
-
- setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {
- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
-
- if (person === null) {
- const existingPersonId = this.distinctIdToPersonId.get(cacheKey)
- this.distinctIdToPersonId.delete(cacheKey)
- if (existingPersonId) {
- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, existingPersonId), null)
- }
- return
- }
-
- this.distinctIdToPersonId.set(cacheKey, person.id)
-
- const existingPersonUpdate = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, person.id))
-
- if (existingPersonUpdate) {
- const mergedPersonUpdate = this.mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate, person)
- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), mergedPersonUpdate)
- } else {
- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), person)
- }
- }
-
- setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {
- this.personCheckCache.set(this.getDistinctCacheKey(teamId, distinctId), person)
- }
-
- setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {
- this.distinctIdToPersonId.set(this.getDistinctCacheKey(teamId, distinctId), personId)
- }
-
- clearPersonCacheForPersonId(teamId: number, personId: string): void {
- this.personUpdateCache.delete(this.getPersonIdCacheKey(teamId, personId))
- }
-
- clearAllCachesForPersonId(teamId: number, personId: string): void {
- this.clearPersonCacheForPersonId(teamId, personId)
-
- const distinctIdsToRemove: string[] = []
- for (const [distinctCacheKey, mappedPersonId] of this.distinctIdToPersonId.entries()) {
- if (mappedPersonId === personId && distinctCacheKey.startsWith(`${teamId}:`)) {
- distinctIdsToRemove.push(distinctCacheKey)
- }
- }
-
- for (const distinctCacheKey of distinctIdsToRemove) {
- this.distinctIdToPersonId.delete(distinctCacheKey)
- this.personCheckCache.delete(distinctCacheKey)
- }
- }
-
- removeDistinctIdFromCache(teamId: number, distinctId: string): void {
- this.distinctIdToPersonId.delete(this.getDistinctCacheKey(teamId, distinctId))
- }
-
- clearAllCachesForDistinctId(teamId: number, distinctId: string): void {
- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
- const personId = this.distinctIdToPersonId.get(cacheKey)
-
- this.distinctIdToPersonId.delete(cacheKey)
-
- if (personId) {
- this.clearPersonCacheForPersonId(teamId, personId)
- }
-
- this.personCheckCache.delete(cacheKey)
- }
-
- releaseBatchId(batchId: number): void {
- const keys = this.batchDistinctKeys.get(batchId)
- if (this.pendingPrefetchesByBatchId.has(batchId)) {
- this.releasedBatchIdsWithPendingPrefetch.add(batchId)
- }
- if (!keys) {
- return
- }
-
- for (const distinctKey of keys) {
- const refCount = (this.distinctKeyRefCount.get(distinctKey) ?? 1) - 1
- if (refCount <= 0) {
- this.distinctKeyRefCount.delete(distinctKey)
- this.evictDistinctKey(distinctKey)
- } else {
- this.distinctKeyRefCount.set(distinctKey, refCount)
- }
- }
-
- this.batchDistinctKeys.delete(batchId)
- }
-
- trackPendingPrefetch(batchIds: Set<number>): void {
- for (const batchId of batchIds) {
- this.pendingPrefetchesByBatchId.set(batchId, (this.pendingPrefetchesByBatchId.get(batchId) ?? 0) + 1)
- }
- }
-
- finishPendingPrefetch(batchIds: Set<number>): void {
- for (const batchId of batchIds) {
- const pendingCount = (this.pendingPrefetchesByBatchId.get(batchId) ?? 1) - 1
- if (pendingCount <= 0) {
- this.pendingPrefetchesByBatchId.delete(batchId)
- this.releasedBatchIdsWithPendingPrefetch.delete(batchId)
- } else {
- this.pendingPrefetchesByBatchId.set(batchId, pendingCount)
- }
- }
- }
-
- isBatchReleasedWithPendingPrefetch(batchId: number): boolean {
- return this.releasedBatchIdsWithPendingPrefetch.has(batchId)
- }
-
- processDeferredEvictions(): void {
- for (const distinctKey of this.deferredEvictions) {
- const colonIdx = distinctKey.indexOf(':')
- const teamId = Number(distinctKey.slice(0, colonIdx))
- const personId = this.distinctIdToPersonId.get(distinctKey)
- if (personId === undefined) {
- this.deferredEvictions.delete(distinctKey)
- continue
- }
- const personIdKey = this.getPersonIdCacheKey(teamId, personId)
- const update = this.personUpdateCache.get(personIdKey)
- if (!update || !update.needs_write) {
- this.personUpdateCache.delete(personIdKey)
- this.distinctIdToPersonId.delete(distinctKey)
- this.deferredEvictions.delete(distinctKey)
- }
- }
- }
-
- trackBatchEntry(batchId: number, teamId: number, distinctId: string): void {
- const distinctKey = this.getDistinctCacheKey(teamId, distinctId)
- let keys = this.batchDistinctKeys.get(batchId)
- if (!keys) {
- keys = new Set()
- this.batchDistinctKeys.set(batchId, keys)
- }
- if (!keys.has(distinctKey)) {
- keys.add(distinctKey)
- this.distinctKeyRefCount.set(distinctKey, (this.distinctKeyRefCount.get(distinctKey) ?? 0) + 1)
- }
- }
-
- private evictDistinctKey(distinctKey: string): void {
- const colonIdx = distinctKey.indexOf(':')
- const teamId = Number(distinctKey.slice(0, colonIdx))
- const personId = this.distinctIdToPersonId.get(distinctKey)
-
- if (personId !== undefined) {
- const personIdKey = this.getPersonIdCacheKey(teamId, personId)
- const update = this.personUpdateCache.get(personIdKey)
- if (!update || !update.needs_write) {
- this.personUpdateCache.delete(personIdKey)
- this.distinctIdToPersonId.delete(distinctKey)
- } else {
- this.deferredEvictions.add(distinctKey)
- }
- }
-
- this.personCheckCache.delete(distinctKey)
- }
-
- private mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate: PersonUpdate, person: PersonUpdate): PersonUpdate {
- const mergedPersonUpdate: PersonUpdate = {
- ...existingPersonUpdate,
- properties: {
- ...existingPersonUpdate.properties,
- ...person.properties,
- },
- is_identified: existingPersonUpdate.is_identified || person.is_identified,
- }
-
- mergedPersonUpdate.properties_to_set = {
- ...existingPersonUpdate.properties_to_set,
- ...person.properties,
- ...person.properties_to_set,
- }
- for (const key of person.properties_to_unset) {
- delete mergedPersonUpdate.properties_to_set[key]
- }
-
- mergedPersonUpdate.properties_to_unset = [
- ...new Set([...existingPersonUpdate.properties_to_unset, ...person.properties_to_unset]),
- ]
- const keysToSet = new Set(Object.keys(person.properties_to_set))
- mergedPersonUpdate.properties_to_unset = mergedPersonUpdate.properties_to_unset.filter(
- (key) => !keysToSet.has(key)
- )
-
- mergedPersonUpdate.created_at = DateTime.min(existingPersonUpdate.created_at, person.created_at)
- mergedPersonUpdate.needs_write = existingPersonUpdate.needs_write || person.needs_write
- mergedPersonUpdate.force_update = existingPersonUpdate.force_update || person.force_update
-
- if (person.last_seen_at) {
- if (!mergedPersonUpdate.last_seen_at || person.last_seen_at > mergedPersonUpdate.last_seen_at) {
- mergedPersonUpdate.last_seen_at = person.last_seen_at
- }
- }
-
- return mergedPersonUpdate
- }
-
- private getDistinctCacheKey(teamId: number, distinctId: string): string {
- return `${teamId}:${distinctId}`
- }
-
- private getPersonIdCacheKey(teamId: number, personId: string): string {
- return `${teamId}:${personId}`
- }
-}
-
-class BatchBoundPersonsCache {
- constructor(
- private readonly cache: BatchWritingPersonsCache,
- private readonly batchId: number
- ) {}
-
- getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- return this.cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)
- }
-
- getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- return this.cache.getCheckCachedPerson(teamId, distinctId)
- }
-
- setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- this.cache.setCachedPersonForUpdate(teamId, distinctId, person)
- }
-
- setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- this.cache.setCheckCachedPerson(teamId, distinctId, person)
- }
-
- setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- this.cache.setDistinctIdToPersonId(teamId, distinctId, personId)
- }
-}
-
/**
* Writes persons to the database in batches, accumulating all changes for the
* same person across events and flushing them on `flush()` calls. The cache
* persists across batches under concurrentBatches > 1.
*
+ * **Cache model** (the cache itself is in `batch-writing-persons-cache.ts`):
+ * - One entry per person per pod: a base row plus this pod's pending set, set-once and unset lanes. A read
+ * answers the base with the lanes applied.
+ * - The base moves only to a row with a strictly newer version.
+ * - A pending change retires only when it equals what a committed write carried; a change made since stays.
+ * - An entry with unwritten changes is detached or deferred, never evicted; it goes once a flush leaves it clean.
+ * - A read that began before an entry was dropped does not reinstall it.
+ * - On a locked-outcome team, nothing from a merge reaches the cache before the merge commits.
+ *
* **Lifecycle:** construction starts a metric-emission timer. Callers MUST
* invoke `shutdown()` on graceful exit to stop the timer and flush any
* remaining dirty entries.
@@ -572,6 +198,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
this.mergePolicy = {
updateAllProperties: this.options.updateAllProperties,
isTombstoneTeam: buildIntegerMatcher(this.options.mergeTombstoneTeamAllowlist, true),
+ isLockedOutcomeTeam: buildIntegerMatcher(this.options.mergeLockedOutcomeTeamAllowlist, true),
mergeEvents: {
enabled: this.options.mergeEventsEnabled,
partitionCount: this.options.mergeEventsPartitionCount,
@@ -627,6 +254,11 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return 'changed'
}
+ // The store cannot tell whether the row already holds a carried key, so a pending set-once always writes.
+ if (Object.keys(update.properties_to_set_once).length > 0) {
+ return 'changed'
+ }
+
const hasPropertyChanges =
Object.keys(update.properties_to_set).length > 0 || update.properties_to_unset.length > 0
@@ -708,15 +340,26 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
if (outcome === 'changed') {
// Track which property keys caused person updates
const metricsKeys = new Set<string>()
- Object.keys(update.properties_to_set).forEach((propertyKey) => {
- metricsKeys.add(getMetricKey(propertyKey))
- })
+ Object.keys({ ...update.properties_to_set, ...update.properties_to_set_once }).forEach(
+ (propertyKey) => {
+ metricsKeys.add(getMetricKey(propertyKey))
+ }
+ )
update.properties_to_unset.forEach((propertyKey) => {
metricsKeys.add(getMetricKey(propertyKey))
})
metricsKeys.forEach((propertyKey) => personPropertyKeyUpdateCounter.labels({ key: propertyKey }).inc())
- updateEntries.push([key, update])
+ // A copy, because the retire edits the live entry in place and compares it with what this write carried.
+ updateEntries.push([
+ key,
+ {
+ ...update,
+ properties_to_set: { ...update.properties_to_set },
+ properties_to_set_once: { ...update.properties_to_set_once },
+ properties_to_unset: [...update.properties_to_unset],
+ },
+ ])
}
// Clear needs_write for every dirty entry we considered, including
@@ -785,6 +428,46 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return this.personCache.getFlushStats()
}
+ /**
+ * An answer newer than the base replaces it with the row it returned; either way the pending change for
+ * each key the write carried retires, unless the entry holds a newer pending change for that key. A
+ * re-targeted write lands on another person's entry this way too.
+ */
+ private retireLandedChanges(record: PersonUpdate, landed: InternalPerson, version: number): void {
+ const entry = this.personCache.getLiveUpdate(record.team_id, record.id)
+ if (!entry) {
+ return
+ }
+ // Two re-targeted writes to one row can answer out of commit order, and a row read can arrive between a
+ // write and its answer. An answer older than the base retires what it carried but leaves the base.
+ if (version > entry.version) {
+ takeRow(entry, landed, version)
+ }
+ retireCarried(entry, record)
+ }
+
+ /**
+ * Runs a row read and names the returned persons whose entries were dropped since it began, so their rows
+ * are not installed; the read ends whatever the repository does.
+ */
+ private async readRows<T>(
+ query: () => Promise<T>,
+ persons: (result: T) => InternalPerson[]
+ ): Promise<{ result: T; dropped: Set<string> }> {
+ const read = this.personCache.beginRead()
+ try {
+ const result = await query()
+ const dropped = new Set(
+ persons(result)
+ .filter((person) => this.personCache.droppedSince(person.team_id, person.id, read))
+ .map((person) => person.id)
+ )
+ return { result, dropped }
+ } finally {
+ this.personCache.endRead(read)
+ }
+ }
+
/**
* Flush all person updates using a single batch query (NO_ASSERT mode).
* Falls back to individual updates for any persons that fail in the batch.
@@ -804,10 +487,19 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
const allKafkaMessages: FlushResult[] = []
const failedUpdates: PersonUpdate[] = []
+ // With a uuid carried by two entries, the returned row cannot say which entry's write it holds.
+ const uuidCounts = new Map<string, number>()
+ for (const update of updates) {
+ uuidCounts.set(update.uuid, (uuidCounts.get(update.uuid) ?? 0) + 1)
+ }
+
// Process batch results
for (const update of updates) {
const result = batchResults.get(update.uuid)
if (result?.success && result.kafkaMessage) {
+ if (uuidCounts.get(update.uuid) === 1 && result.person && result.version !== undefined) {
+ this.retireLandedChanges(update, result.person, result.version)
+ }
allKafkaMessages.push({
messages: [result.kafkaMessage],
teamId: update.team_id,
@@ -820,28 +512,15 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
outcome: 'success',
})
} else {
- // Handle specific error types
+ // One oversized row fails the statement for every row, so the repository marks them all. Each
+ // person retries alone, where only the oversized one is repaired or rejected and warned.
if (result?.error instanceof PersonPropertiesSizeViolationError) {
- await emitIngestionWarning(this.ingestionWarningsOutputs, update.team_id, {
- type: 'person_properties_size_violation',
- details: {
- personId: update.uuid,
- distinctId: update.distinct_id,
- teamId: update.team_id,
- message: 'Person properties exceeds size limit and was rejected',
- },
- pipelineStep: 'person-store',
- })
personWriteMethodAttemptCounter.inc({
db_write_mode: this.options.dbWriteMode,
method: 'batch',
outcome: 'properties_size_violation',
})
- // Don't retry size violations - they will never succeed
- continue
}
-
- // Queue for individual retry
failedUpdates.push(update)
}
}
@@ -1049,21 +728,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
}
if (error instanceof PersonPropertiesSizeViolationError) {
- await emitIngestionWarning(this.ingestionWarningsOutputs, update.team_id, {
- type: 'person_properties_size_violation',
- details: {
- personId: update.uuid,
- distinctId: update.distinct_id,
- teamId: update.team_id,
- message: 'Person properties exceeds size limit and was rejected',
- },
- pipelineStep: 'person-store',
- })
- personWriteMethodAttemptCounter.inc({
- db_write_mode: this.options.dbWriteMode,
- method: this.options.dbWriteMode,
- outcome: 'properties_size_violation',
- })
+ await this.rejectOversizedWrite(update, this.options.dbWriteMode)
return []
}
@@ -1134,12 +799,18 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
try {
this.incrementDatabaseOperation('fetchForChecking', distinctId)
const start = performance.now()
- const person = await this.personRepository.fetchPerson(teamId, distinctId, {
- useReadReplica: true,
- callerTag: 'ingestion/person-resolution',
- })
+ const { result: person, dropped } = await this.readRows(
+ () =>
+ this.personRepository.fetchPerson(teamId, distinctId, {
+ useReadReplica: true,
+ callerTag: 'ingestion/person-resolution',
+ }),
+ (found) => (found ? [found] : [])
+ )
observeLatencyByVersion(person, start, 'fetchForChecking')
- cache.setCheckCachedPerson(teamId, distinctId, person ?? null)
+ if (dropped.size === 0) {
+ cache.setCheckCachedPerson(teamId, distinctId, person ?? null)
+ }
return person ?? null
} finally {
this.fetchPromisesForChecking.delete(cacheKey)
@@ -1220,6 +891,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
// Create a shared promise for the batch fetch that populates caches when complete
// Use primary (useReadReplica=false) to ensure fresh data for updates
+ const read = this.personCache.beginRead()
const batchFetchPromise = this.personRepository
.fetchPersonsByDistinctIds(
uncachedEntries.map(({ teamId, distinctId }) => ({ teamId, distinctId })),
@@ -1243,6 +915,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
const cache = this.personCache.obtainForBatchId(batchId)
const person = personsByKey.get(cacheKey)
+ if (person && this.personCache.droppedSince(teamId, person.id, read)) {
+ continue
+ }
if (person) {
cache.setCheckCachedPerson(teamId, distinctId, person)
const personUpdate = fromInternalPerson(person, distinctId)
@@ -1255,6 +930,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return personsByKey
})
.finally(() => {
+ this.personCache.endRead(read)
// Clean up the promises after completion
for (const { cacheKey } of uncachedEntries) {
this.fetchPromisesForChecking.delete(cacheKey)
@@ -1328,15 +1004,29 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
try {
this.incrementDatabaseOperation('fetchForUpdate', distinctId)
const start = performance.now()
- const person = await this.personRepository.fetchPerson(teamId, distinctId, {
- useReadReplica: false,
- callerTag: 'ingestion/person-update-conflict',
- })
+ let person: InternalPerson | undefined
+ // A person dropped while the read was out may have changed, so it is read once more.
+ for (let attempt = 0; ; attempt++) {
+ const { result, dropped } = await this.readRows(
+ () =>
+ this.personRepository.fetchPerson(teamId, distinctId, {
+ useReadReplica: false,
+ callerTag: 'ingestion/person-update-conflict',
+ }),
+ (found) => (found ? [found] : [])
+ )
+ person = result
+ if (dropped.size === 0 || attempt > 0) {
+ break
+ }
+ }
observeLatencyByVersion(person, start, 'fetchForUpdate')
if (person !== undefined) {
const personUpdate = fromInternalPerson(person, distinctId)
cache.setCachedPersonForUpdate(teamId, distinctId, personUpdate)
- return person
+ // The entry may already hold this pod's changes, reached through another id.
+ const live = this.personCache.getLiveUpdate(teamId, person.id)
+ return live ? toInternalPerson(live) : person
} else {
// Before caching null, check if another async operation populated
// the cache while we were awaiting the DB query. This can happen when:
@@ -1366,29 +1056,119 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return fetchPromise
}
- updatePersonForMerge(
+ /**
+ * Writes the outcome under the merge's transaction, so it commits with the sources' deletion; the cache takes
+ * the row through takeMergedRow after the commit. The flag says whether the outcome is on the row: one the
+ * view already shows is not written. An oversized one throws, because its statement aborted the transaction.
+ */
+ async updatePersonForMerge(
person: InternalPerson,
- update: Partial<InternalPerson>,
+ update: MergePersonUpdate,
distinctId: string,
- batchId: number,
- _tx?: PersonRepositoryTransaction
- ): Promise<[InternalPerson, PersonMessage[], boolean]>
- updatePersonForMerge(
+ tx: PersonRepositoryTransaction
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ this.incrementCount('updatePersonForMerge', distinctId)
+ const record = this.mergeUpdateIntoPersonUpdate(fromInternalPerson(person, distinctId), update, true)
+ if (this.getPersonUpdateOutcome(record) !== 'changed') {
+ return [person, [], false]
+ }
+ this.incrementDatabaseOperation('updatePersonForMerge', distinctId)
+ personWriteMethodAttemptCounter.inc({
+ db_write_mode: this.options.dbWriteMode,
+ method: 'merge',
+ outcome: 'attempt',
+ })
+ const start = performance.now()
+ const result = (await tx.updatePersonsBatch([record])).get(record.uuid)
+ this.recordUpdateLatency('updatePersonForMerge', (performance.now() - start) / 1000, distinctId)
+ if (result?.error instanceof PersonPropertiesSizeViolationError) {
+ throw new MergeOutcomeOversizedError(`merge outcome for person ${record.uuid} exceeds the size limit`)
+ }
+ if (!result?.success || !result.person || !result.kafkaMessage) {
+ throw result?.error ?? new NoRowsUpdatedError(`Person with uuid="${record.uuid}" was not updated`)
+ }
+ personWriteMethodAttemptCounter.inc({
+ db_write_mode: this.options.dbWriteMode,
+ method: 'merge',
+ outcome: 'success',
+ })
+ return [result.person, [result.kafkaMessage], true]
+ }
+
+ /**
+ * Drops a merge outcome over the size limit with a warning, as the flush drops an oversized write. The
+ * warning's produce is not awaited, so it does not hold the merge's row locks.
+ */
+ rejectMergeOutcome(
person: InternalPerson,
- update: Partial<InternalPerson>,
- distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<[InternalPerson, PersonMessage[], boolean]>
- updatePersonForMerge(
+ update: MergePersonUpdate,
+ distinctId: string
+ ): [InternalPerson, PersonMessage[], boolean] {
+ const record = this.mergeUpdateIntoPersonUpdate(fromInternalPerson(person, distinctId), update, true)
+ if (this.getPersonUpdateOutcome(record) === 'changed') {
+ void this.rejectOversizedWrite(record, 'merge').catch((error) =>
+ logger.warn('oversized merge survivor warning failed', { error: String(error) })
+ )
+ }
+ return [person, [], false]
+ }
+
+ /** Queues the outcome on the survivor's entry for the next flush; a rollback leaves it queued. Returns the pod's view. */
+ deferMergeOutcome(
person: InternalPerson,
- update: Partial<InternalPerson>,
+ update: MergePersonUpdate,
distinctId: string,
- batchIdOrTx?: number | PersonRepositoryTransaction,
- _tx?: PersonRepositoryTransaction
- ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ batchId: number
+ ): InternalPerson {
this.incrementCount('updatePersonForMerge', distinctId)
- const batchId = typeof batchIdOrTx === 'number' ? batchIdOrTx : 0
- return Promise.resolve(this.addPersonUpdateToBatch(person, update, distinctId, batchId))
+ const cache = this.personCache.obtainForBatchId(batchId)
+ const existingUpdate = cache.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)
+ const personUpdate = this.mergeUpdateIntoPersonUpdate(
+ existingUpdate ?? fromInternalPerson(person, distinctId),
+ update,
+ true
+ )
+ personUpdate.id = person.id
+ cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)
+ return toInternalPerson(personUpdate)
+ }
+
+ /**
+ * After a merge commits, the survivor's entry takes the row and drops the pending changes the merge wrote
+ * over: those it read, for the keys its outcome carried. A change made since the read, or to a key the merge
+ * left alone, stays pending. With no entry, the row is cached as it stands. Returns the survivor as this pod
+ * sees it, the row with its pending changes applied.
+ */
+ takeMergedRow(
+ row: InternalPerson,
+ distinctId: string,
+ written: MergePersonUpdate,
+ read: PendingPersonChanges | null,
+ batchId: number
+ ): InternalPerson {
+ const entry = this.personCache.getLiveUpdate(row.team_id, row.id)
+ if (!entry) {
+ this.setCachedPersonForUpdate(row.team_id, distinctId, fromInternalPerson(row, distinctId), batchId)
+ return row
+ }
+ if (row.version > entry.version) {
+ takeRow(entry, row, row.version)
+ }
+ if (read) {
+ const carried = new Set([
+ ...Object.keys(written.properties ?? {}),
+ ...Object.keys(written.properties_to_set_once ?? {}),
+ ...(written.properties_to_unset ?? []),
+ ])
+ const pick = (lane: Properties): Properties =>
+ Object.fromEntries(Object.entries(lane).filter(([key]) => carried.has(key)))
+ retireCarried(entry, {
+ properties_to_set: pick(read.toSet),
+ properties_to_set_once: pick(read.toSetOnce),
+ properties_to_unset: read.toUnset.filter((key) => carried.has(key)),
+ })
+ }
+ return toInternalPerson(entry)
}
async applyEventOps(
@@ -1405,6 +1185,19 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
// intents refine here too — identification only transitions
// false→true, last-seen only advances.
const refined = refineEventOps(ops, person.properties, this.options.updateAllProperties)
+ // The view shows a pending change before it lands, so a $set of that value refines away but must still
+ // write: a set-once as a set, and an unforced set when this event is forced. An unforced repeat of a
+ // pending set changes nothing and is left alone.
+ const live = this.personCache.getLiveUpdate(person.team_id, person.id)
+ const lanes = live
+ ? [live.properties_to_set_once, ...(ops.shouldForceUpdate ? [live.properties_to_set] : [])]
+ : []
+ for (const [key, value] of Object.entries(ops.set)) {
+ if (lanes.some((lane) => Object.hasOwn(lane, key) && isEqual(lane[key], value))) {
+ refined.toSet[key] = value
+ refined.hasChanges = true
+ }
+ }
const otherUpdates = computeOpsScalarUpdates(ops, person)
if (!refined.hasChanges && Object.keys(otherUpdates).length === 0) {
@@ -1495,10 +1288,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
const response = await (tx || this.personRepository).deletePerson(personToDelete)
observeLatencyByVersion(person, start, 'deletePerson')
-
- // Clear ALL caches related to this person id
- this.clearAllCachesForPersonId(person.team_id, person.id)
-
+ // The merge clears the caches after commit, so a rollback keeps them.
return response
}
@@ -1528,6 +1318,29 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return await (tx || this.personRepository).isPersonLive(person)
}
+ async readMergeRows(
+ teamId: number,
+ targetId: string,
+ sourceIds: string[],
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<InternalPerson[]> {
+ this.incrementDatabaseOperation('readMergeRows', distinctId)
+ return await tx.readMergeRows(teamId, targetId, sourceIds)
+ }
+
+ pendingChanges(teamId: number, personId: string): PendingPersonChanges | null {
+ const cached = this.personCache.getCachedPersonForUpdateByPersonId(teamId, personId)
+ return cached
+ ? {
+ toSet: cached.properties_to_set,
+ toSetOnce: cached.properties_to_set_once,
+ toUnset: cached.properties_to_unset,
+ createdAt: cached.created_at,
+ }
+ : null
+ }
+
async fetchPersonsForUpdateByDistinctIds(
teamId: Team['id'],
distinctIds: string[],
@@ -1538,10 +1351,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
}
this.incrementCount('fetchPersonsForUpdateByDistinctIds', distinctIds[0])
this.incrementDatabaseOperation('fetchPersonsForUpdateByDistinctIds', distinctIds[0])
- const rows = await this.personRepository.fetchPersonsForUpdateByDistinctIds(
- teamId,
- distinctIds,
- 'ingestion/merge-fold'
+ const { result: rows, dropped } = await this.readRows(
+ () => this.personRepository.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, 'ingestion/merge-fold'),
+ (found) => found
)
// Populate the per-batch update cache so later events for these
@@ -1549,7 +1361,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
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))
+ if (!dropped.has(person.id)) {
+ cache.setCachedPersonForUpdate(teamId, distinct_id, fromInternalPerson(person, distinct_id))
+ }
}
return rows
@@ -1572,11 +1386,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
if (persons.length > 0) {
observeLatencyByVersion(persons[0], start, 'deletePersons')
}
-
- for (const person of persons) {
- this.clearAllCachesForPersonId(person.team_id, person.id)
- }
-
+ // The merge clears the caches after commit, so a rollback keeps them.
return response
}
@@ -1610,9 +1420,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
const response = await tx.moveDistinctIds(source, target, limit)
observeLatencyByVersion(target, start, 'moveDistinctIds')
- // Clear the cache for the source person id to ensure deleted person isn't cached
- this.clearAllCachesForPersonId(source.team_id, source.id)
-
// Update cache for the target person for the current distinct ID
// Check if we already have cached data for the target person that includes merged properties
const existingTargetCache = this.getCachedPersonForUpdateByPersonId(target.team_id, target.id)
@@ -1628,6 +1435,8 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
if (response.success) {
for (const movedDistinctId of response.distinctIdsMoved) {
this.setDistinctIdToPersonId(target.team_id, movedDistinctId, target.id, batchId)
+ // The checked person is the source; drop it so the next check reads the row.
+ this.getCheckCache().delete(this.getDistinctCacheKey(target.team_id, movedDistinctId))
}
}
@@ -1647,10 +1456,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
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) {
@@ -1662,6 +1467,8 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
if (response.success) {
for (const movedDistinctId of response.distinctIdsMoved) {
this.setDistinctIdToPersonId(target.team_id, movedDistinctId, target.id, batchId)
+ // The checked person is the source; drop it so the next check reads the row.
+ this.getCheckCache().delete(this.getDistinctCacheKey(target.team_id, movedDistinctId))
}
}
@@ -1836,6 +1643,27 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
this.personCache.clearPersonCacheForPersonId(teamId, personId)
}
+ /**
+ * After a merge commits, drops the source's entry unless changes reached it since the merge read its pending
+ * changes; those stay for the next flush, whose no-rows re-target lands them on the survivor. Either way the
+ * source's distinct ids read the row from now on, so no event lands on the deleted person.
+ */
+ releaseMergedSource(teamId: number, personId: string, carried: PendingPersonChanges | null): void {
+ const entry = this.personCache.getLiveUpdate(teamId, personId)
+ if (entry && carried) {
+ retireCarried(entry, {
+ properties_to_set: carried.toSet,
+ properties_to_set_once: carried.toSetOnce,
+ properties_to_unset: carried.toUnset,
+ })
+ }
+ if (entry && hasLanes(entry)) {
+ this.personCache.detachEntry(teamId, personId)
+ return
+ }
+ this.personCache.clearAllCachesForPersonId(teamId, personId)
+ }
+
clearAllCachesForPersonId(teamId: number, personId: string): void {
this.personCache.clearAllCachesForPersonId(teamId, personId)
}
@@ -1920,39 +1748,13 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return result
}
- private addPersonUpdateToBatch(
- person: InternalPerson,
- update: Partial<InternalPerson>,
- distinctId: string,
- batchId: number
- ): [InternalPerson, PersonMessage[], boolean] {
- const cache = this.personCache.obtainForBatchId(batchId)
- const existingUpdate = cache.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)
-
- let personUpdate: PersonUpdate
- if (!existingUpdate) {
- // Create new PersonUpdate from the person and apply the update
- personUpdate = fromInternalPerson(person, distinctId)
- personUpdate = this.mergeUpdateIntoPersonUpdate(personUpdate, update, true)
- personUpdate.id = person.id
- cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)
- } else {
- // Merge updates into existing cached PersonUpdate
- personUpdate = this.mergeUpdateIntoPersonUpdate(existingUpdate, update, true)
- personUpdate.id = person.id
- cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)
- }
- // Return the merged person from the cache
- return [toInternalPerson(personUpdate), [], false]
- }
-
/**
* Helper method to merge an update into a PersonUpdate
* Handles properties and is_identified merging with proper logic
*/
private mergeUpdateIntoPersonUpdate(
personUpdate: PersonUpdate,
- update: Partial<InternalPerson>,
+ update: MergePersonUpdate,
allowCreatedAtUpdate: boolean = false
): PersonUpdate {
// For properties, we track them in the fine-grained properties_to_set/unset
@@ -1968,8 +1770,28 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
})
}
+ personUpdate.properties_to_set_once = {
+ ...personUpdate.properties_to_set_once,
+ ...update.properties_to_set_once,
+ }
+
+ // An unset wins over a set the batch already queued for the same key.
+ for (const key of update.properties_to_unset ?? []) {
+ delete personUpdate.properties_to_set[key]
+ delete personUpdate.properties_to_set_once[key]
+ if (!personUpdate.properties_to_unset.includes(key)) {
+ personUpdate.properties_to_unset.push(key)
+ }
+ }
+
// Apply other updates (excluding properties which we handled above)
- const fieldsToExclude = ['properties', 'is_identified']
+ const fieldsToExclude = [
+ 'properties',
+ 'properties_to_set_once',
+ 'properties_to_unset',
+ 'is_identified',
+ 'last_seen_at',
+ ]
if (!allowCreatedAtUpdate) {
fieldsToExclude.push('created_at')
}
@@ -1994,6 +1816,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
if (update.is_identified !== undefined) {
personUpdate.is_identified = personUpdate.is_identified || update.is_identified
}
+ if (update.last_seen_at && (!personUpdate.last_seen_at || update.last_seen_at > personUpdate.last_seen_at)) {
+ personUpdate.last_seen_at = update.last_seen_at
+ }
personUpdate.needs_write = true
@@ -2038,6 +1863,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
}
// Remove from set list if it was there
delete personUpdate.properties_to_set[key]
+ delete personUpdate.properties_to_set_once[key]
})
// Handle is_identified specially with || operator
@@ -2064,33 +1890,68 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return [toInternalPerson(personUpdate), []]
}
+ /** One row through the batch statement; a missing row throws for withMergeRetry. */
private async updatePersonNoAssert(personUpdate: PersonUpdate): Promise<PersonUpdateResult> {
const operation = 'updatePersonNoAssert'
this.incrementDatabaseOperation(operation as MethodName, personUpdate.distinct_id)
- // Convert PersonUpdate back to InternalPerson for database call
+
+ this.incrementCount('updatePersonNoAssert', personUpdate.distinct_id)
+ this.incrementDatabaseOperation('updatePersonNoAssert', personUpdate.distinct_id)
+ const start = performance.now()
+
+ const result = (await this.personRepository.updatePersonsBatch([personUpdate])).get(personUpdate.uuid)
+ if (result?.error instanceof PersonPropertiesSizeViolationError) {
+ return this.repairOversizedPerson(personUpdate, start)
+ }
+ this.recordUpdateLatency('updatePersonNoAssert', (performance.now() - start) / 1000, personUpdate.distinct_id)
+ observeLatencyByVersion(toInternalPerson(personUpdate), start, 'updatePersonNoAssert')
+
+ if (!result?.success) {
+ throw result?.error ?? new NoRowsUpdatedError(`Person with uuid="${personUpdate.uuid}" was not updated`)
+ }
+ if (result.person && result.version !== undefined) {
+ this.retireLandedChanges(personUpdate, result.person, result.version)
+ }
+ return { success: true, messages: result.kafkaMessage ? [result.kafkaMessage] : [] }
+ }
+
+ /**
+ * Trims and writes a row already over the size limit; rejects any other oversized write. The trim can drop keys
+ * this write carried, so nothing retires.
+ */
+ private async repairOversizedPerson(personUpdate: PersonUpdate, start: number): Promise<PersonUpdateResult> {
const person = toInternalPerson(personUpdate)
- // Always pass all mutable fields for consistent query plans
- const updateFields = {
+ const [, messages] = await this.personRepository.handleOversizedPersonProperties(person, {
properties: person.properties,
properties_last_updated_at: person.properties_last_updated_at,
properties_last_operation: person.properties_last_operation,
is_identified: person.is_identified,
created_at: person.created_at,
last_seen_at: person.last_seen_at,
- }
-
- this.incrementCount('updatePersonNoAssert', personUpdate.distinct_id)
- this.incrementDatabaseOperation('updatePersonNoAssert', personUpdate.distinct_id)
- const start = performance.now()
-
- const [_, messages] = await this.personRepository.updatePerson(person, updateFields, 'updatePersonNoAssert')
+ })
this.recordUpdateLatency('updatePersonNoAssert', (performance.now() - start) / 1000, personUpdate.distinct_id)
observeLatencyByVersion(person, start, 'updatePersonNoAssert')
-
- // updatePersonNoAssert always succeeds (no version conflicts)
return { success: true, messages }
}
+ private async rejectOversizedWrite(update: PersonUpdate, method: string): Promise<void> {
+ personWriteMethodAttemptCounter.inc({
+ db_write_mode: this.options.dbWriteMode,
+ method,
+ outcome: 'properties_size_violation',
+ })
+ await emitIngestionWarning(this.ingestionWarningsOutputs, update.team_id, {
+ type: 'person_properties_size_violation',
+ details: {
+ personId: update.uuid,
+ distinctId: update.distinct_id,
+ teamId: update.team_id,
+ message: 'Person properties exceeds size limit and was rejected',
+ },
+ pipelineStep: 'person-store',
+ })
+ }
+
/**
* Updates the person in the database by attempting to write to a column where the version is the stored cached
* version. If no rows to update are found, the update fails and we retry by reading again from the database.
@@ -2112,6 +1973,8 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
observeLatencyByVersion(personUpdate, start, 'updatePersonAssertVersion')
if (actualVersion !== undefined) {
+ // The version matched, so the row now holds exactly this record's view.
+ this.retireLandedChanges(personUpdate, toInternalPerson(personUpdate), actualVersion)
// Success - optimistic update worked, create updated PersonUpdate with new version
const updatedPersonUpdate: PersonUpdate = {
...personUpdate,
@@ -2129,6 +1992,15 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
callerTag: 'ingestion/person-version-conflict',
})
+ if (latestPerson && latestPerson.id !== personUpdate.id) {
+ // The distinct id belongs to another person now; re-target as the NO_ASSERT path does, and like it
+ // treat nothing to re-target as done.
+ const refreshed = await this.refreshPersonIdAfterMerge(personUpdate)
+ return refreshed
+ ? { success: false, messages: [], personUpdate: refreshed }
+ : { success: true, messages: [] }
+ }
+
if (latestPerson) {
// Use fine-grained merge: start with latest properties from DB and apply our specific changes
const mergedProperties = { ...latestPerson.properties }
@@ -2292,13 +2164,22 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return null
}
+ const live = this.personCache.getLiveUpdate(personUpdate.team_id, personUpdate.id)
+ // On the first hop the record's lanes are the flush's copy of the entry under its id, which holds them plus
+ // every change since, minus what a merge on this pod has carried or decided against; so the entry is the
+ // carrier and the copy is dropped, and an entry a merge released leaves nothing to re-target. On a later
+ // hop the entry under the record's id belongs to another person, and the record is the only carrier of
+ // the earlier hop.
+ const firstHop = !personUpdate.retargeted
+ if (firstHop && !live) {
+ return null
+ }
// Clear the old person ID from cache since it's been merged
this.clearPersonCacheForPersonId(personUpdate.team_id, personUpdate.id)
// Update our cache mapping to reflect the new person ID
this.personCache.setDistinctIdToPersonId(personUpdate.team_id, personUpdate.distinct_id, currentPerson.id)
- // Create updated PersonUpdate with the new person ID and version
const updatedPersonUpdate: PersonUpdate = {
id: currentPerson.id,
team_id: personUpdate.team_id,
@@ -2307,17 +2188,38 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
properties: currentPerson.properties,
properties_last_updated_at: personUpdate.properties_last_updated_at,
properties_last_operation: personUpdate.properties_last_operation,
- created_at: currentPerson.created_at,
+ created_at: DateTime.min(currentPerson.created_at, personUpdate.created_at),
version: currentPerson.version,
is_identified: currentPerson.is_identified || personUpdate.is_identified,
is_user_id: personUpdate.is_user_id,
- last_seen_at: personUpdate.last_seen_at,
+ // Like created_at, the record keeps what an earlier hop carried even when no live entry remains.
+ last_seen_at:
+ personUpdate.last_seen_at &&
+ (!currentPerson.last_seen_at || personUpdate.last_seen_at > currentPerson.last_seen_at)
+ ? personUpdate.last_seen_at
+ : currentPerson.last_seen_at,
needs_write: personUpdate.needs_write,
- properties_to_set: personUpdate.properties_to_set,
- properties_to_unset: personUpdate.properties_to_unset,
+ properties_to_set: firstHop ? {} : personUpdate.properties_to_set,
+ properties_to_set_once: firstHop ? {} : personUpdate.properties_to_set_once,
+ properties_to_unset: firstHop ? [] : personUpdate.properties_to_unset,
original_is_identified: personUpdate.original_is_identified,
original_created_at: personUpdate.original_created_at,
original_last_seen_at: personUpdate.original_last_seen_at,
+ retargeted: true,
+ }
+ if (live) {
+ this.mergeUpdateIntoPersonUpdate(
+ updatedPersonUpdate,
+ {
+ properties: live.properties_to_set,
+ properties_to_set_once: live.properties_to_set_once,
+ properties_to_unset: live.properties_to_unset,
+ is_identified: live.is_identified,
+ created_at: live.created_at,
+ ...(live.last_seen_at ? { last_seen_at: live.last_seen_at } : {}),
+ },
+ true
+ )
}
return updatedPersonUpdate
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-persons-cache.ts b/nodejs/src/ingestion/common/persons/batch-writing-persons-cache.ts
new file mode 100644
index 000000000000..c4df1529cc46
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/batch-writing-persons-cache.ts
@@ -0,0 +1,558 @@
+import { isEqual } from 'lodash'
+import { DateTime } from 'luxon'
+
+import { PersonUpdate } from '~/common/persons/person-update-batch'
+import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
+import { InternalPerson } from '~/types'
+
+interface CacheMetrics {
+ updateCacheHits: number
+ updateCacheMisses: number
+ checkCacheHits: number
+ checkCacheMisses: number
+}
+
+type PendingChange = { set: unknown } | { setOnce: unknown } | { unset: true }
+type Lanes = Pick<PersonUpdate, 'properties_to_set' | 'properties_to_set_once' | 'properties_to_unset'>
+
+/** One key's pending change, tagged by lane, so two records compare by what each would send. */
+function pendingChangeFor(update: Lanes, name: string): PendingChange | undefined {
+ if (Object.hasOwn(update.properties_to_set, name)) {
+ return { set: update.properties_to_set[name] }
+ }
+ if (Object.hasOwn(update.properties_to_set_once, name)) {
+ return { setOnce: update.properties_to_set_once[name] }
+ }
+ if (update.properties_to_unset.includes(name)) {
+ return { unset: true }
+ }
+ return undefined
+}
+
+/**
+ * Removes from the entry each pending change equal to the one a write or a merge carried for that key; a
+ * differing change made since stays pending.
+ */
+export function retireCarried(entry: PersonUpdate, carried: Lanes): void {
+ const names = new Set([
+ ...Object.keys(carried.properties_to_set),
+ ...Object.keys(carried.properties_to_set_once),
+ ...carried.properties_to_unset,
+ ])
+ for (const name of names) {
+ const pending = pendingChangeFor(entry, name)
+ if (pending !== undefined && !isEqual(pending, pendingChangeFor(carried, name))) {
+ continue
+ }
+ delete entry.properties_to_set[name]
+ delete entry.properties_to_set_once[name]
+ entry.properties_to_unset = entry.properties_to_unset.filter((unset) => unset !== name)
+ }
+}
+
+type RowScalars = Pick<InternalPerson, 'properties' | 'is_identified' | 'created_at' | 'last_seen_at'>
+
+/**
+ * Points the entry's base at a row newer than the one it reflects, scalars included, so a flush with no newer
+ * change stays a no-op; a change made since the snapshot keeps precedence the way the statement merges it.
+ */
+export function takeRow(entry: PersonUpdate, row: RowScalars, version: number): void {
+ entry.version = version
+ entry.properties = { ...row.properties }
+ entry.is_identified = entry.is_identified || row.is_identified
+ entry.created_at = DateTime.min(entry.created_at, row.created_at)
+ if (row.last_seen_at && (!entry.last_seen_at || row.last_seen_at > entry.last_seen_at)) {
+ entry.last_seen_at = row.last_seen_at
+ }
+ entry.original_is_identified = row.is_identified
+ entry.original_created_at = row.created_at
+ entry.original_last_seen_at = row.last_seen_at
+}
+
+export function hasLanes(lanes: Lanes): boolean {
+ return (
+ Object.keys(lanes.properties_to_set).length > 0 ||
+ Object.keys(lanes.properties_to_set_once).length > 0 ||
+ lanes.properties_to_unset.length > 0
+ )
+}
+
+export class BatchWritingPersonsCache {
+ private personCheckCache = new Map<string, InternalPerson | null>()
+ /**
+ * Counts entry drops while row reads are in flight. A read that began before a person's entry was dropped
+ * may have read the row before whatever dropped it, so its answer is not installed for that person.
+ */
+ private generation = 0
+ private droppedAt = new Map<string, number>()
+ private readsInFlight = new Map<number, number>()
+ private nextRead = 0
+ private distinctIdToPersonId = new Map<string, string>()
+ private personUpdateCache = new Map<string, PersonUpdate | null>()
+ private batchDistinctKeys = new Map<number, Set<string>>()
+ private distinctKeyRefCount = new Map<string, number>()
+ private deferredEvictions = new Set<string>()
+ /** Entries kept without distinct ids for a flush to re-target, by person key; evicted once clean. */
+ private detachedEntries = new Set<string>()
+ private pendingPrefetchesByBatchId = new Map<number, number>()
+ private releasedBatchIdsWithPendingPrefetch = new Set<number>()
+ private cacheMetrics: CacheMetrics = {
+ updateCacheHits: 0,
+ updateCacheMisses: 0,
+ checkCacheHits: 0,
+ checkCacheMisses: 0,
+ }
+
+ obtainForBatchId(batchId: number): BatchBoundPersonsCache {
+ return new BatchBoundPersonsCache(this, batchId)
+ }
+
+ getCheckCache(): Map<string, InternalPerson | null> {
+ return this.personCheckCache
+ }
+
+ getUpdateCache(): Map<string, PersonUpdate | null> {
+ return this.personUpdateCache
+ }
+
+ getDistinctIdToPersonIdCache(): Map<string, string> {
+ return this.distinctIdToPersonId
+ }
+
+ getBatchDistinctKeys(): Map<number, Set<string>> {
+ return this.batchDistinctKeys
+ }
+
+ getDistinctKeyRefCount(): Map<string, number> {
+ return this.distinctKeyRefCount
+ }
+
+ getCacheMetrics(): CacheMetrics {
+ return this.cacheMetrics
+ }
+
+ resetMetrics(): void {
+ this.cacheMetrics = {
+ updateCacheHits: 0,
+ updateCacheMisses: 0,
+ checkCacheHits: 0,
+ checkCacheMisses: 0,
+ }
+ }
+
+ getUpdateCacheValues(): IterableIterator<PersonUpdate | null> {
+ return this.personUpdateCache.values()
+ }
+
+ getUpdateCacheEntries(): IterableIterator<[string, PersonUpdate | null]> {
+ return this.personUpdateCache.entries()
+ }
+
+ getFlushStats(): BatchWritingStoreFlushStats {
+ const dirtyPersonKeys = new Set<string>()
+ for (const [personKey, update] of this.personUpdateCache.entries()) {
+ if (update?.needs_write) {
+ dirtyPersonKeys.add(personKey)
+ }
+ }
+
+ const referencedBatchIds = new Set<number>()
+ for (const [batchId, distinctKeys] of this.batchDistinctKeys.entries()) {
+ for (const distinctKey of distinctKeys) {
+ const personId = this.distinctIdToPersonId.get(distinctKey)
+ if (!personId) {
+ continue
+ }
+
+ const separatorIndex = distinctKey.indexOf(':')
+ const teamId = distinctKey.slice(0, separatorIndex)
+ if (dirtyPersonKeys.has(`${teamId}:${personId}`)) {
+ referencedBatchIds.add(batchId)
+ break
+ }
+ }
+ }
+
+ return {
+ dirtyEntryCount: dirtyPersonKeys.size,
+ referencedBatchCount: referencedBatchIds.size,
+ cacheEntryCount: this.personUpdateCache.size,
+ }
+ }
+
+ getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {
+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
+ const result = this.personCheckCache.get(cacheKey)
+ if (result !== undefined) {
+ this.cacheMetrics.checkCacheHits++
+ return result === null
+ ? null
+ : {
+ ...result,
+ properties: { ...result.properties },
+ created_at: result.created_at,
+ }
+ }
+
+ this.cacheMetrics.checkCacheMisses++
+ return result
+ }
+
+ getCachedPersonForUpdateByPersonId(teamId: number, personId: string | undefined): PersonUpdate | null | undefined {
+ if (personId === undefined) {
+ this.cacheMetrics.updateCacheMisses++
+ return undefined
+ }
+
+ const result = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, personId))
+ if (result !== undefined) {
+ this.cacheMetrics.updateCacheHits++
+ if (result === null) {
+ return null
+ }
+
+ return {
+ ...result,
+ properties: { ...result.properties },
+ properties_to_set: { ...result.properties_to_set },
+ properties_to_set_once: { ...result.properties_to_set_once },
+ properties_to_unset: [...result.properties_to_unset],
+ }
+ }
+
+ this.cacheMetrics.updateCacheMisses++
+ return undefined
+ }
+
+ getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {
+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
+ const personId = this.distinctIdToPersonId.get(cacheKey)
+
+ return this.getCachedPersonForUpdateByPersonId(teamId, personId)
+ }
+
+ setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {
+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
+
+ if (person === null) {
+ const existingPersonId = this.distinctIdToPersonId.get(cacheKey)
+ this.distinctIdToPersonId.delete(cacheKey)
+ if (existingPersonId) {
+ const personIdKey = this.getPersonIdCacheKey(teamId, existingPersonId)
+ this.dropEntry(personIdKey)
+ this.personUpdateCache.set(personIdKey, null)
+ }
+ return
+ }
+
+ this.distinctIdToPersonId.set(cacheKey, person.id)
+
+ const existingPersonUpdate = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, person.id))
+
+ if (existingPersonUpdate) {
+ const mergedPersonUpdate = this.mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate, person)
+ this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), mergedPersonUpdate)
+ } else {
+ this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), person)
+ }
+ }
+
+ setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {
+ this.personCheckCache.set(this.getDistinctCacheKey(teamId, distinctId), person)
+ }
+
+ setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {
+ this.distinctIdToPersonId.set(this.getDistinctCacheKey(teamId, distinctId), personId)
+ }
+
+ clearPersonCacheForPersonId(teamId: number, personId: string): void {
+ this.dropEntry(this.getPersonIdCacheKey(teamId, personId))
+ }
+
+ clearAllCachesForPersonId(teamId: number, personId: string): void {
+ this.clearPersonCacheForPersonId(teamId, personId)
+ this.dropDistinctIdsForPersonId(teamId, personId)
+ }
+
+ /** Sends the next read of each of the person's distinct ids to the row; the entry itself stays. */
+ private dropDistinctIdsForPersonId(teamId: number, personId: string): void {
+ const distinctIdsToRemove: string[] = []
+ for (const [distinctCacheKey, mappedPersonId] of this.distinctIdToPersonId.entries()) {
+ if (mappedPersonId === personId && distinctCacheKey.startsWith(`${teamId}:`)) {
+ distinctIdsToRemove.push(distinctCacheKey)
+ }
+ }
+
+ for (const distinctCacheKey of distinctIdsToRemove) {
+ this.distinctIdToPersonId.delete(distinctCacheKey)
+ this.personCheckCache.delete(distinctCacheKey)
+ }
+ }
+
+ removeDistinctIdFromCache(teamId: number, distinctId: string): void {
+ this.distinctIdToPersonId.delete(this.getDistinctCacheKey(teamId, distinctId))
+ }
+
+ clearAllCachesForDistinctId(teamId: number, distinctId: string): void {
+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)
+ const personId = this.distinctIdToPersonId.get(cacheKey)
+
+ this.distinctIdToPersonId.delete(cacheKey)
+
+ if (personId) {
+ this.clearPersonCacheForPersonId(teamId, personId)
+ }
+
+ this.personCheckCache.delete(cacheKey)
+ }
+
+ releaseBatchId(batchId: number): void {
+ const keys = this.batchDistinctKeys.get(batchId)
+ if (this.pendingPrefetchesByBatchId.has(batchId)) {
+ this.releasedBatchIdsWithPendingPrefetch.add(batchId)
+ }
+ if (!keys) {
+ return
+ }
+
+ for (const distinctKey of keys) {
+ const refCount = (this.distinctKeyRefCount.get(distinctKey) ?? 1) - 1
+ if (refCount <= 0) {
+ this.distinctKeyRefCount.delete(distinctKey)
+ this.evictDistinctKey(distinctKey)
+ } else {
+ this.distinctKeyRefCount.set(distinctKey, refCount)
+ }
+ }
+
+ this.batchDistinctKeys.delete(batchId)
+ }
+
+ trackPendingPrefetch(batchIds: Set<number>): void {
+ for (const batchId of batchIds) {
+ this.pendingPrefetchesByBatchId.set(batchId, (this.pendingPrefetchesByBatchId.get(batchId) ?? 0) + 1)
+ }
+ }
+
+ finishPendingPrefetch(batchIds: Set<number>): void {
+ for (const batchId of batchIds) {
+ const pendingCount = (this.pendingPrefetchesByBatchId.get(batchId) ?? 1) - 1
+ if (pendingCount <= 0) {
+ this.pendingPrefetchesByBatchId.delete(batchId)
+ this.releasedBatchIdsWithPendingPrefetch.delete(batchId)
+ } else {
+ this.pendingPrefetchesByBatchId.set(batchId, pendingCount)
+ }
+ }
+ }
+
+ isBatchReleasedWithPendingPrefetch(batchId: number): boolean {
+ return this.releasedBatchIdsWithPendingPrefetch.has(batchId)
+ }
+
+ processDeferredEvictions(): void {
+ for (const personIdKey of this.detachedEntries) {
+ const update = this.personUpdateCache.get(personIdKey)
+ if (!update || !update.needs_write) {
+ this.dropEntry(personIdKey)
+ this.detachedEntries.delete(personIdKey)
+ }
+ }
+ for (const distinctKey of this.deferredEvictions) {
+ const colonIdx = distinctKey.indexOf(':')
+ const teamId = Number(distinctKey.slice(0, colonIdx))
+ const personId = this.distinctIdToPersonId.get(distinctKey)
+ if (personId === undefined) {
+ this.deferredEvictions.delete(distinctKey)
+ continue
+ }
+ const personIdKey = this.getPersonIdCacheKey(teamId, personId)
+ const update = this.personUpdateCache.get(personIdKey)
+ if (!update || !update.needs_write) {
+ this.dropEntry(personIdKey)
+ this.distinctIdToPersonId.delete(distinctKey)
+ this.deferredEvictions.delete(distinctKey)
+ }
+ }
+ }
+
+ trackBatchEntry(batchId: number, teamId: number, distinctId: string): void {
+ const distinctKey = this.getDistinctCacheKey(teamId, distinctId)
+ let keys = this.batchDistinctKeys.get(batchId)
+ if (!keys) {
+ keys = new Set()
+ this.batchDistinctKeys.set(batchId, keys)
+ }
+ if (!keys.has(distinctKey)) {
+ keys.add(distinctKey)
+ this.distinctKeyRefCount.set(distinctKey, (this.distinctKeyRefCount.get(distinctKey) ?? 0) + 1)
+ }
+ }
+
+ private evictDistinctKey(distinctKey: string): void {
+ const colonIdx = distinctKey.indexOf(':')
+ const teamId = Number(distinctKey.slice(0, colonIdx))
+ const personId = this.distinctIdToPersonId.get(distinctKey)
+
+ if (personId !== undefined) {
+ const personIdKey = this.getPersonIdCacheKey(teamId, personId)
+ const update = this.personUpdateCache.get(personIdKey)
+ if (!update || !update.needs_write) {
+ this.dropEntry(personIdKey)
+ this.distinctIdToPersonId.delete(distinctKey)
+ } else {
+ this.deferredEvictions.add(distinctKey)
+ }
+ }
+
+ this.personCheckCache.delete(distinctKey)
+ }
+
+ private mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate: PersonUpdate, person: PersonUpdate): PersonUpdate {
+ const mergedPersonUpdate: PersonUpdate = {
+ ...existingPersonUpdate,
+ is_identified: existingPersonUpdate.is_identified || person.is_identified,
+ }
+ // A row read replaces the base only when it is newer than the row the base reflects; an older read, or an
+ // entry built from this one or its view, carries no newer version and leaves it.
+ if (person.version > existingPersonUpdate.version) {
+ takeRow(
+ mergedPersonUpdate,
+ {
+ properties: person.properties,
+ is_identified: person.original_is_identified,
+ created_at: person.original_created_at,
+ last_seen_at: person.original_last_seen_at,
+ },
+ person.version
+ )
+ }
+
+ // Pending holds only this pod's sets, never the fetched row.
+ mergedPersonUpdate.properties_to_set = {
+ ...existingPersonUpdate.properties_to_set,
+ ...person.properties_to_set,
+ }
+ mergedPersonUpdate.properties_to_set_once = {
+ ...existingPersonUpdate.properties_to_set_once,
+ ...person.properties_to_set_once,
+ }
+ for (const key of person.properties_to_unset) {
+ delete mergedPersonUpdate.properties_to_set[key]
+ delete mergedPersonUpdate.properties_to_set_once[key]
+ }
+
+ mergedPersonUpdate.properties_to_unset = [
+ ...new Set([...existingPersonUpdate.properties_to_unset, ...person.properties_to_unset]),
+ ]
+ const keysToSet = new Set(Object.keys(person.properties_to_set))
+ mergedPersonUpdate.properties_to_unset = mergedPersonUpdate.properties_to_unset.filter(
+ (key) => !keysToSet.has(key)
+ )
+
+ mergedPersonUpdate.created_at = DateTime.min(existingPersonUpdate.created_at, person.created_at)
+ mergedPersonUpdate.needs_write = existingPersonUpdate.needs_write || person.needs_write
+ mergedPersonUpdate.force_update = existingPersonUpdate.force_update || person.force_update
+
+ if (person.last_seen_at) {
+ if (!mergedPersonUpdate.last_seen_at || person.last_seen_at > mergedPersonUpdate.last_seen_at) {
+ mergedPersonUpdate.last_seen_at = person.last_seen_at
+ }
+ }
+
+ return mergedPersonUpdate
+ }
+
+ private getDistinctCacheKey(teamId: number, distinctId: string): string {
+ return `${teamId}:${distinctId}`
+ }
+
+ beginRead(): number {
+ const read = this.nextRead++
+ this.readsInFlight.set(read, this.generation)
+ return read
+ }
+
+ endRead(read: number): void {
+ this.readsInFlight.delete(read)
+ if (this.readsInFlight.size === 0) {
+ this.droppedAt.clear()
+ } else if (this.droppedAt.size > 256) {
+ const oldest = Math.min(...this.readsInFlight.values())
+ for (const [key, at] of this.droppedAt) {
+ if (at <= oldest) {
+ this.droppedAt.delete(key)
+ }
+ }
+ }
+ }
+
+ droppedSince(teamId: number, personId: string, read: number): boolean {
+ const began = this.readsInFlight.get(read) ?? this.generation
+ return (this.droppedAt.get(this.getPersonIdCacheKey(teamId, personId)) ?? -1) > began
+ }
+
+ private dropEntry(personIdKey: string): void {
+ this.personUpdateCache.delete(personIdKey)
+ this.fenceReads(personIdKey)
+ }
+
+ /** A read that began before now does not install this person, whether or not its entry stays. */
+ private fenceReads(personIdKey: string): void {
+ if (this.readsInFlight.size > 0) {
+ this.droppedAt.set(personIdKey, ++this.generation)
+ }
+ }
+
+ /**
+ * Keeps the entry for the next flush alone: its distinct ids read the row, a read from before now does not
+ * reinstall the person, and the entry is evicted once it is clean.
+ */
+ detachEntry(teamId: number, personId: string): void {
+ const personIdKey = this.getPersonIdCacheKey(teamId, personId)
+ this.fenceReads(personIdKey)
+ this.dropDistinctIdsForPersonId(teamId, personId)
+ this.detachedEntries.add(personIdKey)
+ }
+
+ /** The live entry itself: no copy and no cache hit metrics. */
+ getLiveUpdate(teamId: number, personId: string): PersonUpdate | null | undefined {
+ return this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, personId))
+ }
+
+ private getPersonIdCacheKey(teamId: number, personId: string): string {
+ return `${teamId}:${personId}`
+ }
+}
+
+class BatchBoundPersonsCache {
+ constructor(
+ private readonly cache: BatchWritingPersonsCache,
+ private readonly batchId: number
+ ) {}
+
+ getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {
+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
+ return this.cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)
+ }
+
+ getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {
+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
+ return this.cache.getCheckCachedPerson(teamId, distinctId)
+ }
+
+ setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {
+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
+ this.cache.setCachedPersonForUpdate(teamId, distinctId, person)
+ }
+
+ setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {
+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
+ this.cache.setCheckCachedPerson(teamId, distinctId, person)
+ }
+
+ setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {
+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
+ this.cache.setDistinctIdToPersonId(teamId, distinctId, personId)
+ }
+}
diff --git a/nodejs/src/ingestion/common/persons/person-create-service.test.ts b/nodejs/src/ingestion/common/persons/person-create-service.test.ts
index 8c57318bd395..a58980ff4ae0 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.test.ts
@@ -173,7 +173,7 @@ describe('PersonCreateService', () => {
mockPersonStore.createPerson.mockResolvedValue(conflictResult)
mockPersonStore.fetchForUpdate.mockResolvedValue(existingPerson)
- const [person, created] = await personCreateService.createPerson(
+ const [person, created, , idOwned] = await personCreateService.createPerson(
createdAt,
properties,
propertiesOnce,
@@ -186,6 +186,7 @@ describe('PersonCreateService', () => {
expect(person).toEqual(existingPerson)
expect(created).toBe(false)
+ expect(idOwned).toBe(true)
expect(mockPersonStore.fetchForUpdate).toHaveBeenCalledWith(teamId, 'test-distinct-id')
})
@@ -215,7 +216,7 @@ describe('PersonCreateService', () => {
})
mockPersonStore.fetchForUpdate.mockResolvedValue(null)
- const [person, created] = await personCreateService.createPerson(
+ const [person, created, , idOwned] = await personCreateService.createPerson(
createdAt,
properties,
propertiesOnce,
@@ -228,6 +229,7 @@ describe('PersonCreateService', () => {
expect(person).toEqual(holder)
expect(created).toBe(false)
+ expect(idOwned).toBe(false)
})
it('should prefer the distinct ID match over the uuid holder when both exist', async () => {
diff --git a/nodejs/src/ingestion/common/persons/person-create-service.ts b/nodejs/src/ingestion/common/persons/person-create-service.ts
index 694e768c13aa..4f4a596a5de9 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.ts
@@ -22,7 +22,8 @@ export class PersonCreateService {
* produce, so a transactional caller can defer it past commit instead of
* holding the transaction open across the Kafka roundtrip.
*
- * @returns [Person, true if person was created by this call (false if found existing person from concurrent creation), ClickHouse messages to produce]
+ * @returns [Person, true if person was created by this call (false if found existing person from concurrent creation), ClickHouse messages to produce,
+ * true if the conflict found a person that owns one of the requested distinct ids]
*/
async createPerson(
createdAt: DateTime,
@@ -35,7 +36,7 @@ export class PersonCreateService {
primaryDistinctId: { distinctId: string; version?: number },
extraDistinctIds?: { distinctId: string; version?: number }[],
tx?: PersonsStoreTransactionForBatch
- ): Promise<[InternalPerson, boolean, PersonMessage[]]> {
+ ): Promise<[InternalPerson, boolean, PersonMessage[], boolean]> {
const uuid = uuidFromDistinctId(teamId, primaryDistinctId.distinctId)
const props = { ...propertiesOnce, ...properties, ...{ $creator_event_uuid: creatorEventUuid } }
@@ -65,7 +66,7 @@ export class PersonCreateService {
)
if (result.success) {
- return [result.person, result.created, result.messages]
+ return [result.person, result.created, result.messages, false]
}
// Handle creation conflict - another process created the person concurrently
@@ -75,7 +76,7 @@ export class PersonCreateService {
for (const distinctIdInfo of allDistinctIds) {
const existingPerson = await this.store.fetchForUpdate(teamId, distinctIdInfo.distinctId)
if (existingPerson) {
- return [existingPerson, false, []]
+ return [existingPerson, false, [], true]
}
}
@@ -86,7 +87,7 @@ export class PersonCreateService {
// mapping, so no two identities are silently merged.
if (result.conflictingPerson) {
personCreateConflictResolvedCounter.labels({ resolved_by: 'uuid' }).inc()
- return [result.conflictingPerson, false, []]
+ return [result.conflictingPerson, false, [], false]
}
// The holder vanished between the failed write and the lookup, so there is
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
index d3c6fea59382..7323570fe579 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
@@ -45,6 +45,7 @@ describe('PostgresPersonMerge merge events', () => {
{
updateAllProperties: false,
isTombstoneTeam: () => false,
+ isLockedOutcomeTeam: () => true,
mergeEvents,
},
request,
@@ -288,6 +289,7 @@ describe('PostgresPersonMerge merge events', () => {
{
updateAllProperties: false,
isTombstoneTeam: () => false,
+ isLockedOutcomeTeam: () => true,
mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },
...policyOverrides,
},
@@ -336,6 +338,7 @@ describe('PostgresPersonMerge merge events', () => {
{
updateAllProperties: false,
isTombstoneTeam: () => false,
+ isLockedOutcomeTeam: () => true,
mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },
},
request,
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
index 1a082ccb4d5f..7b8c2263224d 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
@@ -1,9 +1,11 @@
+import { isEqual } from 'lodash'
import { DateTime } from 'luxon'
import { Counter, Histogram } from 'prom-client'
import { PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { personMergeFailureCounter } from '~/common/persons/metrics'
import { PersonMessage } from '~/common/persons/person-message'
+import { MergePersonUpdate, PendingPersonChanges } from '~/common/persons/person-update-batch'
import { isDistinctIdUnmergeable } from '~/common/persons/person-utils'
import {
PersonClaimedByLifecycleOpError,
@@ -20,6 +22,7 @@ import { PersonOutputs } from './person-context'
import { PersonCreateService } from './person-create-service'
import { buildPersonMergeEventMessage } from './person-merge-event'
import {
+ MergeOutcomeOversizedError,
PersonMergeLimitExceededError,
PersonMergeRaceConditionError,
PersonMergeResult,
@@ -128,6 +131,8 @@ export interface PostgresMergePolicy {
updateAllProperties: boolean
/** Teams on the new-world merge behavior: lifecycle-mark claims plus tombstone deletes. */
isTombstoneTeam: ValueMatcher<number>
+ /** Teams whose merge locks the person rows and writes the survivor in its transaction; others queue it for the flush. */
+ isLockedOutcomeTeam: ValueMatcher<number>
mergeEvents: MergeEventsConfig
/**
* When set, already-satisfied merges re-emit the committed mappings (debounced),
@@ -136,6 +141,29 @@ export interface PostgresMergePolicy {
noopMappingDebounce?: MergeMappingDebounce
}
+/**
+ * The keys a merge changes. The event's $set keys and keys this pod's pending unset hides go as sets, because the view
+ * can show a set-once that has not landed and the row can still hold a hidden key. Every other key only fills a gap.
+ */
+function propertyChanges(
+ before: Properties,
+ after: Properties,
+ eventSets: Properties,
+ hidden: Set<string>
+): { toSet: Properties; toSetOnce: Properties; toUnset: string[] } {
+ const toSet: Properties = {}
+ const toSetOnce: Properties = {}
+ for (const [key, value] of Object.entries(after)) {
+ // Deep equality: the outcome is a copy, so object values never match by reference.
+ if (Object.hasOwn(eventSets, key) || !isEqual(before[key], value)) {
+ const fillsGap = !Object.hasOwn(eventSets, key) && !hidden.has(key)
+ ;(fillsGap ? toSetOnce : toSet)[key] = value
+ }
+ }
+ const toUnset = Object.keys(before).filter((key) => !Object.hasOwn(after, key))
+ return { toSet, toSetOnce, toUnset }
+}
+
/**
* The Postgres implementation of PersonsStore.mergePersons:
* classification, lifecycle-mark claims, distinct-id moves, cohort
@@ -154,6 +182,10 @@ export class PostgresPersonMerge {
* unwinds past that scope while the commit it produced for stands.
*/
private bootstrapAck?: Promise<void>
+ /** The distinct ids the store re-pointed at the target during the attempt, purged when it throws. */
+ private movedDistinctIds: string[] = []
+ /** Set when an attempt's outcome was oversized; the rerun commits the merge without it. */
+ private dropOversizedOutcome = false
constructor(
private store: BatchWritingPersonsStore,
@@ -187,6 +219,10 @@ export class PostgresPersonMerge {
return this.policy.isTombstoneTeam(this.teamId)
}
+ private lockedOutcomeEnabled(): boolean {
+ return this.policy.isLockedOutcomeTeam(this.teamId)
+ }
+
async execute(): Promise<MergePersonsResult> {
if (this.request.sources.length === 0) {
throw new Error('mergePersons requires at least one source')
@@ -215,21 +251,117 @@ export class PostgresPersonMerge {
}
/**
- * Runs a single-source merge, purging both ids from the batch caches
- * on any throw: merge verbs update the caches optimistically inside a
- * transaction that has now rolled back, and a retry must re-read
- * committed state rather than a mapping that was never committed.
+ * Runs a single-source merge, purging both request ids and every id it
+ * moved from the batch caches on any throw: merge verbs update the
+ * caches optimistically inside a transaction that has now rolled back,
+ * and a retry must re-read committed state rather than a mapping that
+ * was never committed.
*/
private async mergeSingleWithCachePurge(source: MergePersonsSource): Promise<MergePersonsResult> {
+ this.movedDistinctIds = []
try {
return await this.mergeSingle(source)
} catch (error) {
this.store.removeDistinctIdFromCache(this.teamId, this.targetDistinctId)
this.store.removeDistinctIdFromCache(this.teamId, source.distinctId)
+ this.purgeMovedDistinctIds()
throw error
}
}
+ private purgeMovedDistinctIds(): void {
+ for (const distinctId of this.movedDistinctIds) {
+ this.store.removeDistinctIdFromCache(this.teamId, distinctId)
+ }
+ this.movedDistinctIds = []
+ }
+
+ /**
+ * Locks the target and sources, in ascending id order, and returns their rows; a row that is gone throws the
+ * caller's error for its role.
+ */
+ private async lockMergeRows(
+ tx: PersonsStoreTransactionForBatch,
+ target: InternalPerson,
+ sources: InternalPerson[],
+ missing: (role: 'target' | 'source') => Error
+ ): Promise<Map<string, InternalPerson>> {
+ const rows = await tx.readMergeRows(
+ target.team_id,
+ target.id,
+ sources.map((source) => source.id),
+ this.targetDistinctId
+ )
+ const byId = new Map(rows.map((row) => [row.id, row]))
+ if (!byId.has(target.id)) {
+ throw missing('target')
+ }
+ if (sources.some((source) => !byId.has(source.id))) {
+ throw missing('source')
+ }
+ return byId
+ }
+
+ /**
+ * Target wins over sources, earlier sources over later; the event's ops apply on top. Returns the pending
+ * changes each row's view took, so the entries can be settled against them after the commit.
+ */
+ private mergeOutcome(
+ byId: Map<string, InternalPerson>,
+ target: InternalPerson,
+ sources: InternalPerson[]
+ ): {
+ changes: { toSet: Properties; toSetOnce: Properties; toUnset: string[] }
+ createdAt: DateTime
+ pending: Map<string, PendingPersonChanges | null>
+ } {
+ const pendingById = new Map<string, PendingPersonChanges | null>()
+ const withPending = (row: InternalPerson): InternalPerson => {
+ const pending = this.store.pendingChanges(row.team_id, row.id)
+ pendingById.set(row.id, pending)
+ if (!pending) {
+ return row
+ }
+ const properties = { ...pending.toSetOnce, ...row.properties, ...pending.toSet }
+ for (const key of pending.toUnset) {
+ delete properties[key]
+ }
+ return { ...row, properties, created_at: DateTime.min(row.created_at, pending.createdAt) }
+ }
+ const targetView = withPending(byId.get(target.id)!)
+ const sourceViews = sources.map((source) => withPending(byId.get(source.id)!))
+ const after = this.applyMergePrecedence(targetView, sourceViews)
+ return {
+ changes: propertyChanges(
+ targetView.properties,
+ after.properties,
+ this.request.eventOps.set,
+ new Set(this.store.pendingChanges(target.team_id, target.id)?.toUnset)
+ ),
+ createdAt: DateTime.min(targetView.created_at, ...sourceViews.map((source) => source.created_at)),
+ pending: pendingById,
+ }
+ }
+
+ private applyMergePrecedence(target: InternalPerson, sources: InternalPerson[]): InternalPerson {
+ const merged: Properties = {}
+ for (let i = sources.length - 1; i >= 0; i--) {
+ Object.assign(merged, sources[i].properties)
+ }
+ Object.assign(merged, target.properties)
+ const refined = refineEventOps(this.request.eventOps, merged, this.policy.updateAllProperties)
+ const [after] = applyEventPropertyUpdates(refined, { ...target, properties: merged })
+ return after
+ }
+
+ private deferredOutcome(target: InternalPerson, sources: InternalPerson[]): MergePersonUpdate {
+ return {
+ created_at: DateTime.min(target.created_at, ...sources.map((source) => source.created_at)),
+ properties: this.applyMergePrecedence(target, sources).properties,
+ is_identified: true,
+ }
+ }
+
private inTransaction<T>(
description: string,
body: (tx: PersonsStoreTransactionForBatch) => Promise<T>
@@ -429,7 +561,7 @@ export class PostgresPersonMerge {
const distinctId2Version = 1
this.recordOverrideCount('neitherExist')
- const [created, wasCreated, messages] = await this.createService.createPerson(
+ const [created, wasCreated, messages, idOwned] = await this.createService.createPerson(
this.timestamp,
this.request.eventOps.set,
this.request.eventOps.setOnce,
@@ -441,8 +573,12 @@ export class PostgresPersonMerge {
[{ distinctId: distinctId2, version: distinctId2Version }],
tx
)
- // If person was not created (creation conflict) and is not identified,
- // we need to update it later
+ // A retry can attach only when no other writer owns one of the ids by now.
+ if (idOwned) {
+ throw new PersonMergeRaceConditionError(
+ `person for ${distinctId1} or ${distinctId2} was created concurrently during a merge`
+ )
+ }
return [created, !wasCreated && !created.is_identified, messages] as const
}
)
@@ -464,6 +600,7 @@ export class PostgresPersonMerge {
* fall back to per-event sequential merges.
*/
private async executeFold(): Promise<MergePersonsResult> {
+ this.movedDistinctIds = []
try {
return await this.executeFoldInner()
} catch (error) {
@@ -475,6 +612,7 @@ export class PostgresPersonMerge {
for (const source of this.request.sources) {
this.store.removeDistinctIdFromCache(this.teamId, source.distinctId)
}
+ this.purgeMovedDistinctIds()
logger.warn('🤔', 'folded merge failed, falling back to sequential merges', {
team_id: this.teamId,
distinct_id: this.targetDistinctId,
@@ -493,7 +631,7 @@ export class PostgresPersonMerge {
* 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;
+ * so there is nothing left of it to fold;
* - 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.
@@ -616,102 +754,111 @@ export class PostgresPersonMerge {
return { survivor: target, results: outcomes, kafkaAck }
}
- // Sequential property precedence: each source merges its properties
- // under the accumulated target's (target wins, earlier sources win
- // over later ones). Event $set/$set_once apply on top, as in mergePeople.
- const mergedProperties: Properties = {}
- for (let i = mergeSources.length - 1; i >= 0; i--) {
- Object.assign(mergedProperties, mergeSources[i].properties)
- }
- Object.assign(mergedProperties, target.properties)
- const propertyUpdates = refineEventOps(this.request.eventOps, mergedProperties, this.policy.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
this.discardOverrideCounts()
const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)
- const [mergedPerson, kafkaMessages] = await this.inTransaction('mergePeopleFold', async (tx) => {
- // New-world folds claim every person, keeping concurrent lifecycle operations
- // (other merges, the delete saga) off the targets and sources until commit.
- if (this.tombstoneEnabled()) {
- await tx.claimLifecycleMarks(
- lifecycleOpId,
- currentTarget.team_id,
- [
- { personId: currentTarget.id, personUuid: currentTarget.uuid, role: 'target' },
- ...mergeSources.map((source, index) => ({
- personId: source.id,
- personUuid: source.uuid,
- role: 'source' as const,
- ordinal: index,
- })),
- ],
- this.targetDistinctId
- )
- if (!(await tx.isPersonLive(currentTarget, this.targetDistinctId))) {
- throw new MergeFoldConflictError('Fold target was deleted concurrently')
+ let pendingAtRead = new Map<string, PendingPersonChanges | null>()
+ const [survivorRow, survivorUpdate, kafkaMessages] = await this.inTransaction(
+ 'mergePeopleFold',
+ async (tx): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> => {
+ // New-world folds claim every person, keeping concurrent lifecycle operations
+ // (other merges, the delete saga) off the targets and sources until commit.
+ if (this.tombstoneEnabled()) {
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ currentTarget.team_id,
+ [
+ { personId: currentTarget.id, personUuid: currentTarget.uuid, role: 'target' },
+ ...mergeSources.map((source, index) => ({
+ personId: source.id,
+ personUuid: source.uuid,
+ role: 'source' as const,
+ ordinal: index,
+ })),
+ ],
+ this.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(currentTarget, this.targetDistinctId))) {
+ throw new MergeFoldConflictError('Fold target was deleted concurrently')
+ }
}
- }
- const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)
-
- let person = currentTarget
- let updateMessages: PersonMessage[] = []
- if (mergeSources.length > 0) {
- ;[person, updateMessages] = await tx.updatePersonForMerge(
- currentTarget,
- {
+ if (!this.lockedOutcomeEnabled()) {
+ return await this.deferredOutcomeFold(
+ tx,
+ currentTarget,
+ mergeSources,
+ missingSources,
+ lifecycleOpId
+ )
+ }
+ // Before the person rows lock, as in mergePeople.
+ if (mergeSources.length > 0) {
+ await tx.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamId,
+ mergeSources.map((source) => source.id),
+ currentTarget.id,
+ this.targetDistinctId
+ )
+ }
+ // The person rows first, before the moves take key-share locks on them, so two merges that share a
+ // person cannot deadlock; the locks then span the merge.
+ const rows =
+ mergeSources.length > 0
+ ? await this.lockMergeRows(
+ tx,
+ currentTarget,
+ mergeSources,
+ (role) => new MergeFoldConflictError(`Fold ${role} was deleted concurrently`)
+ )
+ : undefined
+ const moveMessages = await this.moveFoldDistinctIds(tx, currentTarget, mergeSources, missingSources)
+
+ let survivor = currentTarget
+ let outcome: MergePersonUpdate | null = null
+ let survivorMessages: PersonMessage[] = []
+ let deleteMessages: PersonMessage[] = []
+ if (rows) {
+ // Right before the write, so a change this pod made during the moves counts as pending.
+ const { changes, createdAt, pending } = this.mergeOutcome(rows, currentTarget, mergeSources)
+ pendingAtRead = pending
+ const changesWritten: MergePersonUpdate = {
created_at: createdAt,
- properties: updatedTempPerson.properties,
+ properties: changes.toSet,
+ properties_to_set_once: changes.toSetOnce,
+ properties_to_unset: changes.toUnset,
is_identified: true,
- version,
- },
- this.targetDistinctId
- )
- }
-
- const moveResult = await tx.moveDistinctIdsFromPersons(mergeSources, currentTarget, this.targetDistinctId)
- 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')
- }
- this.recordOverrideCount('bothExistMove', moveResult.distinctIdsMoved.length)
-
- const addMessages: PersonMessage[] = []
- for (const pair of missingSources) {
- // See mergeSingle for the distinctIdVersion logic.
- const distinctIdVersion = 1
- this.recordOverrideCount('fold')
- addMessages.push(...(await tx.addDistinctId(person, pair.distinctId, distinctIdVersion)))
- }
-
- let deleteMessages: PersonMessage[] = []
- if (mergeSources.length > 0) {
- await tx.updateCohortsAndFeatureFlagsForMergeBatch(
- teamId,
- mergeSources.map((source) => source.id),
- currentTarget.id,
- this.targetDistinctId
- )
- deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)
- }
+ }
+ // The survivor's write and the sources' delete commit together, every row locked since the read.
+ let written: boolean
+ ;[survivor, survivorMessages, written] = await tx.updatePersonForMerge(
+ currentTarget,
+ changesWritten,
+ this.targetDistinctId
+ )
+ outcome = written ? changesWritten : null
+ deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)
+ }
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
+ if (this.tombstoneEnabled()) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
+ }
+ return [survivor, outcome, [...moveMessages, ...survivorMessages, ...deleteMessages]]
}
- return [person, [...updateMessages, ...moveResult.messages, ...addMessages, ...deleteMessages]]
- })
+ )
+ // After the commit, so a rollback leaves nothing of the merge in the cache: the survivor's entry takes the
+ // row, and the sources' entries are released.
+ const mergedPerson = survivorUpdate
+ ? this.store.takeMergedRow(
+ survivorRow,
+ this.targetDistinctId,
+ survivorUpdate,
+ pendingAtRead.get(currentTarget.id) ?? null,
+ this.batchId
+ )
+ : survivorRow
+ for (const source of mergeSources) {
+ this.store.releaseMergedSource(source.team_id, source.id, pendingAtRead.get(source.id) ?? null)
+ }
this.flushOverrideCounts()
mergeFoldExecutedCounter.inc()
@@ -751,8 +898,6 @@ export class PostgresPersonMerge {
otherPerson: InternalPerson
otherPersonDistinctId: string
}): Promise<MergePersonsResult> {
- const olderCreatedAt = DateTime.min(mergeInto.created_at, otherPerson.created_at)
-
// $merge_dangerously has no restrictions; $create_alias and $identify
// will not merge a user who's already identified into anyone else.
const mergeAllowed = this.request.allowIdentifiedSources || !otherPerson.is_identified
@@ -783,21 +928,11 @@ export class PostgresPersonMerge {
// that guarantees consistency of how properties are processed regardless of persons created_at timestamps and rollout state
// we're calling aliasDeprecated as we need to refresh the persons info completely first
- const mergedProperties: Properties = { ...otherPerson.properties, ...mergeInto.properties }
- const propertyUpdates = refineEventOps(this.request.eventOps, mergedProperties, this.policy.updateAllProperties)
-
- // Create a temporary person object to apply property updates to
- const tempPerson: InternalPerson = { ...mergeInto, properties: mergedProperties }
- const [updatedTempPerson, _] = applyEventPropertyUpdates(propertyUpdates, tempPerson)
- const properties = updatedTempPerson.properties
-
const result = await this.handleMergeTransaction(
mergeInto,
mergeIntoDistinctId,
otherPerson,
- otherPersonDistinctId,
- olderCreatedAt, // Keep the oldest created_at (i.e. the first time we've seen either person)
- properties
+ otherPersonDistinctId
)
if (result.success) {
@@ -856,9 +991,7 @@ export class PostgresPersonMerge {
private async executeTransaction(
currentTargetPerson: InternalPerson,
- currentSourcePerson: InternalPerson,
- createdAt: DateTime,
- properties: Properties
+ currentSourcePerson: InternalPerson
): Promise<PersonMergeResult> {
try {
mergeTxnAttemptCounter
@@ -871,92 +1004,118 @@ export class PostgresPersonMerge {
this.discardOverrideCounts()
const lifecycleOpId = lifecycleOpIdFromEvent(this.teamId, this.request.eventUuid)
- const [mergedPerson, kafkaMessages] = await this.inTransaction('mergePeople', async (tx) => {
- // New-world merges claim both persons in the lifecycle mark table: at
- // most one live operation (merge or delete saga) may hold a person, so
- // neither can be tombstoned under this transaction. The marks say
- // nothing about tombstones committed before the claim, so assert both
- // persons are still live while holding them. Liveness checks are
- // separate statements because a claim that waited on the mark index
- // resumes with a stale snapshot.
- if (this.tombstoneEnabled()) {
- await tx.claimLifecycleMarks(
- lifecycleOpId,
- currentTargetPerson.team_id,
- [
- {
- personId: currentTargetPerson.id,
- personUuid: currentTargetPerson.uuid,
- role: 'target',
- },
- {
- personId: currentSourcePerson.id,
- personUuid: currentSourcePerson.uuid,
- role: 'source',
- ordinal: 0,
- },
- ],
- this.targetDistinctId
- )
- if (!(await tx.isPersonLive(currentTargetPerson, this.targetDistinctId))) {
- throw new TargetPersonNotFoundError('Target person was deleted concurrently')
+ let sourcePending: PendingPersonChanges | null = null
+ let targetPending: PendingPersonChanges | null = null
+ const [survivorRow, survivorUpdate, kafkaMessages] = await this.inTransaction(
+ 'mergePeople',
+ async (tx): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> => {
+ // New-world merges claim both persons in the lifecycle mark table: at
+ // most one live operation (merge or delete saga) may hold a person, so
+ // neither can be tombstoned under this transaction. The marks say
+ // nothing about tombstones committed before the claim, so assert both
+ // persons are still live while holding them. Liveness checks are
+ // separate statements because a claim that waited on the mark index
+ // resumes with a stale snapshot.
+ if (this.tombstoneEnabled()) {
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ currentTargetPerson.team_id,
+ [
+ {
+ personId: currentTargetPerson.id,
+ personUuid: currentTargetPerson.uuid,
+ role: 'target',
+ },
+ {
+ personId: currentSourcePerson.id,
+ personUuid: currentSourcePerson.uuid,
+ role: 'source',
+ ordinal: 0,
+ },
+ ],
+ this.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(currentTargetPerson, this.targetDistinctId))) {
+ throw new TargetPersonNotFoundError('Target person was deleted concurrently')
+ }
+ if (!(await tx.isPersonLive(currentSourcePerson, this.targetDistinctId))) {
+ throw new SourcePersonNotFoundError('Source person was deleted concurrently')
+ }
}
- if (!(await tx.isPersonLive(currentSourcePerson, this.targetDistinctId))) {
- throw new SourcePersonNotFoundError('Source person was deleted concurrently')
+ if (!this.lockedOutcomeEnabled()) {
+ return await this.deferredOutcomeTransaction(
+ tx,
+ currentTargetPerson,
+ currentSourcePerson,
+ lifecycleOpId
+ )
}
- }
- const [person, updatePersonMessages] = await tx.updatePersonForMerge(
- currentTargetPerson,
- {
+ // Before the person rows lock, so the locks do not span this step. It locks no person row: the
+ // override foreign key is checked at commit, and cohort rows have none.
+ // TODO: Doesn't this table need to add updates to CH too?
+ await tx.updateCohortsAndFeatureFlagsForMerge(
+ currentSourcePerson.team_id,
+ currentSourcePerson.id,
+ currentTargetPerson.id,
+ this.targetDistinctId
+ )
+ // The person rows first, before the moves take key-share locks on them, so two merges that
+ // share a person cannot deadlock; the locks then span the merge.
+ const rows = await this.lockMergeRows(tx, currentTargetPerson, [currentSourcePerson], (role) =>
+ role === 'target'
+ ? new TargetPersonNotFoundError('Target person was deleted concurrently')
+ : new SourcePersonNotFoundError('Source person was deleted concurrently')
+ )
+ // Move distinct IDs early to establish ownership of the source person quickly.
+ // This reduces contention when multiple concurrent merges target the same source,
+ // as subsequent lookups via distinct ID will fail faster.
+ const allDistinctIdMessages = await this.moveDistinctIdsBasedOnMode(
+ tx,
+ currentSourcePerson,
+ currentTargetPerson
+ )
+
+ // Right before the write, so a change this pod made during the moves counts as pending.
+ const { changes, createdAt, pending } = this.mergeOutcome(rows, currentTargetPerson, [
+ currentSourcePerson,
+ ])
+ sourcePending = pending.get(currentSourcePerson.id) ?? null
+ targetPending = pending.get(currentTargetPerson.id) ?? null
+ const outcome: MergePersonUpdate = {
created_at: createdAt,
- properties: properties,
+ properties: changes.toSet,
+ properties_to_set_once: changes.toSetOnce,
+ properties_to_unset: changes.toUnset,
is_identified: true,
+ }
- // By using the max version between the two Persons, we ensure that if
- // this Person is later split, we can use `this_person.version + 1` for
- // any split-off Persons and know that *that* version will be higher than
- // any previously deleted Person, and so the new Person row will "win" and
- // "undelete" the Person.
- //
- // For example:
- // - Merge Person_1(version:7) into Person_2(version:2)
- // - Person_1 is deleted
- // - Person_2 attains version 8 via this code below
- // - Person_2 is later split, which attempts to re-create Person_1 by using
- // its `distinct_id` to generate the deterministic Person UUID.
- // That new Person_1 will have a version _at least_ as high as 8, and
- // so any previously existing rows in CH or otherwise from
- // Person_1(version:7) will "lose" to this new Person_1.
- version: Math.max(currentTargetPerson.version, currentSourcePerson.version) + 1,
- },
- this.targetDistinctId
- )
-
- // Move distinct IDs first to establish ownership of the source person quickly.
- // This reduces contention when multiple concurrent merges target the same source,
- // as subsequent lookups via distinct ID will fail faster.
- const allDistinctIdMessages = await this.moveDistinctIdsBasedOnMode(
- tx,
- currentSourcePerson,
- currentTargetPerson
- )
-
- // Update cohorts and feature flags after distinct IDs are moved.
- // The source person row still exists (deleted below), so FK constraints are satisfied.
- // TODO: Doesn't this table need to add updates to CH too?
- await tx.updateCohortsAndFeatureFlagsForMerge(
- currentSourcePerson.team_id,
- currentSourcePerson.id,
- currentTargetPerson.id,
- this.targetDistinctId
- )
-
- const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.targetDistinctId)
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
+ // The survivor's write and the source's delete commit together, both rows locked since the read.
+ const [survivor, survivorMessages, written] = this.dropOversizedOutcome
+ ? this.store.rejectMergeOutcome(currentTargetPerson, outcome, this.targetDistinctId)
+ : await tx.updatePersonForMerge(currentTargetPerson, outcome, this.targetDistinctId)
+ const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.targetDistinctId)
+ if (this.tombstoneEnabled()) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
+ }
+ return [
+ survivor,
+ written ? outcome : null,
+ [...allDistinctIdMessages, ...survivorMessages, ...deletePersonMessages],
+ ]
}
- return [person, [...updatePersonMessages, ...allDistinctIdMessages, ...deletePersonMessages]]
- })
+ )
+ // After the commit, so a rollback leaves nothing of the merge in the cache: the survivor's entry takes
+ // the row, and the source's entry is released.
+ const mergedPerson = survivorUpdate
+ ? this.store.takeMergedRow(
+ survivorRow,
+ this.targetDistinctId,
+ survivorUpdate,
+ targetPending,
+ this.batchId
+ )
+ : survivorRow
+ this.store.releaseMergedSource(currentSourcePerson.team_id, currentSourcePerson.id, sourcePending)
this.flushOverrideCounts()
mergeTxnSuccessCounter
@@ -976,6 +1135,8 @@ export class PostgresPersonMerge {
void this.producePersonMergeEvent(currentSourcePerson, mergedPerson).catch(() => {})
return mergeSuccess(mergedPerson, kafkaAck, true)
} catch (error) {
+ // The transaction rolled back, so the ids its move re-pointed at the target are the source's again.
+ this.purgeMovedDistinctIds()
// Map exceptions to result types - these will cause transaction rollback
if (error instanceof SourcePersonNotFoundError) {
return mergeError(error)
@@ -1082,6 +1243,7 @@ export class PostgresPersonMerge {
allDistinctIdMessages.push(...distinctIdResult.messages)
hasProcessedAnyDistinctIds = true
this.recordOverrideCount('bothExistMove', distinctIdResult.distinctIdsMoved.length)
+ this.movedDistinctIds.push(...distinctIdResult.distinctIdsMoved)
// Check if we moved fewer than the batch size, indicating we're done
hasMore = distinctIdResult.distinctIdsMoved.length >= batchSize
@@ -1114,6 +1276,9 @@ export class PostgresPersonMerge {
}
const allDistinctIdMessages = distinctIdResult.success ? distinctIdResult.messages : []
+ if (distinctIdResult.success) {
+ this.movedDistinctIds.push(...distinctIdResult.distinctIdsMoved)
+ }
// If moved count equals the per-call limit, verify if it's a partial move by checking remaining IDs
const movedCount = distinctIdResult.success ? distinctIdResult.distinctIdsMoved.length : 0
@@ -1136,25 +1301,122 @@ export class PostgresPersonMerge {
return allDistinctIdMessages
}
+ private async moveFoldDistinctIds(
+ tx: PersonsStoreTransactionForBatch,
+ target: InternalPerson,
+ mergeSources: InternalPerson[],
+ missingSources: MergePersonsSource[]
+ ): Promise<PersonMessage[]> {
+ const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)
+
+ const moveResult = await tx.moveDistinctIdsFromPersons(mergeSources, target, this.targetDistinctId)
+ 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')
+ }
+ this.recordOverrideCount('bothExistMove', moveResult.distinctIdsMoved.length)
+ this.movedDistinctIds.push(...moveResult.distinctIdsMoved)
+
+ const addMessages: PersonMessage[] = []
+ for (const pair of missingSources) {
+ // See mergeSingle for the distinctIdVersion logic.
+ const distinctIdVersion = 1
+ this.recordOverrideCount('fold')
+ addMessages.push(...(await tx.addDistinctId(target, pair.distinctId, distinctIdVersion)))
+ }
+ return [...moveResult.messages, ...addMessages]
+ }
+
+ /** The merge for a team off the locked-outcome allowlist: the survivor is queued for the flush and no person row is locked. */
+ private async deferredOutcomeTransaction(
+ tx: PersonsStoreTransactionForBatch,
+ target: InternalPerson,
+ source: InternalPerson,
+ lifecycleOpId: string
+ ): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> {
+ const allDistinctIdMessages = await this.moveDistinctIdsBasedOnMode(tx, source, target)
+ const survivor = this.store.deferMergeOutcome(
+ target,
+ this.deferredOutcome(target, [source]),
+ this.targetDistinctId,
+ this.batchId
+ )
+ await tx.updateCohortsAndFeatureFlagsForMerge(source.team_id, source.id, target.id, this.targetDistinctId)
+ const deletePersonMessages = await tx.deletePerson(source, this.targetDistinctId)
+ if (this.tombstoneEnabled()) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
+ }
+ return [survivor, null, [...allDistinctIdMessages, ...deletePersonMessages]]
+ }
+
+ private async deferredOutcomeFold(
+ tx: PersonsStoreTransactionForBatch,
+ target: InternalPerson,
+ mergeSources: InternalPerson[],
+ missingSources: MergePersonsSource[],
+ lifecycleOpId: string
+ ): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> {
+ const moveMessages = await this.moveFoldDistinctIds(tx, target, mergeSources, missingSources)
+ let survivor = target
+ let deleteMessages: PersonMessage[] = []
+ if (mergeSources.length > 0) {
+ survivor = this.store.deferMergeOutcome(
+ target,
+ this.deferredOutcome(target, mergeSources),
+ this.targetDistinctId,
+ this.batchId
+ )
+ await tx.updateCohortsAndFeatureFlagsForMergeBatch(
+ this.teamId,
+ mergeSources.map((source) => source.id),
+ target.id,
+ this.targetDistinctId
+ )
+ deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)
+ }
+ if (this.tombstoneEnabled()) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
+ }
+ return [survivor, null, [...moveMessages, ...deleteMessages]]
+ }
+
+ /**
+ * An oversized outcome aborts the transaction, so it rolls back, and one rerun commits the merge without the
+ * outcome, as the flush drops an oversized write. The rerun reads the rows afresh.
+ */
+ private async executeTransactionOrDropOversized(
+ target: InternalPerson,
+ source: InternalPerson
+ ): Promise<PersonMergeResult> {
+ try {
+ return await this.executeTransaction(target, source)
+ } catch (error) {
+ if (!(error instanceof MergeOutcomeOversizedError) || this.dropOversizedOutcome) {
+ throw error
+ }
+ this.dropOversizedOutcome = true
+ return await this.executeTransaction(target, source)
+ }
+ }
+
private async handleMergeTransaction(
targetPerson: InternalPerson,
targetDistinctId: string,
sourcePerson: InternalPerson,
sourceDistinctId: string,
- createdAt: DateTime,
- properties: Properties,
maxRetries: number = 5
): Promise<PersonMergeResult> {
let currentTargetPerson = targetPerson
let currentSourcePerson = sourcePerson
for (let attempt = 0; attempt <= maxRetries; attempt++) {
- const result = await this.executeTransaction(
- currentTargetPerson,
- currentSourcePerson,
- createdAt,
- properties
- )
+ const result = await this.executeTransactionOrDropOversized(currentTargetPerson, currentSourcePerson)
if (result.success) {
return result
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 21ea782119a4..2df4f836054b 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -17,6 +17,7 @@ import { PersonContext } from './person-context'
import {
PersonMergeCallFailedError,
PersonMergeLimitExceededError,
+ PersonMergeRaceConditionError,
PersonMergeResponseMismatchError,
PersonMergeResult,
PersonMergeUnsettledError,
@@ -303,14 +304,16 @@ export class PersonMergeService {
[ConnectError, PersonMergeResponseMismatchError]
)
} catch (error) {
- if (!(error instanceof PersonMergeUnsettledError)) {
+ if (!(error instanceof PersonMergeUnsettledError || error instanceof PersonMergeRaceConditionError)) {
throw error
}
- // Retries exhausted without a settled answer: dropped with the
- // race warning, as Postgres drops a persistent conflict. The
- // drop also counts on the claim-drop series, so the drop rate
- // reads whole across both backends.
- mergeUnsettledCounter.inc()
+ // Retries exhausted without a settled answer, or a creation race that
+ // outlasted them: dropped with the race warning, as Postgres drops a
+ // persistent conflict. The drop also counts on the claim-drop series,
+ // so the drop rate reads whole across both backends.
+ if (error instanceof PersonMergeUnsettledError) {
+ mergeUnsettledCounter.inc()
+ }
mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()
const warningAck = emitIngestionWarning(this.context.outputs, teamId, {
type: 'merge_race_condition',
@@ -323,9 +326,10 @@ export class PersonMergeService {
pipelineStep: 'person-merge',
alwaysSend: true,
}).then(() => undefined)
- logger.warn('🤔', 'merge unsettled through every retry; dropped with the race warning', {
+ logger.warn('🤔', 'merge unresolved through every retry; dropped with the race warning', {
team_id: teamId,
distinct_id: mergeIntoDistinctId,
+ error: error.constructor.name,
})
return mergeSuccess(undefined, warningAck, true)
}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-types.ts b/nodejs/src/ingestion/common/persons/person-merge-types.ts
index 330ff5b2b615..61722ee2b24a 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-types.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-types.ts
@@ -56,6 +56,14 @@ export class PersonMergeUnsettledError extends PersonMergeError {
readonly type = 'UNSETTLED' as const
}
+/** A merge outcome over the properties size limit. Its statement aborted the merge's transaction. */
+export class MergeOutcomeOversizedError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'MergeOutcomeOversizedError'
+ }
+}
+
export class PersonMergeRaceConditionError extends PersonMergeError {
readonly type = 'RACE_CONDITION' as const
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 bf6fdc143cd1..bb12fc927f18 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 { MergePersonUpdate } from '~/common/persons/person-update-batch'
import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
@@ -32,7 +33,7 @@ export interface PersonsStoreTransactionForBatch {
updatePersonForMerge(
person: InternalPerson,
- update: Partial<InternalPerson>,
+ update: MergePersonUpdate,
distinctId: string
): Promise<[InternalPerson, PersonMessage[], boolean]>
@@ -56,6 +57,9 @@ export interface PersonsStoreTransactionForBatch {
/** Whether the person is live; only meaningful while holding its lifecycle mark. */
isPersonLive(person: InternalPerson, distinctId: string): Promise<boolean>
+ /** The target and sources are row-locked, in ascending id order, until the transaction ends. */
+ readMergeRows(teamId: number, targetId: string, sourceIds: string[], distinctId: string): Promise<InternalPerson[]>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
moveDistinctIds(
@@ -183,10 +187,10 @@ export class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactio
updatePersonForMerge(
person: InternalPerson,
- update: Partial<InternalPerson>,
+ update: MergePersonUpdate,
distinctId: string
): Promise<[InternalPerson, PersonMessage[], boolean]> {
- return this.tx.updatePersonForMerge(person, update, distinctId, this.batchId)
+ return this.tx.updatePersonForMerge(person, update, distinctId)
}
updatePersonWithPropertiesDiffForUpdate(
@@ -229,6 +233,15 @@ export class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactio
return this.tx.isPersonLive(person, distinctId)
}
+ readMergeRows(
+ teamId: number,
+ targetId: string,
+ sourceIds: string[],
+ distinctId: string
+ ): Promise<InternalPerson[]> {
+ return this.tx.readMergeRows(teamId, targetId, sourceIds, distinctId)
+ }
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return this.tx.addDistinctId(person, distinctId, version, this.batchId)
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
index 8067634b535b..911b1be637f6 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { MergePersonUpdate } from '~/common/persons/person-update-batch'
import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
@@ -51,11 +52,10 @@ export class PersonsStoreTransaction {
async updatePersonForMerge(
person: InternalPerson,
- update: Partial<InternalPerson>,
- distinctId: string,
- batchId: number
+ update: MergePersonUpdate,
+ distinctId: string
): Promise<[InternalPerson, PersonMessage[], boolean]> {
- return await this.store.updatePersonForMerge(person, update, distinctId, batchId, this.tx)
+ return await this.store.updatePersonForMerge(person, update, distinctId, this.tx)
}
async updatePersonWithPropertiesDiffForUpdate(
@@ -100,6 +100,15 @@ export class PersonsStoreTransaction {
return await this.store.isPersonLive(person, distinctId, this.tx)
}
+ async readMergeRows(
+ teamId: number,
+ targetId: string,
+ sourceIds: string[],
+ distinctId: string
+ ): Promise<InternalPerson[]> {
+ return await this.store.readMergeRows(teamId, targetId, sourceIds, distinctId, this.tx)
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 3354c5951bf4..5c9a907fe871 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -154,6 +154,8 @@ export type IngestionConsumerConfig = {
PERSON_BATCH_WRITING_MAX_CONCURRENT_UPDATES: number
PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: number
PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: number
+ // Teams whose batch person writes merge per key with the row. Comma-separated team IDs, or '*'; empty means none.
+ PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST: string
/** Concurrent RPC fan-out in the personhog store (batch fetches and flush). */
PERSONHOG_STORE_MAX_CONCURRENT_UPDATES: number
PERSONS_PREFETCH_ENABLED: boolean
@@ -194,6 +196,9 @@ export type IngestionConsumerConfig = {
// whose creates revive a tombstoned key. Every environment rolled this out to all teams, so
// '*' is the default. Comma-separated team IDs, or '*' for all teams; empty means no teams.
PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
+ // Teams whose merges lock the person rows and write the survivor in the transaction; other teams queue it for
+ // the next flush. Enable after PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST. Team IDs, or '*'; empty means none.
+ PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST: string
// Re-emit committed distinct id mappings for merge events that arrive already satisfied,
// debounced per (team, distinct id). Heals ClickHouse mapping rows lost to a crash between
// a merge's commit and its produce; see MergeMappingDebounce for why the cache is in-memory.
@@ -356,6 +361,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,
PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: 5,
PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: 50,
+ PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST: '',
PERSONHOG_STORE_MAX_CONCURRENT_UPDATES: 10,
PERSONS_PREFETCH_ENABLED: false,
@@ -378,6 +384,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '*',
+ PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST: '',
PERSON_MERGE_NOOP_MAPPING_EMISSION_ENABLED: false,
PERSON_MERGE_NOOP_MAPPING_EMISSION_CACHE_SIZE: 500_000,
PERSON_MERGE_NOOP_MAPPING_EMISSION_TTL_MS: 60 * 60 * 1000,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 05e5c1364dda..fb3f95e82eea 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -239,6 +239,7 @@ export class IngestionConsumer {
optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
+ mergeLockedOutcomeTeamAllowlist: this.config.PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST,
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
index 21a8662ee948..bb2d3c8c1600 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
@@ -252,6 +252,7 @@ describe('ErrorTrackingPipeline', () => {
fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
createPerson: jest.fn(),
updatePerson: jest.fn(),
+ handleOversizedPersonProperties: jest.fn(),
updatePersonAssertVersion: jest.fn(),
updatePersonsBatch: jest.fn(),
deletePerson: jest.fn(),
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 09c41b8a6fb1..d4ce6800eb69 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -232,6 +232,7 @@ export class IngestionApiServer implements NodeServer {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
+ personBatchWritePerKeyTeamAllowlist: this.config.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
@@ -347,6 +348,7 @@ export class IngestionApiServer implements NodeServer {
optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
+ mergeLockedOutcomeTeamAllowlist: this.config.PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST,
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index 1353eb1399f2..bca3d7a69657 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -224,6 +224,7 @@ export class IngestionGeneralServer implements NodeServer {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
+ personBatchWritePerKeyTeamAllowlist: this.config.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.ts
index 35159cde7b9c..5977a36fc591 100644
--- a/nodejs/tests/helpers/ingestion-e2e.ts
+++ b/nodejs/tests/helpers/ingestion-e2e.ts
@@ -424,6 +424,9 @@ export async function createIngestionTestInfra(
...getDefaultMetricsIngestionConsumerConfig(),
...getDefaultSessionRecordingConfig(),
...getDefaultSessionRecordingApiConfig(),
+ // The suites here assert the rolled-out behavior.
+ PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST: '*',
+ PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST: '*',
...configOverrides,
}
@@ -450,6 +453,7 @@ export async function createIngestionTestInfra(
const postgresPersonRepository = new PostgresPersonRepository(postgres, {
calculatePropertiesSize: serverConfig.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
personMergeTombstoneTeamAllowlist: serverConfig.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
+ personBatchWritePerKeyTeamAllowlist: serverConfig.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
diff --git a/nodejs/tests/ingestion/person-state-batch.serial.test.ts b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
index ea5762db1880..8391feb69dbd 100644
--- a/nodejs/tests/ingestion/person-state-batch.serial.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
@@ -126,6 +126,21 @@ async function createPerson(
return result.person
}
+/** Whether another connection could lock the person row right now. */
+function rowLockState(hub: Hub, id: string): Promise<string> {
+ return hub.postgres
+ .query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT id FROM posthog_person WHERE id = $1 FOR UPDATE NOWAIT',
+ [id],
+ 'lockProbe'
+ )
+ .then(
+ () => 'free',
+ (error: Error) => (error.message.includes('could not obtain lock') ? 'locked' : error.message)
+ )
+}
+
async function flushPersonStoreToKafka(
kafkaProducer: KafkaProducerWrapper,
personStore: PersonsStoreForBatch,
@@ -1115,7 +1130,9 @@ describe('PersonState.processEvent()', () => {
}
expect(personRepository.fetchPerson).toHaveBeenCalledTimes(1)
- expect(personRepository.updatePerson).toHaveBeenCalledTimes(2)
+ // The batch and the single-person fallback both miss the merged-away row; the refreshed update lands.
+ expect(personRepository.updatePersonsBatch).toHaveBeenCalledTimes(3)
+ expect(personRepository.updatePerson).not.toHaveBeenCalled()
// verify Postgres persons
const persons = sortPersons(await fetchPostgresPersonsH())
@@ -2127,6 +2144,660 @@ describe('PersonState.processEvent()', () => {
expect(clickHouseDistinctIds).toEqual(expect.arrayContaining([oldUserDistinctId, newUserDistinctId]))
})
+ it(`merge writes only the keys it changes on the survivor, including the event's $unset`, async () => {
+ await createPerson(hub, timestamp, { a: 1, b: 2 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ // `nested` is object-valued and unchanged, so it must not travel as a set.
+ await createPerson(
+ hub,
+ timestamp2,
+ { b: 3, c: 4, d: 5, constructor: 'x', nested: { k: [1, 2] } },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ newUserUuid,
+ { distinctId: newUserDistinctId }
+ )
+
+ const mergeService = personMergeService({
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $set: { d: 6 }, $unset: ['c', 'constructor'], $anon_distinct_id: oldUserDistinctId },
+ })
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ // The survivor's own key (b) stays out; the source's key (a) only fills a gap; a prototype-named key unsets like any other.
+ expect(personRepository.updatePersonsBatch).toHaveBeenCalledWith(
+ [
+ expect.objectContaining({
+ uuid: newUserUuid,
+ properties_to_set: { d: 6 },
+ properties_to_set_once: { a: 1 },
+ properties_to_unset: ['c', 'constructor'],
+ }),
+ ],
+ expect.anything()
+ )
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({
+ uuid: newUserUuid,
+ properties: { a: 1, b: 3, d: 6, nested: { k: [1, 2] } },
+ })
+ })
+
+ it(`a merge does not replay a set this pod already flushed over another pod's newer value`, async () => {
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { own: 'x' }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const podA = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const source = await podA.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await podA.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'v1' }, [], {}, oldUserDistinctId, 0)
+ await podA.flush()
+ const podB = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const sourceB = await podB.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await podB.updatePersonWithPropertiesDiffForUpdate(sourceB!, { k: 'v2' }, [], {}, oldUserDistinctId, 0)
+ await podB.flush()
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ podA
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { own: 'x', k: 'v2' } })
+ })
+
+ it(`a merge moves cohorts and flags before it locks the persons, and holds both row locks before it moves distinct ids`, async () => {
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { own: 'x' }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const lockState = (id: string): Promise<string> => rowLockState(hub, id)
+ const moveDistinctIds = personRepository.moveDistinctIds.bind(personRepository)
+ const updateCohortsAndFeatureFlags =
+ personRepository.updateCohortsAndFeatureFlagsForMerge.bind(personRepository)
+ const seenAtCohorts: string[] = []
+ jest.spyOn(personRepository, 'updateCohortsAndFeatureFlagsForMerge').mockImplementationOnce(
+ async (team, sourceId, targetId, tx) => {
+ seenAtCohorts.push(await lockState(sourceId), await lockState(targetId))
+ return updateCohortsAndFeatureFlags(team, sourceId, targetId, tx)
+ }
+ )
+ const seen: string[] = []
+ jest.spyOn(personRepository, 'moveDistinctIds').mockImplementationOnce(
+ async (source, target, limit, tx) => {
+ seen.push(await lockState(source.id), await lockState(target.id))
+ return moveDistinctIds(source, target, limit, tx)
+ }
+ )
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ expect(seenAtCohorts).toEqual(['free', 'free'])
+ expect(seen).toEqual(['locked', 'locked'])
+ })
+
+ it(`a folded merge moves cohorts and flags before it locks the persons`, async () => {
+ const secondSourceDistinctId = 'fold-second-source'
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(
+ hub,
+ timestamp,
+ { b: 2 },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ uuidFromDistinctId(teamId, secondSourceDistinctId),
+ { distinctId: secondSourceDistinctId }
+ )
+ await createPerson(hub, timestamp2, { own: 'x' }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const updateBatch = personRepository.updateCohortsAndFeatureFlagsForMergeBatch.bind(personRepository)
+ const seenAtCohorts: string[] = []
+ jest.spyOn(personRepository, 'updateCohortsAndFeatureFlagsForMergeBatch').mockImplementationOnce(
+ async (team, sourceIds, targetId, tx) => {
+ for (const id of [...sourceIds, targetId]) {
+ seenAtCohorts.push(await rowLockState(hub, id))
+ }
+ return updateBatch(team, sourceIds, targetId, tx)
+ }
+ )
+ const eventUuid = new UUIDT().toString()
+
+ const result = await batchStore.mergePersons(
+ {
+ teamId,
+ targetDistinctId: newUserDistinctId,
+ sources: [
+ { distinctId: oldUserDistinctId, eventUuid },
+ { distinctId: secondSourceDistinctId, eventUuid: new UUIDT().toString() },
+ ],
+ eventOps: {
+ set: {},
+ setOnce: {},
+ unset: [],
+ denied: false,
+ shouldForceUpdate: true,
+ eventName: '$identify',
+ },
+ eventUuid,
+ allowIdentifiedSources: true,
+ mergeMode: createDefaultSyncMergeMode(),
+ createdAtMs: timestamp.toMillis(),
+ },
+ 0
+ )
+
+ expect(result.foldAborted).toBeUndefined()
+ expect(seenAtCohorts).toEqual(['free', 'free', 'free'])
+ })
+
+ it.each([
+ ["survives the merge's own write", {}],
+ [
+ "lands over the merge event's $set of the value the merge read, which does not replay",
+ { $set: { k: 'v1' } },
+ ],
+ ])(`a source's update flushed from another pod after a merge %s`, async (_case, eventProperties) => {
+ await createPerson(hub, timestamp, { k: 'v1' }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { own: 'x' }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ // Pod B holds the source's newer value, unflushed.
+ const podB = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const source = await podB.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await podB.updatePersonWithPropertiesDiffForUpdate(source!, { k: 'v2' }, [], {}, oldUserDistinctId, 0)
+
+ const podA = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { ...eventProperties, $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ podA
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+
+ // Pod B's flush finds the source gone and re-targets; pod A's flush comes after.
+ await podB.flush()
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { own: 'x', k: 'v2' } })
+
+ // Pod A's merged-in key landed, so it no longer waits to be written.
+ expect(podA.getCachedPersonForUpdateByPersonId(teamId, persons[0].id)?.properties_to_set_once).toEqual({})
+ })
+
+ it(`a merge that rolls back after its survivor write leaves the survivor's row untouched`, async () => {
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { own: 'x' }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ // The source's delete, after the survivor's write, fails the transaction on every attempt.
+ jest.spyOn(personRepository, 'deletePerson').mockRejectedValue(new Error('connection reset'))
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $set: { k: 'a' }, $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ await mergeService.handleIdentifyOrAlias().catch(() => undefined)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.map(({ uuid, properties, is_identified }) => ({ uuid, properties, is_identified }))).toEqual(
+ expect.arrayContaining([
+ { uuid: oldUserUuid, properties: { a: 1 }, is_identified: false },
+ { uuid: newUserUuid, properties: { own: 'x' }, is_identified: false },
+ ])
+ )
+ })
+
+ it.each([
+ ['holds the key', { k: 'target' }, {}],
+ ['lacks the key', {}, { k: 'pending' }],
+ ])(
+ `merge lands a source's key over the survivor's unflushed unset when the row %s`,
+ async (_case, row, set) => {
+ await createPerson(hub, timestamp, { k: 'source' }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, row, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const target = await batchStore.fetchForUpdate(teamId, newUserDistinctId, 0)
+ await batchStore.updatePersonWithPropertiesDiffForUpdate(target!, set, [], {}, newUserDistinctId, 0)
+ await batchStore.updatePersonWithPropertiesDiffForUpdate(target!, {}, ['k'], {}, newUserDistinctId, 0)
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { k: 'source' } })
+ }
+ )
+
+ it(`merge carries a property this batch set on the source but has not flushed yet`, async () => {
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { b: 2 }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+
+ // A $set on the source, buffered in the store; the row does not have it yet.
+ const source = await batchStore.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await batchStore.updatePersonWithPropertiesDiffForUpdate(
+ source!,
+ { pending: 'yes' },
+ [],
+ {},
+ oldUserDistinctId,
+ 0
+ )
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ // The committed merge cleared the source's entry before any flush could.
+ expect(batchStore.getCachedPersonForUpdateByPersonId(teamId, source!.id)).toBeUndefined()
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { a: 1, b: 2, pending: 'yes' } })
+ })
+
+ it(`a merge that rolls back after its move leaves the source's pending set for the survivor`, async () => {
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { b: 2 }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const source = await batchStore.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await batchStore.updatePersonWithPropertiesDiffForUpdate(
+ source!,
+ { pending: 'yes' },
+ [],
+ {},
+ oldUserDistinctId,
+ 0
+ )
+
+ // The first attempt fails after its move; the retry merges afresh.
+ jest.spyOn(personRepository, 'updateCohortsAndFeatureFlagsForMerge').mockImplementationOnce(() =>
+ Promise.reject(Object.assign(new Error('deadlock detected'), { code: '40P01' }))
+ )
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { a: 1, b: 2, pending: 'yes' } })
+ })
+
+ it(`a source merged away under a merge still gets its pending set onto the survivor`, async () => {
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, { b: 2 }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const elsewhere = await createPerson(
+ hub,
+ timestamp2,
+ { c: 3 },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ new UUIDT().toString(),
+ {
+ distinctId: 'elsewhere',
+ }
+ )
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const source = await batchStore.fetchForUpdate(teamId, oldUserDistinctId, 0)
+ await batchStore.updatePersonWithPropertiesDiffForUpdate(
+ source!,
+ { pending: 'yes' },
+ [],
+ {},
+ oldUserDistinctId,
+ 0
+ )
+
+ // Another pod merges the source elsewhere between this merge's fetch and its row locks; the locks find
+ // it gone, and the retry merges the person its distinct id names now.
+ jest.spyOn(personRepository, 'readMergeRows').mockImplementationOnce(async (...args) => {
+ await personRepository.inRawTransaction('elsewhere', async (tx) => {
+ await personRepository.moveDistinctIds(source!, elsewhere, undefined, tx)
+ await personRepository.deletePerson(source!, tx)
+ })
+ return await PostgresPersonRepository.prototype.readMergeRows.apply(personRepository, args)
+ })
+
+ const mergeService = personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, properties: { b: 2, c: 3, pending: 'yes' } })
+ })
+
+ it(`a merge chain in one batch carries the oldest birth and properties through the middle person`, async () => {
+ const oldest = DateTime.fromISO('2019-01-01T00:00:00.000Z').toUTC()
+ await createPerson(hub, oldest, { first: 1 }, {}, {}, teamId, null, false, new UUIDT().toString(), {
+ distinctId: 'oldest-anon',
+ })
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, {}, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
+ const merge = (event: Partial<PluginEvent>) =>
+ personMergeService(
+ event,
+ hub,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ batchStore
+ )
+
+ // oldest-anon into old-user, buffered; then old-user into new-user before that flushes.
+ const first = await merge({
+ event: '$identify',
+ distinct_id: oldUserDistinctId,
+ properties: { $anon_distinct_id: 'oldest-anon' },
+ }).handleIdentifyOrAlias()
+ expect(first.success).toBe(true)
+ const secondService = merge({
+ event: '$merge_dangerously',
+ distinct_id: newUserDistinctId,
+ properties: { alias: oldUserDistinctId },
+ })
+ const second = await secondService.handleIdentifyOrAlias()
+ expect(second.success).toBe(true)
+ if (!second.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, secondService.getContext().personStore, second.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ uuid: newUserUuid, created_at: oldest, properties: { first: 1 } })
+ })
+
+ it.each([
+ ['before its transaction', 'inTransaction'],
+ ['right before its row locks', 'readMergeRows'],
+ ])(`merge carries a property another writer lands on the source %s`, async (_when, boundary) => {
+ await createPerson(hub, timestamp, { a: 1 }, {}, {}, teamId, null, false, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ const target = await createPerson(hub, timestamp2, { b: 2 }, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+
+ // Another pod's flush lands on the source after the merge's reads.
+ const lateWrite = () =>
+ hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ `UPDATE posthog_person SET properties = properties || '{"late": "yes"}'::jsonb, version = version + 1
+ WHERE team_id = $1 AND uuid = $2`,
+ [teamId, oldUserUuid],
+ 'lateSourceWrite'
+ )
+ if (boundary === 'inTransaction') {
+ jest.spyOn(personRepository, 'inTransaction').mockImplementationOnce(async (description, body) => {
+ await lateWrite()
+ return await PostgresPersonRepository.prototype.inTransaction.call(
+ personRepository,
+ description,
+ body
+ )
+ })
+ } else {
+ jest.spyOn(personRepository, 'readMergeRows').mockImplementationOnce(async (...args) => {
+ await lateWrite()
+ return await PostgresPersonRepository.prototype.readMergeRows.apply(personRepository, args)
+ })
+ }
+
+ const mergeService = personMergeService({
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ })
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({ id: target.id, properties: { a: 1, b: 2, late: 'yes' } })
+ })
+
+ it(`joins both ids when another writer creates the anon person during a neither-exists merge`, async () => {
+ // The anon person lands on another pod before this merge's two-id create.
+ let raced = false
+ jest.spyOn(personRepository, 'createPerson').mockImplementation(async (...args) => {
+ if (!raced) {
+ raced = true
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+ }
+ return await PostgresPersonRepository.prototype.createPerson.apply(personRepository, args)
+ })
+
+ const mergeService = personMergeService({
+ event: '$identify',
+ distinct_id: oldUserDistinctId,
+ properties: { $anon_distinct_id: newUserDistinctId },
+ })
+ const result = await mergeService.handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected successful merge result')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const persons = sortPersons(await fetchPostgresPersonsH())
+ expect(persons.length).toEqual(1)
+ expect(persons[0].uuid).toEqual(newUserUuid)
+ const distinctIds = await fetchDistinctIdValues(hub.postgres, persons[0])
+ expect(distinctIds).toEqual(expect.arrayContaining([oldUserDistinctId, newUserDistinctId]))
+ })
+
+ it(`does not retry a neither-exists merge when the uuid's holder owns neither id`, async () => {
+ // A live person holds the target's uuid under a third id, so no retry can attach.
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, newUserUuid, {
+ distinctId: 'stranded-holder',
+ })
+ const created = jest.spyOn(personRepository, 'createPerson')
+
+ const mergeService = personMergeService({
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ })
+ const result = await mergeService.handleIdentifyOrAlias()
+
+ expect(result.success).toBe(true)
+ expect(created).toHaveBeenCalledTimes(1)
+ })
+
it(`handles race condition when other thread creates the user`, async () => {
await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, oldUserUuid, {
distinctId: oldUserDistinctId,
@@ -3637,32 +4308,20 @@ describe('PersonState.processEvent()', () => {
// Mock removeDistinctIdFromCache to verify it's called
const removeDistinctIdFromCacheSpy = jest.spyOn(batchStore, 'removeDistinctIdFromCache')
- // Mock moveDistinctIds to first move the distinct ID to person3 (simulating race condition), then succeed
- let moveDistinctIdsCalls = 0
- const originalMoveDistinctIds = batchStore.moveDistinctIds.bind(batchStore)
-
- // Mock the batch store method which is what gets called through the transaction wrapper
- const moveDistinctIdsSpy = jest
- .spyOn(batchStore, 'moveDistinctIds')
- .mockImplementation(async (source, target, distinctId, limit, tx) => {
- moveDistinctIdsCalls++
- if (moveDistinctIdsCalls === 1) {
- // Simulate the race condition: move firstUserDistinctId to person3
- // This simulates another process moving the distinct ID during the merge
+ // Another process moves firstUserDistinctId to person3 and deletes person1 between this merge's fetch
+ // and its row locks; the locks find person1 gone, and the retry merges person3 instead.
+ let lockCalls = 0
+ const readMergeRowsSpy = jest
+ .spyOn(personRepository, 'readMergeRows')
+ .mockImplementation(async (...args) => {
+ lockCalls++
+ if (lockCalls === 1) {
await personRepository.inRawTransaction('test', async (tx) => {
await personRepository.moveDistinctIds(person1, person3, undefined, tx)
await personRepository.deletePerson(person1, tx)
})
-
- // First call fails with SourcePersonNotFoundError (person1 no longer exists)
- return Promise.resolve({
- success: false,
- error: 'SourceNotFound',
- message: 'Source person no longer exists',
- })
}
- // Second call succeeds - call the original method
- return originalMoveDistinctIds(source, target, distinctId, limit, tx, 0)
+ return await PostgresPersonRepository.prototype.readMergeRows.apply(personRepository, args)
})
// Attempt to merge persons - this should trigger the retry logic
@@ -3676,8 +4335,8 @@ describe('PersonState.processEvent()', () => {
// Verify the cache was cleared during retry
expect(removeDistinctIdFromCacheSpy).toHaveBeenCalledWith(teamId, firstUserDistinctId)
- // Verify moveDistinctIds was called twice (first failed with person1, second succeeded with person3)
- expect(moveDistinctIdsSpy).toHaveBeenCalledTimes(2)
+ // The first attempt's locks found person1 gone; the retry locked person3.
+ expect(readMergeRowsSpy).toHaveBeenCalledTimes(2)
// Verify we got the target person back
expect(person).toMatchObject({
@@ -3720,28 +4379,18 @@ describe('PersonState.processEvent()', () => {
event: '$merge_dangerously',
})
- // Mock moveDistinctIds to first move the distinct ID to person3 (simulating race condition), then succeed
- let moveDistinctIdsCalls = 0
- const originalMoveDistinctIds = personRepository.moveDistinctIds
- const moveDistinctIdsSpy = jest
- .spyOn(personRepository, 'moveDistinctIds')
+ // Another process moves firstUserDistinctId to person3 and deletes person1 between this merge's fetch
+ // and its row locks; the locks find person1 gone, and the retry merges person3 instead.
+ let lockCalls = 0
+ const readMergeRowsSpy = jest
+ .spyOn(personRepository, 'readMergeRows')
.mockImplementation(async (...args) => {
- moveDistinctIdsCalls++
- if (moveDistinctIdsCalls === 1) {
- // Simulate the race condition: move firstUserDistinctId to person3
- // This simulates another process moving the distinct ID during the merge
- await originalMoveDistinctIds.call(personRepository, person1, person3)
+ lockCalls++
+ if (lockCalls === 1) {
+ await personRepository.moveDistinctIds(person1, person3)
await personRepository.deletePerson(person1)
-
- // First call fails with SourcePersonNotFoundError (person1 no longer exists)
- return Promise.resolve({
- success: false,
- error: 'SourceNotFound',
- message: 'Source person no longer exists',
- })
}
- // Second call succeeds - call the original method
- return originalMoveDistinctIds.call(personRepository, ...args)
+ return await PostgresPersonRepository.prototype.readMergeRows.apply(personRepository, args)
})
// Attempt to merge persons - this should trigger the retry logic
@@ -3752,8 +4401,8 @@ describe('PersonState.processEvent()', () => {
}
const person = result.person
- // Verify moveDistinctIds was called twice (first failed with person1, second succeeded with person3)
- expect(moveDistinctIdsSpy).toHaveBeenCalledTimes(2)
+ // The first attempt's locks found person1 gone; the retry locked person3.
+ expect(readMergeRowsSpy).toHaveBeenCalledTimes(2)
// Verify we got the target person back
expect(person).toMatchObject({
diff --git a/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
index 11e0499e7f63..563cbb6400ad 100644
--- a/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
+++ b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
@@ -71,8 +71,7 @@ describe('personhog shadow parity (e2e)', () => {
let kafkaProducer: KafkaProducerWrapper
let routerClient: PersonHogClient
let closeIdentity: () => void
- let personhogStore: PersonhogPersonsStore
- let pgStore: BatchWritingPersonsStore
+ let writeRepository: PersonHogPersonWriteRepository
let routing: RoutingPersonsStore
let personsDb: Pool = undefined as unknown as Pool
let organizationId: string
@@ -107,6 +106,23 @@ describe('personhog shadow parity (e2e)', () => {
),
})
+ /**
+ * One ingestion pod: its own caches over the shared databases and the
+ * shared personhog cluster, so two pods can interleave on one person.
+ */
+ const newPod = (): RoutingPersonsStore =>
+ new RoutingPersonsStore(
+ new BatchWritingPersonsStore(new PostgresPersonRepository(hub.postgres), outputs(), {
+ metricEmissionIntervalMs: 0,
+ }),
+ new PersonhogPersonsStore(writeRepository, {
+ maxConcurrentUpdates: 10,
+ updateAllProperties: false,
+ syncMergeMoveLimit: 10_000,
+ }),
+ 'shadow'
+ )
+
const ops = (properties: Record<string, unknown>, event = '$set') =>
extractEventOps({
event,
@@ -210,13 +226,15 @@ describe('personhog shadow parity (e2e)', () => {
properties: Record<string, unknown>
is_identified: boolean
created_at: string
+ last_seen_at: string | null
}
const mainRowByDistinctId = async (distinctId: string): Promise<DurableRow | null> => {
const { rows } = await hub.postgres.query<DurableRow>(
PostgresUse.PERSONS_WRITE,
`SELECT p.uuid, p.properties, p.is_identified,
- (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at
+ (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at,
+ (extract(epoch from p.last_seen_at) * 1000)::bigint::text AS last_seen_at
FROM posthog_persondistinctid d
JOIN posthog_person p ON p.id = d.person_id
WHERE d.team_id = $1 AND d.distinct_id = $2`,
@@ -229,7 +247,8 @@ describe('personhog shadow parity (e2e)', () => {
const tmpRowByDistinctId = async (distinctId: string): Promise<DurableRow | null> => {
const { rows } = await personsDb.query<DurableRow>(
`SELECT p.uuid, p.properties, p.is_identified,
- (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at
+ (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at,
+ (extract(epoch from p.last_seen_at) * 1000)::bigint::text AS last_seen_at
FROM personhog_persondistinctid_tmp d
JOIN personhog_person_tmp p ON p.id = d.person_id AND p.team_id = d.team_id
WHERE d.team_id = $1 AND d.distinct_id = $2
@@ -259,6 +278,7 @@ describe('personhog shadow parity (e2e)', () => {
tmp.uuid === main!.uuid &&
tmp.is_identified === main!.is_identified &&
tmp.created_at === main!.created_at &&
+ tmp.last_seen_at === main!.last_seen_at &&
isDeepStrictEqual(tmp.properties, main!.properties)
) {
break
@@ -272,6 +292,7 @@ describe('personhog shadow parity (e2e)', () => {
expect(tmp!.uuid).toBe(main!.uuid)
expect(tmp!.is_identified).toBe(main!.is_identified)
expect(tmp!.created_at).toBe(main!.created_at)
+ expect(tmp!.last_seen_at).toBe(main!.last_seen_at)
expect(tmp!.properties).toEqual(main!.properties)
}
@@ -288,7 +309,7 @@ describe('personhog shadow parity (e2e)', () => {
{ mergeTimeoutMs: 35_000 }
)
closeIdentity = identityClients.close
- const writeRepository = new PersonHogPersonWriteRepository(
+ writeRepository = new PersonHogPersonWriteRepository(
routerClient,
identityClients.identity,
'personhog-shadow-parity-e2e'
@@ -302,15 +323,7 @@ describe('personhog shadow parity (e2e)', () => {
`or a hogli dev stack. Cause: ${error instanceof Error ? error.message : String(error)}`
)
}
- personhogStore = new PersonhogPersonsStore(writeRepository, {
- maxConcurrentUpdates: 10,
- updateAllProperties: false,
- syncMergeMoveLimit: 10_000,
- })
- pgStore = new BatchWritingPersonsStore(new PostgresPersonRepository(hub.postgres), outputs(), {
- metricEmissionIntervalMs: 0,
- })
- routing = new RoutingPersonsStore(pgStore, personhogStore, 'shadow')
+ routing = newPod()
personsDb = new Pool({ connectionString: PERSONS_DATABASE_URL, max: 2 })
organizationId = await createOrganization(hub.postgres)
teamId = await createTeam(hub.postgres, organizationId)
@@ -641,6 +654,54 @@ describe('personhog shadow parity (e2e)', () => {
await expectDurableRowParity(source)
})
+ it.each([['before'], ['after']])(
+ "another pod's pending update to a merged-away id lands on the survivor when flushed %s the merge's own update",
+ async (order) => {
+ const target = id(`pods-${order}-target`)
+ const source = id(`pods-${order}-source`)
+ await createThroughBoth(target, { origin: 'target' }, batchId)
+ await createThroughBoth(source, { origin: 'source', extra: 'source' }, batchId)
+
+ // The other pod reads the source and holds an update to it, with
+ // a newer last-seen, while this pod merges the source away. Its
+ // flush finds no row for the person it cached: Postgres re-targets
+ // from the distinct id, personhog redirects to the survivor.
+ const other = newPod()
+ const held = await other.fetchForUpdate(teamId, source, batchId)
+ expect(held?.uuid).toBe(uuidFromDistinctId(teamId, source))
+ const otherOps = ops({ $set: { fromOtherPod: 'yes' } })
+ otherOps.lastSeenAtMs = DateTime.utc().plus({ hours: 1 }).startOf('hour').toMillis()
+ await other.applyEventOps(held!, otherOps, source, batchId)
+
+ const { result, mergeOps } = await runMerge(target, [source], { set: { mergedBy: 'this pod' } })
+ expect(result.results[0]?.outcome).toBe('merged')
+ if (order === 'before') {
+ await other.flush()
+ }
+ await applyMergeFollowUp(result, mergeOps, target)
+ await routing.flush()
+ if (order === 'after') {
+ await other.flush()
+ }
+ other.releaseBatch(batchId)
+ routing.releaseBatch(batchId)
+
+ batchId += 1
+ const survivor = await routing.fetchForUpdate(teamId, target, batchId)
+ expect(survivor?.properties).toMatchObject({
+ origin: 'target',
+ extra: 'source',
+ mergedBy: 'this pod',
+ fromOtherPod: 'yes',
+ })
+ expect(survivor?.last_seen_at?.toMillis()).toBe(otherOps.lastSeenAtMs)
+ expect(await divergences()).toBe(0)
+ expect(await shadowErrors()).toBe(0)
+ await expectDurableRowParity(target)
+ await expectDurableRowParity(source)
+ }
+ )
+
it('a merged-away id reads the survivor on both backends', async () => {
const target = id('heal-target')
const source = id('heal-source')