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.

157 KB
Raw Blame
import { mockProducer } from '~/tests/helpers/mocks/producer.mock'

import { DateTime } from 'luxon'

import { KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '~/common/config/kafka-topics'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PersonMessage } from '~/common/persons/person-message'
import { COOKIELESS_SENTINEL_VALUE } from '~/common/persons/person-utils'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { NoRowsUpdatedError, UUIDT } from '~/common/utils/utils'
import { createTeam, createTestTeamFixture, insertRow } from '~/tests/helpers/sql'
import { Hub, InternalPerson, PropertyUpdateOperation, Team } from '~/types'

import {
    DistinctIdConflictError,
    PersonClaimedByLifecycleOpError,
    PersonPropertiesSizeViolationError,
    PersonTombstoneBlockedError,
} from './person-repository'
import { PostgresPersonRepository } from './postgres-person-repository'
import { createPersonUpdateFields, fetchDistinctIdValues, fetchDistinctIds } from './test-helpers'

jest.mock('~/common/utils/logger')

describe('PostgresPersonRepository', () => {
    let hub: Hub
    let postgres: PostgresRouter
    let repository: PostgresPersonRepository
    let team: Team

    beforeAll(async () => {
        hub = await createHub()
        postgres = hub.postgres
        repository = new PostgresPersonRepository(postgres, {
            calculatePropertiesSize: 0,
            personPropertiesDbConstraintLimitBytes: 1024 * 1024, // 1MB for tests
            personPropertiesTrimTargetBytes: 512 * 1024,
        })
    })

    afterAll(async () => {
        await closeHub(hub)
    })

    beforeEach(async () => {
        team = (await createTestTeamFixture(postgres)).team
    })

    afterEach(() => {
        // The hub outlives each test now, so spies on it must not.
        jest.restoreAllMocks()
        jest.clearAllMocks()
    })

    const TIMESTAMP = DateTime.fromISO('2024-01-15T10:30:00.000Z').toUTC()

    // Helper function to create a person with all the necessary setup
    async function createTestPerson(teamId: number, distinctId: string, properties: Record<string, any> = {}) {
        const uuid = new UUIDT().toString()
        const result = await repository.createPerson(TIMESTAMP, properties, {}, {}, teamId, null, true, uuid, {
            distinctId,
        })
        if (!result.success) {
            throw new Error('Failed to create person')
        }
        const personOutputs = new IngestionOutputs({
            [PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
            [PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
                PERSON_DISTINCT_IDS_OUTPUT,
                KAFKA_PERSON_DISTINCT_ID,
                mockProducer,
                'test'
            ),
        })
        await Promise.all(
            result.messages.map((msg) => personOutputs.produce(msg.output, { value: msg.value, key: null }))
        )
        return result.person
    }

    describe('fetchPerson()', () => {
        it('returns undefined if person does not exist', async () => {
            const person = await repository.fetchPerson(team.id, 'some_id')

            expect(person).toEqual(undefined)
        })

        it('returns person object if person exists', async () => {
            const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })
            const person = await repository.fetchPerson(team.id, 'some_id')

            expect(person).toEqual(createdPerson)
            expect(person).toEqual(
                expect.objectContaining({
                    id: expect.any(String),
                    uuid: createdPerson.uuid,
                    properties: { foo: 'bar' },
                    is_identified: true,
                    created_at: TIMESTAMP,
                    version: 0,
                })
            )
        })

        it('throws error when both forUpdate and useReadReplica are true', async () => {
            await expect(
                repository.fetchPerson(team.id, 'some_id', { forUpdate: true, useReadReplica: true })
            ).rejects.toThrow("can't enable both forUpdate and useReadReplica in db::fetchPerson")
        })

        it('uses read replica when useReadReplica is true', async () => {
            const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })

            // Mock the postgres query to verify it's called with the right parameters
            const mockQuery = jest.spyOn(postgres, 'query').mockResolvedValue({
                rows: [
                    {
                        id: createdPerson.id,
                        uuid: createdPerson.uuid,
                        created_at: createdPerson.created_at.toISO(),
                        team_id: createdPerson.team_id,
                        properties: createdPerson.properties,
                        properties_last_updated_at: createdPerson.properties_last_updated_at,
                        properties_last_operation: createdPerson.properties_last_operation,
                        is_user_id: createdPerson.is_user_id,
                        version: createdPerson.version,
                        is_identified: createdPerson.is_identified,
                        last_seen_at: createdPerson.last_seen_at,
                    },
                ],
                command: 'SELECT',
                rowCount: 1,
                oid: 0,
                fields: [],
            })

            await repository.fetchPerson(team.id, 'some_id', { useReadReplica: true })

            expect(mockQuery).toHaveBeenCalledWith(
                PostgresUse.PERSONS_READ,
                expect.stringContaining('SELECT'),
                [team.id, 'some_id'],
                'fetchPerson'
            )
        })

        it('uses write connection when useReadReplica is false', async () => {
            const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })

            // Mock the postgres query to verify it's called with the right parameters
            const mockQuery = jest.spyOn(postgres, 'query').mockResolvedValue({
                rows: [
                    {
                        id: createdPerson.id,
                        uuid: createdPerson.uuid,
                        created_at: createdPerson.created_at.toISO(),
                        team_id: createdPerson.team_id,
                        properties: createdPerson.properties,
                        properties_last_updated_at: createdPerson.properties_last_updated_at,
                        properties_last_operation: createdPerson.properties_last_operation,
                        is_user_id: createdPerson.is_user_id,
                        version: createdPerson.version,
                        is_identified: createdPerson.is_identified,
                        last_seen_at: createdPerson.last_seen_at,
                    },
                ],
                command: 'SELECT',
                rowCount: 1,
                oid: 0,
                fields: [],
            })

            await repository.fetchPerson(team.id, 'some_id', { useReadReplica: false })

            expect(mockQuery).toHaveBeenCalledWith(
                PostgresUse.PERSONS_WRITE,
                expect.stringContaining('SELECT'),
                [team.id, 'some_id'],
                'fetchPerson'
            )
        })

        it('adds FOR UPDATE clause when forUpdate is true', async () => {
            // Mock the postgres query to verify the SQL contains FOR UPDATE
            const mockQuery = jest.spyOn(postgres, 'query').mockResolvedValue({
                rows: [],
                command: 'SELECT',
                rowCount: 0,
                oid: 0,
                fields: [],
            })

            await repository.fetchPerson(team.id, 'some_id', { forUpdate: true })

            expect(mockQuery).toHaveBeenCalledWith(
                PostgresUse.PERSONS_WRITE,
                expect.stringContaining('FOR UPDATE'),
                [team.id, 'some_id'],
                'fetchPerson'
            )
        })
    })

    describe('tombstoned rows', () => {
        function recordQueryTags(): () => string[] {
            const spy = jest.spyOn(postgres, 'query')
            return () => spy.mock.calls.map((call) => String(call[3]))
        }

        async function tombstonePerson(person: InternalPerson): Promise<void> {
            await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'UPDATE posthog_person SET is_deleted = true, version = version + 1 WHERE team_id = $1 AND id = $2',
                [person.team_id, person.id],
                'tombstonePerson'
            )
        }

        async function tombstoneDistinctId(teamId: number, distinctId: string): Promise<void> {
            await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'UPDATE posthog_persondistinctid SET is_deleted = true, version = COALESCE(version, 0) + 1 WHERE team_id = $1 AND distinct_id = $2',
                [teamId, distinctId],
                'tombstoneDistinctId'
            )
        }

        function buildPersonUpdate(person: InternalPerson, distinctId: string, version: number) {
            return {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: distinctId,
                properties: { name: 'Jane' },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }
        }

        it('excludes tombstoned persons from person reads', async () => {
            const person = await createTestPerson(team.id, 'tombstoned-person-did')
            await tombstonePerson(person)

            await expect(repository.fetchPerson(team.id, 'tombstoned-person-did')).resolves.toBeUndefined()
            await expect(
                repository.fetchPersonsByDistinctIds([{ teamId: team.id, distinctId: 'tombstoned-person-did' }])
            ).resolves.toEqual([])
            await expect(
                repository.fetchPersonsForUpdateByDistinctIds(team.id, ['tombstoned-person-did'])
            ).resolves.toEqual([])
            await expect(
                repository.fetchPersonsByPersonIds([{ teamId: team.id, personId: person.uuid }])
            ).resolves.toEqual([])
        })

        it('excludes tombstoned distinct id mappings from reads while live mappings still resolve', async () => {
            const person = await createTestPerson(team.id, 'live-did')
            await repository.addDistinctId(person, 'dead-did', 0)
            await tombstoneDistinctId(team.id, 'dead-did')

            await expect(repository.fetchPerson(team.id, 'dead-did')).resolves.toBeUndefined()
            await expect(repository.fetchPerson(team.id, 'live-did')).resolves.toMatchObject({ uuid: person.uuid })
            await expect(repository.fetchPersonDistinctIds(person)).resolves.toEqual(['live-did'])
            await expect(repository.fetchDistinctIdsForPersons(team.id, [person.id])).resolves.toEqual({
                [person.id]: ['live-did'],
            })
            await expect(repository.countDistinctIdsForPersons(team.id, [person.id])).resolves.toEqual(
                new Map([[person.id, 1]])
            )
        })

        it('updatePerson does not touch a tombstoned person', async () => {
            const person = await createTestPerson(team.id, 'guard-update-did')
            await tombstonePerson(person)

            await expect(
                repository.updatePerson(
                    person,
                    createPersonUpdateFields(person, { properties: { a: 1 } }),
                    'guard-test'
                )
            ).rejects.toThrow(NoRowsUpdatedError)
        })

        it('updatePersonAssertVersion does not touch a tombstoned person even at the matching version', async () => {
            const person = await createTestPerson(team.id, 'guard-assert-did')
            await tombstonePerson(person)

            // The tombstone bumped the row to person.version + 1; assert against that exact
            // version so only the is_deleted guard can reject the write.
            const [version, messages] = await repository.updatePersonAssertVersion(
                buildPersonUpdate(person, 'guard-assert-did', person.version + 1)
            )

            expect(version).toBeUndefined()
            expect(messages).toEqual([])
        })

        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 })

            // 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'
            )

            // 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 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'
            )
            // 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([
            [
                'fetchPersonsByDistinctIds',
                (_person: InternalPerson) =>
                    repository.fetchPersonsByDistinctIds([{ teamId: team.id, distinctId: 'pruning-person' }]),
            ],
            [
                'fetchPersonsByPersonIds',
                (person: InternalPerson) =>
                    repository.fetchPersonsByPersonIds([{ teamId: team.id, personId: person.uuid }]),
            ],
            [
                'updatePersonsBatch',
                (person: InternalPerson) =>
                    repository.updatePersonsBatch([buildPersonUpdate(person, 'pruning-person', person.version)]),
            ],
        ])('%s plans against only its team partition', async (tag, run) => {
            const person = await createTestPerson(team.id, 'pruning-person')
            const query = jest.spyOn(postgres, 'query')
            await run(person)
            const [, sql, values] = query.mock.calls.find(([, , , callTag]) => callTag === tag)!

            // The planner locks every person partition it cannot prune, so the lock count shows the pruning.
            const lockedPartitions = await postgres.transaction(
                PostgresUse.PERSONS_WRITE,
                'pruningProbe',
                async (tx) => {
                    await postgres.query(tx, `EXPLAIN ${sql}`, values, 'pruningProbe')
                    const { rows } = await postgres.query<{ partitions: number }>(
                        tx,
                        `SELECT count(DISTINCT l.relation)::int AS partitions FROM pg_locks l
                     JOIN pg_inherits i ON i.inhrelid = l.relation
                     WHERE l.pid = pg_backend_pid() AND i.inhparent = 'posthog_person'::regclass`,
                        [],
                        'pruningProbe'
                    )
                    return rows[0].partitions
                }
            )
            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',
                (source: InternalPerson, target: InternalPerson) => repository.moveDistinctIds(source, target),
            ],
            [
                'moveDistinctIds with limit',
                (source: InternalPerson, target: InternalPerson) => repository.moveDistinctIds(source, target, 10),
            ],
            [
                'moveDistinctIdsFromPersons',
                (source: InternalPerson, target: InternalPerson) =>
                    repository.moveDistinctIdsFromPersons([source], target),
            ],
        ])('%s moves only live distinct id mappings', async (_name, move) => {
            const source = await createTestPerson(team.id, 'guard-move-live-did')
            const target = await createTestPerson(team.id, 'guard-move-target-did')
            await repository.addDistinctId(source, 'guard-move-dead-did', 0)
            await tombstoneDistinctId(team.id, 'guard-move-dead-did')

            const result = await move(source, target)

            expect(result).toMatchObject({ success: true, distinctIdsMoved: ['guard-move-live-did'] })
            const sourceRows = await fetchDistinctIds(postgres, source)
            expect(sourceRows).toHaveLength(1)
            expect(sourceRows[0].distinct_id).toBe('guard-move-dead-did')
        })

        it('createPerson revives a tombstoned person and its distinct id at death_version + 1', async () => {
            const uuid = new UUIDT().toString()
            const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
                distinctId: 'revive-did',
            })
            if (!first.success) {
                throw new Error('Failed to create person')
            }
            await tombstonePerson(first.person)
            await tombstoneDistinctId(team.id, 'revive-did')

            const revived = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, true, uuid, {
                distinctId: 'revive-did',
            })

            if (!revived.success) {
                throw new Error('Expected revival to succeed')
            }
            expect(revived.created).toBe(true)
            expect(revived.person.version).toBe(2)
            expect(revived.person.properties).toEqual({ b: 2 })
            await expect(repository.fetchPerson(team.id, 'revive-did')).resolves.toMatchObject({ uuid, version: 2 })

            const personMessage = parseJSON(revived.messages[0].value!.toString())
            expect(personMessage.version).toBe(2)
            expect(personMessage.is_deleted).toBe(0)
            const distinctIdMessage = parseJSON(revived.messages[1].value!.toString())
            expect(distinctIdMessage.version).toBe(2)
        })

        it('createPerson returns CreationConflict against a live person with the same uuid', async () => {
            const uuid = new UUIDT().toString()
            const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
                distinctId: 'live-uuid-did',
            })
            if (!first.success) {
                throw new Error('Failed to create person')
            }

            const second = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, false, uuid, {
                distinctId: 'live-uuid-did-2',
            })

            // The holder owns a different distinct ID, so recovering by distinct ID cannot find
            // it. Returning it here is what lets the caller resolve instead of raising an error
            // the pipeline retries until the consumer dies with uncommitted offsets.
            expect(second).toEqual({
                success: false,
                error: 'CreationConflict',
                distinctIds: ['live-uuid-did-2'],
                conflictingPerson: expect.objectContaining({ id: first.person.id, uuid }),
            })
            await expect(repository.fetchPerson(team.id, 'live-uuid-did')).resolves.toMatchObject({
                version: 0,
                properties: { a: 1 },
            })
        })

        it('returns the uuid holder when the create runs inside a transaction', async () => {
            // The legacy path recovers from a caught unique violation, which leaves the
            // transaction aborted. Reading the holder on that transaction raises 25P02 and the
            // throw escapes the conflict branch entirely, failing the merge saga that reaches
            // createPerson through inTransaction. `repository` has no allowlist, so it takes
            // that path rather than the ON CONFLICT one.
            const uuid = new UUIDT().toString()
            const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
                distinctId: 'tx-uuid-did',
            })
            if (!first.success) {
                throw new Error('Failed to create person')
            }

            const second = await repository.inTransaction('conflict-inside-transaction', (tx) =>
                tx.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, false, uuid, {
                    distinctId: 'tx-uuid-did-2',
                })
            )

            expect(second).toEqual({
                success: false,
                error: 'CreationConflict',
                distinctIds: ['tx-uuid-did-2'],
                conflictingPerson: expect.objectContaining({ id: first.person.id, uuid }),
            })
        })

        it('createPerson dedupes repeated distinct ids instead of failing the multi-insert', async () => {
            const uuid = new UUIDT().toString()

            const result = await repository.createPerson(
                TIMESTAMP,
                {},
                {},
                {},
                team.id,
                null,
                false,
                uuid,
                { distinctId: 'dup-did' },
                [{ distinctId: 'dup-did' }]
            )

            if (!result.success) {
                throw new Error('Expected creation to succeed')
            }
            // One person message and one mapping message: the duplicate collapsed.
            expect(result.messages).toHaveLength(2)
            await expect(repository.fetchPerson(team.id, 'dup-did')).resolves.toMatchObject({ uuid })
        })

        it('createPerson undoes its insert when a distinct id is owned by a live mapping', async () => {
            await createTestPerson(team.id, 'contested-did')
            const uuid = new UUIDT().toString()
            const queryTags = recordQueryTags()

            const result = await repository.createPerson(
                TIMESTAMP,
                { secret: 'value' },
                {},
                {},
                team.id,
                null,
                false,
                uuid,
                { distinctId: 'undo-primary-did' },
                [{ distinctId: 'contested-did' }]
            )

            expect(result).toMatchObject({ success: false, error: 'CreationConflict' })
            expect(queryTags()).not.toContain('lockStrayDistinctIds')
            // The person row and the primary mapping it did attach are tombstoned, not
            // left live: a live person unreachable by its contested distinct id would
            // block the key forever. Like every tombstone, the properties are scrubbed.
            const personRows = await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'SELECT is_deleted, properties FROM posthog_person WHERE team_id = $1 AND uuid = $2',
                [team.id, uuid],
                'fetchUndonePerson'
            )
            expect(personRows.rows).toEqual([{ is_deleted: true, properties: {} }])
            await expect(repository.fetchPerson(team.id, 'undo-primary-did')).resolves.toBeUndefined()
        })

        it('createPerson undone by a live mapping leaves a reattached stray tombstoned', async () => {
            const liveOwner = await createTestPerson(team.id, 'mixed-contested-did')
            const deadOwner = await createTestPerson(team.id, 'mixed-stray-owner-did')
            await repository.addDistinctId(deadOwner, 'mixed-stray-did', 1)
            await tombstonePerson(deadOwner)

            const result = await repository.createPerson(
                TIMESTAMP,
                {},
                {},
                {},
                team.id,
                null,
                false,
                new UUIDT().toString(),
                { distinctId: 'mixed-stray-did' },
                [{ distinctId: 'mixed-contested-did' }]
            )

            expect(result).toMatchObject({ success: false, error: 'CreationConflict' })
            // The tombstone is not published. Its version stays above the mapping's ClickHouse row,
            // and the ClickHouse deletion sweep removes that row with the deleted owner.
            const strayRows = await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'SELECT is_deleted, version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2',
                [team.id, 'mixed-stray-did'],
                'fetchMixedStray'
            )
            expect(strayRows.rows).toEqual([{ is_deleted: true, version: '4' }])
            await expect(repository.fetchPerson(team.id, 'mixed-contested-did')).resolves.toMatchObject({
                uuid: liveOwner.uuid,
            })
        })

        it.each([
            [
                'createPerson',
                async (): Promise<[string, PersonMessage[]]> => {
                    const uuid = new UUIDT().toString()
                    const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, false, uuid, {
                        distinctId: 'stray-did',
                    })
                    if (!result.success) {
                        throw new Error('Expected creation to succeed')
                    }
                    return [uuid, result.messages.slice(1)]
                },
            ],
            [
                'addDistinctId',
                async (): Promise<[string, PersonMessage[]]> => {
                    const newOwner = await createTestPerson(team.id, 'stray-adder-did')
                    return [newOwner.uuid, await repository.addDistinctId(newOwner, 'stray-did', 1)]
                },
            ],
        ])('%s takes over a live mapping left on a tombstoned person', async (_name, write) => {
            const deadOwner = await createTestPerson(team.id, 'stray-owner-did')
            await repository.addDistinctId(deadOwner, 'stray-did', 1)
            await tombstonePerson(deadOwner)

            const [ownerUuid, messages] = await write()

            await expect(repository.fetchPerson(team.id, 'stray-did')).resolves.toMatchObject({ uuid: ownerUuid })
            expect(messages.map((message) => parseJSON(message.value!.toString()))).toEqual([
                expect.objectContaining({ distinct_id: 'stray-did', person_id: ownerUuid, version: 3, is_deleted: 0 }),
            ])
        })

        it('createPerson that revives the owner of a stray keeps the stray attached', async () => {
            const owner = await createTestPerson(team.id, 'self-stray-did')
            await tombstonePerson(owner)

            const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, false, owner.uuid, {
                distinctId: 'self-stray-did',
            })

            expect(result).toMatchObject({ success: true, person: { id: owner.id, uuid: owner.uuid } })
            await expect(repository.fetchPerson(team.id, 'self-stray-did')).resolves.toMatchObject({ uuid: owner.uuid })
        })

        it('addDistinctId revives a tombstoned mapping, repointing it at the new person', async () => {
            const newOwner = await createTestPerson(team.id, 'adder-did')
            const oldOwner = await createTestPerson(team.id, 'old-owner-did')
            await repository.addDistinctId(oldOwner, 'recycled-did', 0)
            await tombstoneDistinctId(team.id, 'recycled-did')

            const messages = await repository.addDistinctId(newOwner, 'recycled-did', 0)

            await expect(repository.fetchPerson(team.id, 'recycled-did')).resolves.toMatchObject({
                uuid: newOwner.uuid,
            })
            const message = parseJSON(messages[0].value!.toString())
            expect(message).toEqual({
                person_id: newOwner.uuid,
                team_id: team.id,
                distinct_id: 'recycled-did',
                version: 2,
                is_deleted: 0,
            })
        })

        it.each([
            ['another live person', 'other-owned-did', false],
            ['the same person', 'conflict-adder-did', true],
        ])(
            'addDistinctId throws DistinctIdConflictError for a live mapping owned by %s',
            async (_owner, distinctId, ownedBySamePerson) => {
                const person = await createTestPerson(team.id, 'conflict-adder-did')
                if (!ownedBySamePerson) {
                    await createTestPerson(team.id, distinctId)
                }
                const queryTags = recordQueryTags()

                await expect(repository.addDistinctId(person, distinctId, 0)).rejects.toThrow(DistinctIdConflictError)
                expect(queryTags()).not.toContain('lockStrayDistinctIds')
            }
        )

        it('isPersonLive is true for a live person and false for a tombstoned one', async () => {
            const person = await createTestPerson(team.id, 'live-check-did')

            await expect(repository.isPersonLive(person)).resolves.toBe(true)
            await tombstonePerson(person)
            await expect(repository.isPersonLive(person)).resolves.toBe(false)
        })

        describe('lifecycle marks', () => {
            async function countLifecycleRows(opId: string): Promise<{ ops: number; persons: number }> {
                const ops = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT count(*) AS count FROM lifecycle_op WHERE op_id = $1',
                    [opId],
                    'countLifecycleOps'
                )
                const persons = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT count(*) AS count FROM lifecycle_op_person WHERE op_id = $1',
                    [opId],
                    'countLifecycleOpPersons'
                )
                return { ops: Number(ops.rows[0].count), persons: Number(persons.rows[0].count) }
            }

            it('claim and release leave no rows behind', async () => {
                const person = await createTestPerson(team.id, 'mark-roundtrip-did')
                const opId = new UUIDT().toString()

                await repository.claimLifecycleMarks(opId, team.id, [
                    { personId: person.id, personUuid: person.uuid, role: 'target' },
                ])
                await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 1, persons: 1 })

                const markRow = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT mark_active FROM lifecycle_op_person WHERE op_id = $1',
                    [opId],
                    'checkMarkActive'
                )
                expect(markRow.rows[0].mark_active).toBe(true)

                await repository.releaseLifecycleMarks(opId, team.id)
                await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 0, persons: 0 })
            })

            it('claiming a person held by a live operation throws PersonClaimedByLifecycleOpError', async () => {
                const person = await createTestPerson(team.id, 'mark-conflict-did')
                const sagaOpId = new UUIDT().toString()
                // A delete saga's live claim: committed in its own transaction and held
                // across ours, exactly what the mark index arbitrates against.
                await repository.claimLifecycleMarks(sagaOpId, team.id, [
                    { personId: person.id, personUuid: person.uuid, role: 'source' },
                ])

                const mergeOpId = new UUIDT().toString()
                await expect(
                    repository.claimLifecycleMarks(mergeOpId, team.id, [
                        { personId: person.id, personUuid: person.uuid, role: 'target' },
                    ])
                ).rejects.toThrow(PersonClaimedByLifecycleOpError)

                await repository.releaseLifecycleMarks(sagaOpId, team.id)
            })

            it('release scoped to another team leaves the marks in place', async () => {
                const person = await createTestPerson(team.id, 'mark-scoped-did')
                const opId = new UUIDT().toString()
                await repository.claimLifecycleMarks(opId, team.id, [
                    { personId: person.id, personUuid: person.uuid, role: 'target' },
                ])

                await repository.releaseLifecycleMarks(opId, team.id + 1)
                await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 1, persons: 1 })

                await repository.releaseLifecycleMarks(opId, team.id)
                await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 0, persons: 0 })
            })

            it('a released mark no longer blocks a new claim', async () => {
                const person = await createTestPerson(team.id, 'mark-released-did')
                const firstOpId = new UUIDT().toString()
                await repository.claimLifecycleMarks(firstOpId, team.id, [
                    { personId: person.id, personUuid: person.uuid, role: 'target' },
                ])
                await repository.releaseLifecycleMarks(firstOpId, team.id)

                const secondOpId = new UUIDT().toString()
                await repository.claimLifecycleMarks(secondOpId, team.id, [
                    { personId: person.id, personUuid: person.uuid, role: 'target' },
                ])
                await repository.releaseLifecycleMarks(secondOpId, team.id)
            })
        })

        describe('deletes', () => {
            it('deletePerson tombstones the row at the exact death version with scrubbed properties', async () => {
                const person = await createTestPerson(team.id, 'ts-delete-did', { secret: 'x' })
                await tombstoneDistinctId(team.id, 'ts-delete-did')

                const messages = await repository.deletePerson(person)

                expect(messages).toHaveLength(1)
                const message = parseJSON(messages[0].value!.toString())
                expect(message).toMatchObject({ id: person.uuid, is_deleted: 1, version: 1, properties: '{}' })

                const { rows } = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT is_deleted, version, properties FROM posthog_person WHERE team_id = $1 AND id = $2',
                    [team.id, person.id],
                    'fetchTombstonedPerson'
                )
                expect(rows[0].is_deleted).toBe(true)
                expect(Number(rows[0].version)).toBe(1)
                expect(rows[0].properties).toEqual({})
            })

            it('deletePerson refuses while live distinct ids still point at the person', async () => {
                const person = await createTestPerson(team.id, 'ts-blocked-did')

                await expect(repository.deletePerson(person)).rejects.toThrow(PersonTombstoneBlockedError)
                await expect(repository.fetchPerson(team.id, 'ts-blocked-did')).resolves.toMatchObject({
                    uuid: person.uuid,
                })
            })

            it('deletePersons tombstones fresh persons and skips already-tombstoned ones', async () => {
                const alreadyDead = await createTestPerson(team.id, 'ts-batch-dead-did')
                const fresh = await createTestPerson(team.id, 'ts-batch-fresh-did')
                await tombstoneDistinctId(team.id, 'ts-batch-dead-did')
                await tombstoneDistinctId(team.id, 'ts-batch-fresh-did')
                await tombstonePerson(alreadyDead)

                const messages = await repository.deletePersons([alreadyDead, fresh])

                expect(messages).toHaveLength(1)
                const message = parseJSON(messages[0].value!.toString())
                expect(message).toMatchObject({ id: fresh.uuid, is_deleted: 1, version: 1 })
            })
        })
    })

    describe('createPerson()', () => {
        it('creates a person with basic properties', async () => {
            const uuid = new UUIDT().toString()
            const properties = { name: 'John Doe', email: '[email protected]' }

            const result = await repository.createPerson(TIMESTAMP, properties, {}, {}, team.id, null, true, uuid, {
                distinctId: 'test-distinct-id',
            })

            if (!result.success) {
                throw new Error('Failed to create person')
            }
            const person = result.person
            const kafkaMessages = result.messages

            expect(person).toEqual(
                expect.objectContaining({
                    id: expect.any(String),
                    uuid: uuid,
                    team_id: team.id,
                    properties: properties,
                    is_identified: true,
                    created_at: TIMESTAMP,
                    version: 0,
                })
            )

            expect(kafkaMessages).toHaveLength(2) // One for person, one for distinct ID
            expect(kafkaMessages[0].output).toBe(PERSONS_OUTPUT)
            expect(kafkaMessages[1].output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
        })

        it('creates a person with multiple distinct IDs', async () => {
            const uuid = new UUIDT().toString()
            const properties = { name: 'Jane Doe' }

            const result = await repository.createPerson(
                TIMESTAMP,
                properties,
                {},
                {},
                team.id,
                null,
                false,
                uuid,
                { distinctId: 'distinct-1', version: 0 },
                [{ distinctId: 'distinct-2', version: 1 }]
            )
            if (!result.success) {
                throw new Error('Failed to create person')
            }
            const person = result.person
            const kafkaMessages = result.messages

            expect(person).toEqual(
                expect.objectContaining({
                    id: expect.any(String),
                    uuid: uuid,
                    team_id: team.id,
                    properties: properties,
                    is_identified: false,
                    created_at: TIMESTAMP,
                    version: 0,
                })
            )

            expect(kafkaMessages).toHaveLength(3) // One for person, two for distinct IDs
            expect(kafkaMessages[0].output).toBe(PERSONS_OUTPUT)
            expect(kafkaMessages[1].output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
            expect(kafkaMessages[2].output).toBe(PERSON_DISTINCT_IDS_OUTPUT)

            const distinctIds = await fetchDistinctIdValues(hub.postgres, person)
            expect(distinctIds).toHaveLength(2)
            expect(distinctIds).toEqual(expect.arrayContaining(['distinct-1', 'distinct-2']))

            const distinctIdRecords = await fetchDistinctIds(hub.postgres, person)
            expect(distinctIdRecords.find((d) => d.distinct_id === 'distinct-1')?.version).toBe('0')
            expect(distinctIdRecords.find((d) => d.distinct_id === 'distinct-2')?.version).toBe('1')
        })

        it('throws error when trying to create a person with the same distinct ID twice', async () => {
            const distinctId = 'duplicate-distinct-id'
            const uuid1 = new UUIDT().toString()
            const uuid2 = new UUIDT().toString()

            // Create first person successfully
            const result1 = await repository.createPerson(
                TIMESTAMP,
                { name: 'First Person' },
                {},
                {},
                team.id,
                null,
                true,
                uuid1,
                { distinctId }
            )

            if (!result1.success) {
                throw new Error('Failed to create person')
            }
            const person1 = result1.person
            const kafkaMessages1 = result1.messages

            expect(person1).toBeDefined()
            expect(kafkaMessages1).toHaveLength(2)

            // Try to create second person with same distinct ID - should fail
            const createPersonResult = await repository.createPerson(
                TIMESTAMP,
                { name: 'Second Person' },
                {},
                {},
                team.id,
                null,
                true,
                uuid2,
                { distinctId }
            )

            expect(createPersonResult.success).toBe(false)
            if (createPersonResult.success === false) {
                expect(createPersonResult.error).toBe('CreationConflict')
            }

            // Verify the first person still exists and can be fetched
            const fetchedPerson = await repository.fetchPerson(team.id, distinctId)
            expect(fetchedPerson).toEqual(person1)
        })
    })

    describe('addDistinctId()', () => {
        it('should add distinct ID to person', async () => {
            const person = await createTestPerson(team.id, 'existing-distinct-id', { name: 'John Doe' })
            const newDistinctId = 'new-distinct-id'
            const version = 1

            const messages = await repository.addDistinctId(person, newDistinctId, version)

            expect(messages).toHaveLength(1)
            expect(messages[0].output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
            expect(messages[0].value).not.toBeNull()

            const messageValue = parseJSON(messages[0].value!.toString())
            expect(messageValue).toEqual({
                person_id: person.uuid,
                team_id: team.id,
                distinct_id: 'new-distinct-id',
                version: 1,
                is_deleted: 0,
            })
        })

        it('should handle adding distinct ID with different version', async () => {
            const person = await createTestPerson(team.id, 'existing-distinct-id', { name: 'John Doe' })
            const newDistinctId = 'another-distinct-id'
            const version = 5

            const messages = await repository.addDistinctId(person, newDistinctId, version)

            expect(messages).toHaveLength(1)
            expect(messages[0].output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
            expect(messages[0].value).not.toBeNull()

            const messageValue = parseJSON(messages[0].value!.toString())
            expect(messageValue).toEqual({
                person_id: person.uuid,
                team_id: team.id,
                distinct_id: 'another-distinct-id',
                version: 5,
                is_deleted: 0,
            })
        })
    })

    describe('deletePerson()', () => {
        it('should handle deleting person that does not exist', async () => {
            const nonExistentPerson = {
                id: '999999',
                uuid: new UUIDT().toString(),
                created_at: TIMESTAMP,
                team_id: team.id,
                properties: {},
                properties_last_updated_at: {},
                properties_last_operation: {},
                is_user_id: null,
                version: 0,
                is_identified: false,
                last_seen_at: null,
            }

            const messages = await repository.deletePerson(nonExistentPerson)

            // Should return empty array when person doesn't exist
            expect(messages).toHaveLength(0)
        })
    })

    describe('fetchPersonDistinctIdMappings()', () => {
        // Re-emission healing depends on this read carrying the committed pairing:
        // a stale uuid or version 0 would overwrite or fail to repair ClickHouse.
        it('returns the committed uuid and version per mapping, skipping deleted and missing ids', async () => {
            const sourcePerson = await createTestPerson(team.id, 'anon')
            const targetPerson = await createTestPerson(team.id, 'main')
            const moveResult = await repository.moveDistinctIds(sourcePerson, targetPerson, undefined)
            expect(moveResult.success).toBe(true)
            await repository.addDistinctId(targetPerson, 'deleted-id', 1)
            await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'UPDATE posthog_persondistinctid SET is_deleted = true WHERE team_id = $1 AND distinct_id = $2',
                [team.id, 'deleted-id'],
                'markDeletedForTest'
            )

            const mappings = await repository.fetchPersonDistinctIdMappings(team.id, [
                'anon',
                'main',
                'deleted-id',
                'never-seen',
            ])

            const byDistinctId = Object.fromEntries(
                mappings.map((mapping) => [mapping.distinctId, parseJSON(mapping.message.value!.toString())])
            )
            expect(Object.keys(byDistinctId).sort()).toEqual(['anon', 'main'])
            expect(byDistinctId['anon']).toEqual({
                team_id: team.id,
                distinct_id: 'anon',
                person_id: targetPerson.uuid,
                version: 1,
                is_deleted: 0,
            })
            expect(byDistinctId['main']).toEqual({
                team_id: team.id,
                distinct_id: 'main',
                person_id: targetPerson.uuid,
                version: 0,
                is_deleted: 0,
            })
            expect(mappings.every((mapping) => mapping.message.output === PERSON_DISTINCT_IDS_OUTPUT)).toBe(true)
        })
    })

    describe('moveDistinctIds()', () => {
        it('should move distinct IDs from source to target person', async () => {
            const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
            const targetPerson = await createTestPerson(team.id, 'target-distinct-id', { name: 'Target Person' })

            // Add another distinct ID to source person
            await repository.addDistinctId(sourcePerson, 'source-distinct-id-2', 1)

            const result = await repository.moveDistinctIds(sourcePerson, targetPerson, undefined)

            expect(result.success).toBe(true)
            if (result.success) {
                expect(result.messages).toHaveLength(2) // Two distinct IDs moved

                // Verify the messages have the correct structure
                for (const message of result.messages) {
                    expect(message.output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
                    expect(message.value).not.toBeNull()

                    const messageValue = parseJSON(message.value!.toString())
                    expect(messageValue).toMatchObject({
                        person_id: targetPerson.uuid,
                        team_id: team.id,
                        is_deleted: 0,
                    })
                    expect(messageValue).toHaveProperty('distinct_id')
                    expect(messageValue).toHaveProperty('version')
                }
            }
        })

        it.skip('should handle target person not found', async () => {
            const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
            const nonExistentTargetPerson = {
                id: '999999',
                uuid: new UUIDT().toString(),
                created_at: TIMESTAMP,
                team_id: team.id,
                properties: {},
                properties_last_updated_at: {},
                properties_last_operation: {},
                is_user_id: null,
                version: 0,
                is_identified: false,
                last_seen_at: null,
            }

            const result = await repository.moveDistinctIds(sourcePerson, nonExistentTargetPerson, undefined)

            expect(result.success).toBe(false)
            if (!result.success) {
                expect(result.error).toBe('TargetNotFound')
            }
        })

        it('should handle source person not found', async () => {
            const targetPerson = await createTestPerson(team.id, 'target-distinct-id', { name: 'Target Person' })
            const nonExistentSourcePerson = {
                id: '888888',
                uuid: new UUIDT().toString(),
                created_at: TIMESTAMP,
                team_id: team.id,
                properties: {},
                properties_last_updated_at: {},
                properties_last_operation: {},
                is_user_id: null,
                version: 0,
                is_identified: false,
                last_seen_at: null,
            }

            const result = await repository.moveDistinctIds(nonExistentSourcePerson, targetPerson, undefined)

            expect(result.success).toBe(false)
            if (!result.success) {
                expect(result.error).toBe('SourceNotFound')
            }
        })

        it('should respect per-call move limit when provided', async () => {
            const limitedRepository = new PostgresPersonRepository(postgres, {})

            const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
            const targetPerson = await createTestPerson(team.id, 'target-distinct-id', { name: 'Target Person' })

            // Add 3 more distinct IDs to source person (total of 4 distinct IDs)
            await repository.addDistinctId(sourcePerson, 'source-distinct-id-2', 1)
            await repository.addDistinctId(sourcePerson, 'source-distinct-id-3', 1)
            await repository.addDistinctId(sourcePerson, 'source-distinct-id-4', 1)

            const result = await limitedRepository.moveDistinctIds(sourcePerson, targetPerson, 2)

            expect(result.success).toBe(true)
            if (result.success) {
                // Should only move 2 distinct IDs due to limit
                expect(result.messages).toHaveLength(2)
                expect(result.distinctIdsMoved).toHaveLength(2)

                // Verify the messages have the correct structure
                for (const message of result.messages) {
                    expect(message.output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
                    expect(message.value).not.toBeNull()

                    const messageValue = parseJSON(message.value!.toString())
                    expect(messageValue).toMatchObject({
                        person_id: targetPerson.uuid,
                        team_id: team.id,
                        is_deleted: 0,
                    })
                    expect(messageValue).toHaveProperty('distinct_id')
                    expect(messageValue).toHaveProperty('version')
                }

                // Verify that there are still distinct IDs left on the source person
                const remainingResult = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT COUNT(*) as count FROM posthog_persondistinctid WHERE person_id = $1 AND team_id = $2',
                    [sourcePerson.id, team.id],
                    'countRemainingDistinctIds'
                )
                expect(parseInt(remainingResult.rows[0].count)).toBe(2) // 4 - 2 = 2 remaining
            }
        })

        it('should move all distinct IDs when no limit is configured', async () => {
            const unlimitedRepository = new PostgresPersonRepository(postgres, {}) // No limit

            const sourcePerson = await createTestPerson(team.id, 'source-unlimited', { name: 'Source Person' })
            const targetPerson = await createTestPerson(team.id, 'target-unlimited', { name: 'Target Person' })

            // Add 3 more distinct IDs to source person (total of 4 distinct IDs)
            await repository.addDistinctId(sourcePerson, 'source-unlimited-2', 1)
            await repository.addDistinctId(sourcePerson, 'source-unlimited-3', 1)
            await repository.addDistinctId(sourcePerson, 'source-unlimited-4', 1)

            const result = await unlimitedRepository.moveDistinctIds(sourcePerson, targetPerson, undefined)

            expect(result.success).toBe(true)
            if (result.success) {
                // Should move all 4 distinct IDs
                expect(result.messages).toHaveLength(4)
                expect(result.distinctIdsMoved).toHaveLength(4)

                // Verify no distinct IDs remain on the source person
                const remainingResult = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT COUNT(*) as count FROM posthog_persondistinctid WHERE person_id = $1 AND team_id = $2',
                    [sourcePerson.id, team.id],
                    'countRemainingDistinctIds'
                )
                expect(parseInt(remainingResult.rows[0].count)).toBe(0) // All moved
            }
        })

        it('should move distinct IDs in deterministic order when per-call limit is set', async () => {
            const limitedRepository = new PostgresPersonRepository(postgres, {})

            const sourcePerson = await createTestPerson(team.id, 'source-deterministic', { name: 'Source Person' })
            const targetPerson = await createTestPerson(team.id, 'target-deterministic', { name: 'Target Person' })

            // Add distinct IDs in a specific order (not alphabetical to test database ID ordering)
            await repository.addDistinctId(sourcePerson, 'distinct-z', 1)
            await repository.addDistinctId(sourcePerson, 'distinct-a', 1)
            await repository.addDistinctId(sourcePerson, 'distinct-m', 1)

            // Get all distinct IDs in database order (by id, not by distinct_id value)
            const allDistinctIdsBeforeMove = await postgres.query(
                PostgresUse.PERSONS_WRITE,
                'SELECT id, distinct_id FROM posthog_persondistinctid WHERE person_id = $1 AND team_id = $2 ORDER BY id',
                [sourcePerson.id, team.id],
                'getAllDistinctIds'
            )

            // Should have 4 total distinct IDs (1 from createTestPerson + 3 added)
            expect(allDistinctIdsBeforeMove.rows).toHaveLength(4)

            const result = await limitedRepository.moveDistinctIds(sourcePerson, targetPerson, 2)
            expect(result.success).toBe(true)
            if (result.success) {
                expect(result.distinctIdsMoved).toHaveLength(2)

                // The moved distinct IDs should be the first 2 in database order (smallest IDs)
                const expectedMovedDistinctIds = [
                    allDistinctIdsBeforeMove.rows[0].distinct_id,
                    allDistinctIdsBeforeMove.rows[1].distinct_id,
                ]

                expect(result.distinctIdsMoved.sort()).toEqual(expectedMovedDistinctIds.sort())

                // Verify the remaining distinct IDs are the ones with higher database IDs
                const remainingIds = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT distinct_id FROM posthog_persondistinctid WHERE person_id = $1 AND team_id = $2 ORDER BY id',
                    [sourcePerson.id, team.id],
                    'getRemainingDistinctIds'
                )

                expect(remainingIds.rows).toHaveLength(2)
                const expectedRemainingDistinctIds = [
                    allDistinctIdsBeforeMove.rows[2].distinct_id,
                    allDistinctIdsBeforeMove.rows[3].distinct_id,
                ]

                const actualRemainingDistinctIds = remainingIds.rows.map((row) => row.distinct_id)
                expect(actualRemainingDistinctIds.sort()).toEqual(expectedRemainingDistinctIds.sort())
            }
        })

        it('should move all distinct IDs when person has fewer than the per-call limit', async () => {
            const limitedRepository = new PostgresPersonRepository(postgres, {})

            const sourcePerson = await createTestPerson(team.id, 'source-below-limit', { name: 'Source Person' })
            const targetPerson = await createTestPerson(team.id, 'target-below-limit', { name: 'Target Person' })

            // Add only 2 more distinct IDs (total of 3, which is below the limit of 5)
            await repository.addDistinctId(sourcePerson, 'source-below-limit-2', 1)
            await repository.addDistinctId(sourcePerson, 'source-below-limit-3', 1)

            const result = await limitedRepository.moveDistinctIds(sourcePerson, targetPerson, 5)

            expect(result.success).toBe(true)
            if (result.success) {
                // Should move all 3 distinct IDs since it's below the limit
                expect(result.messages).toHaveLength(3)
                expect(result.distinctIdsMoved).toHaveLength(3)

                // Verify the messages have the correct structure
                for (const message of result.messages) {
                    expect(message.output).toBe(PERSON_DISTINCT_IDS_OUTPUT)
                    expect(message.value).not.toBeNull()

                    const messageValue = parseJSON(message.value!.toString())
                    expect(messageValue).toMatchObject({
                        person_id: targetPerson.uuid,
                        team_id: team.id,
                        is_deleted: 0,
                    })
                    expect(messageValue).toHaveProperty('distinct_id')
                    expect(messageValue).toHaveProperty('version')
                }

                // Verify no distinct IDs remain on the source person
                const remainingResult = await postgres.query(
                    PostgresUse.PERSONS_WRITE,
                    'SELECT COUNT(*) as count FROM posthog_persondistinctid WHERE person_id = $1 AND team_id = $2',
                    [sourcePerson.id, team.id],
                    'countRemainingDistinctIds'
                )
                expect(parseInt(remainingResult.rows[0].count)).toBe(0) // All moved, none remaining
            }
        })
    })

    describe('fetchPersonDistinctIds()', () => {
        it('should fetch all distinct IDs when no limit is specified', async () => {
            const person = await createTestPerson(team.id, 'test-distinct-id', { name: 'Test Person' })

            // Add more distinct IDs
            await repository.addDistinctId(person, 'distinct-id-2', 1)
            await repository.addDistinctId(person, 'distinct-id-3', 1)
            await repository.addDistinctId(person, 'distinct-id-4', 1)

            const distinctIds = await repository.fetchPersonDistinctIds(person)

            expect(distinctIds).toHaveLength(4)
            expect(distinctIds).toContain('test-distinct-id')
            expect(distinctIds).toContain('distinct-id-2')
            expect(distinctIds).toContain('distinct-id-3')
            expect(distinctIds).toContain('distinct-id-4')
        })

        it('should fetch limited distinct IDs when limit is specified', async () => {
            const person = await createTestPerson(team.id, 'test-limit-distinct', { name: 'Test Person' })

            // Add more distinct IDs
            await repository.addDistinctId(person, 'limit-distinct-2', 1)
            await repository.addDistinctId(person, 'limit-distinct-3', 1)
            await repository.addDistinctId(person, 'limit-distinct-4', 1)

            const distinctIds = await repository.fetchPersonDistinctIds(person, 2)

            expect(distinctIds).toHaveLength(2)
            // Should be deterministic due to ORDER BY id
            expect(distinctIds).toEqual(expect.arrayContaining([expect.any(String), expect.any(String)]))
        })

        it('should return distinct IDs in deterministic order', async () => {
            const person = await createTestPerson(team.id, 'order-test-distinct', { name: 'Test Person' })

            // Add distinct IDs in non-alphabetical order
            await repository.addDistinctId(person, 'z-distinct', 1)
            await repository.addDistinctId(person, 'a-distinct', 1)
            await repository.addDistinctId(person, 'm-distinct', 1)

            const distinctIds1 = await repository.fetchPersonDistinctIds(person)
            const distinctIds2 = await repository.fetchPersonDistinctIds(person)

            // Should return the same order both times due to ORDER BY id
            expect(distinctIds1).toEqual(distinctIds2)
            expect(distinctIds1).toHaveLength(4) // 1 from createTestPerson + 3 added
        })

        it('should handle limit larger than available distinct IDs', async () => {
            const person = await createTestPerson(team.id, 'large-limit-distinct', { name: 'Test Person' })

            // Add only 2 more distinct IDs (total of 3)
            await repository.addDistinctId(person, 'large-limit-2', 1)
            await repository.addDistinctId(person, 'large-limit-3', 1)

            const distinctIds = await repository.fetchPersonDistinctIds(person, 10) // Limit is larger than available

            expect(distinctIds).toHaveLength(3) // Should return all 3 available
            expect(distinctIds).toContain('large-limit-distinct')
            expect(distinctIds).toContain('large-limit-2')
            expect(distinctIds).toContain('large-limit-3')
        })

        it('should work with transactions', async () => {
            const person = await createTestPerson(team.id, 'tx-distinct', { name: 'Test Person' })

            await repository.addDistinctId(person, 'tx-distinct-2', 1)

            await postgres.transaction(PostgresUse.PERSONS_WRITE, 'test-fetch-distinct-ids', async (tx) => {
                const distinctIds = await repository.fetchPersonDistinctIds(person, undefined, tx)
                expect(distinctIds).toHaveLength(2)
                expect(distinctIds).toContain('tx-distinct')
                expect(distinctIds).toContain('tx-distinct-2')
            })
        })
    })

    describe('fetchPersonsByDistinctIds()', () => {
        it('should return empty array when no team persons provided', async () => {
            const result = await repository.fetchPersonsByDistinctIds([])
            expect(result).toEqual([])
        })

        it('should fetch persons by distinct IDs from multiple teams', async () => {
            const team1 = team
            const team2Id = await createTeam(postgres, team1.organization_id)

            // Create persons in different teams
            const person1 = await createTestPerson(team1.id, 'distinct-1', { name: 'Person 1' })
            const person2 = await createTestPerson(team1.id, 'distinct-2', { name: 'Person 2' })
            const person3 = await createTestPerson(team2Id, 'distinct-3', { name: 'Person 3' })

            const teamPersons = [
                { teamId: team1.id, distinctId: 'distinct-1' },
                { teamId: team1.id, distinctId: 'distinct-2' },
                { teamId: team2Id, distinctId: 'distinct-3' },
            ]

            const result = await repository.fetchPersonsByDistinctIds(teamPersons)

            expect(result).toHaveLength(3)

            // Check that we got the right persons with distinct_id included
            const person1Result = result.find((p) => p.distinct_id === 'distinct-1')
            expect(person1Result).toBeDefined()
            expect(person1Result!.uuid).toBe(person1.uuid)
            expect(person1Result!.team_id).toBe(team1.id)
            expect(person1Result!.properties.name).toBe('Person 1')

            const person2Result = result.find((p) => p.distinct_id === 'distinct-2')
            expect(person2Result).toBeDefined()
            expect(person2Result!.uuid).toBe(person2.uuid)
            expect(person2Result!.team_id).toBe(team1.id)
            expect(person2Result!.properties.name).toBe('Person 2')

            const person3Result = result.find((p) => p.distinct_id === 'distinct-3')
            expect(person3Result).toBeDefined()
            expect(person3Result!.uuid).toBe(person3.uuid)
            expect(person3Result!.team_id).toBe(team2Id)
            expect(person3Result!.properties.name).toBe('Person 3')
        })

        it('should handle non-existent distinct IDs gracefully', async () => {
            const person = await createTestPerson(team.id, 'existing-distinct', { name: 'Existing Person' })

            const teamPersons = [
                { teamId: team.id as any, distinctId: 'existing-distinct' },
                { teamId: team.id as any, distinctId: 'non-existent-distinct' },
            ]

            const result = await repository.fetchPersonsByDistinctIds(teamPersons)

            // Should only return the existing person
            expect(result).toHaveLength(1)
            expect(result[0].distinct_id).toBe('existing-distinct')
            expect(result[0].uuid).toBe(person.uuid)
        })

        it('should handle single team person lookup', async () => {
            const person = await createTestPerson(team.id, 'single-distinct', { name: 'Single Person' })

            const teamPersons = [{ teamId: team.id as any, distinctId: 'single-distinct' }]

            const result = await repository.fetchPersonsByDistinctIds(teamPersons)

            expect(result).toHaveLength(1)
            expect(result[0].distinct_id).toBe('single-distinct')
            expect(result[0].uuid).toBe(person.uuid)
            expect(result[0].team_id).toBe(team.id)
            expect(result[0].properties.name).toBe('Single Person')
        })

        it('should handle duplicate team/distinctId pairs', async () => {
            const person = await createTestPerson(team.id, 'duplicate-distinct', { name: 'Duplicate Person' })

            const teamPersons = [
                { teamId: team.id as any, distinctId: 'duplicate-distinct' },
                { teamId: team.id as any, distinctId: 'duplicate-distinct' }, // Same pair
            ]

            const result = await repository.fetchPersonsByDistinctIds(teamPersons)

            // Should only return one result even though we queried twice
            expect(result).toHaveLength(1)
            expect(result[0].distinct_id).toBe('duplicate-distinct')
            expect(result[0].uuid).toBe(person.uuid)
        })

        it('should include all required fields in InternalPersonWithDistinctId', async () => {
            const person = await createTestPerson(team.id, 'fields-test', { name: 'Fields Test', age: 25 })

            const teamPersons = [{ teamId: team.id as any, distinctId: 'fields-test' }]

            const result = await repository.fetchPersonsByDistinctIds(teamPersons)

            expect(result).toHaveLength(1)
            const personResult = result[0]

            // Check all InternalPerson fields are present
            expect(personResult.id).toBe(person.id)
            expect(personResult.uuid).toBe(person.uuid)
            expect(personResult.properties).toEqual({ name: 'Fields Test', age: 25 })
            expect(personResult.created_at).toEqual(person.created_at)
            expect(personResult.version).toBe(person.version)
            expect(personResult.is_user_id).toBe(person.is_user_id)
            expect(personResult.is_identified).toBe(person.is_identified)
            expect(personResult.team_id).toBe(person.team_id)

            // Check the additional distinct_id field
            expect(personResult.distinct_id).toBe('fields-test')
        })
    })

    describe('fetchPersonsByPersonIds', () => {
        it('should return empty array when no team persons provided', async () => {
            const result = await repository.fetchPersonsByPersonIds([])
            expect(result).toEqual([])
        })

        it.each([
            ['single team', 1],
            ['multiple teams', 2],
        ])('should fetch persons by person IDs (%s)', async (_label, teamCount) => {
            const team1 = team
            const team2Id = teamCount > 1 ? await createTeam(postgres, team1.organization_id) : team1.id

            const person1 = await createTestPerson(team1.id, 'pid-test-1', { name: 'Person 1' })
            const person2 =
                teamCount > 1
                    ? await createTestPerson(team2Id, 'pid-test-2', { name: 'Person 2' })
                    : await createTestPerson(team1.id, 'pid-test-2', { name: 'Person 2' })

            const teamPersons = [
                { teamId: team1.id, personId: person1.uuid },
                { teamId: team2Id, personId: person2.uuid },
            ]
            const result = await repository.fetchPersonsByPersonIds(teamPersons)

            expect(result).toHaveLength(2)
            expect(result.map((p) => p.uuid)).toEqual(expect.arrayContaining([person1.uuid, person2.uuid]))
        })

        it('should not return persons from a different team even if their IDs were referenced', async () => {
            const team1 = team
            const team2Id = await createTeam(postgres, team1.organization_id)

            const team1Person = await createTestPerson(team1.id, 'cross-team-1', { name: 'Team 1 Person' })
            const team2Person = await createTestPerson(team2Id, 'cross-team-2', { name: 'Team 2 Person' })

            const teamPersons = [
                { teamId: team2Id, personId: team1Person.uuid },
                { teamId: team1.id, personId: team2Person.uuid },
            ]
            const result = await repository.fetchPersonsByPersonIds(teamPersons)

            // Neither pair matches the actual (team_id, person_id) in the DB
            expect(result).toHaveLength(0)
        })

        it('should handle non-existent person IDs gracefully', async () => {
            const person = await createTestPerson(team.id, 'existing-person', { name: 'Existing' })
            const nonExistentId = new UUIDT().toString()

            const result = await repository.fetchPersonsByPersonIds([
                { teamId: team.id, personId: person.uuid },
                { teamId: team.id, personId: nonExistentId },
            ])

            expect(result).toHaveLength(1)
            expect(result[0].uuid).toBe(person.uuid)
        })

        it('should deduplicate repeated (teamId, personId) pairs', async () => {
            const person = await createTestPerson(team.id, 'dedup-person', { name: 'Dedup' })

            const result = await repository.fetchPersonsByPersonIds([
                { teamId: team.id, personId: person.uuid },
                { teamId: team.id, personId: person.uuid },
            ])

            expect(result).toHaveLength(1)
            expect(result[0].uuid).toBe(person.uuid)
        })
    })

    describe('fetchDistinctIdsForPersons', () => {
        it('returns empty object when no person ids provided', async () => {
            const result = await repository.fetchDistinctIdsForPersons(team.id, [])
            expect(result).toEqual({})
        })

        it('returns distinct_ids keyed by int person_id, capped per person', async () => {
            const person1 = await createTestPerson(team.id, 'distinct-1-a', { name: 'Person 1' })
            await repository.addDistinctId(person1, 'distinct-1-b', 0)
            await repository.addDistinctId(person1, 'distinct-1-c', 0)
            const person2 = await createTestPerson(team.id, 'distinct-2-a', { name: 'Person 2' })

            const all = await repository.fetchDistinctIdsForPersons(team.id, [person1.id, person2.id])
            expect(all[person1.id]).toEqual(expect.arrayContaining(['distinct-1-a', 'distinct-1-b', 'distinct-1-c']))
            expect(all[person1.id]).toHaveLength(3)
            expect(all[person2.id]).toEqual(['distinct-2-a'])

            const limited = await repository.fetchDistinctIdsForPersons(team.id, [person1.id], {
                limitPerPerson: 1,
            })
            // Ordered by insertion (id ASC), so the cap keeps the first one
            expect(limited[person1.id]).toEqual(['distinct-1-a'])
        })

        it('omits persons that have no distinct_ids in the target team', async () => {
            const team1 = team
            const team2Id = await createTeam(postgres, team1.organization_id)
            const personInTeam2 = await createTestPerson(team2Id, 'team2-only', { name: 'Team 2' })

            const result = await repository.fetchDistinctIdsForPersons(team1.id, [personInTeam2.id])
            expect(result).toEqual({})
        })
    })

    describe('personPropertiesSize', () => {
        it('should return properties size for existing person', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', {
                name: 'John Doe',
                email: '[email protected]',
                age: 30,
                preferences: {
                    theme: 'dark',
                    notifications: true,
                },
            })

            const size = await repository.personPropertiesSize(person.id, person.team_id)

            expect(size).toBeGreaterThan(0)
            expect(typeof size).toBe('number')
        })

        it('should return 0 for non-existent person', async () => {
            const fakePersonId = '999999' // Use a numeric ID instead of UUID
            const size = await repository.personPropertiesSize(fakePersonId, team.id)

            expect(size).toBe(0)
        })

        it('should handle different persons correctly', async () => {
            const team1 = team
            const team2Id = await createTeam(hub.postgres, team1.organization_id)

            // Create person in team 1
            const person1 = await createTestPerson(team1.id, 'shared-distinct', { name: 'Team 1 Person' })

            // Create person in team 2
            const person2 = await createTestPerson(team2Id, 'different-distinct', { name: 'Team 2 Person' })

            // Check size for person 1
            const size1 = await repository.personPropertiesSize(person1.id, team1.id)
            expect(size1).toBeGreaterThan(0)

            // Check size for person 2
            const size2 = await repository.personPropertiesSize(person2.id, team2Id)
            expect(size2).toBeGreaterThan(0)
        })

        it('should return larger size for person with more properties', async () => {
            // Create person with minimal properties
            const minimalPerson = await createTestPerson(team.id, 'minimal-person', { name: 'Minimal' })
            const minimalSize = await repository.personPropertiesSize(minimalPerson.id, team.id)

            // Create person with extensive properties
            const extensiveProperties = {
                name: 'Extensive Person',
                email: '[email protected]',
                age: 25,
                address: {
                    street: '123 Main St',
                    city: 'New York',
                    state: 'NY',
                    zip: '10001',
                    country: 'USA',
                },
                preferences: {
                    theme: 'light',
                    notifications: true,
                    privacy: {
                        shareData: false,
                        marketingEmails: true,
                    },
                },
                metadata: {
                    source: 'web',
                    campaign: 'summer2024',
                    tags: ['premium', 'active'],
                },
            }
            const extensivePerson = await createTestPerson(team.id, 'extensive-person', extensiveProperties)
            const extensiveSize = await repository.personPropertiesSize(extensivePerson.id, team.id)

            expect(extensiveSize).toBeGreaterThan(minimalSize)
        })
    })

    describe('updatePerson', () => {
        it('should update person properties successfully', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John', age: 25 })

            const update = { properties: { name: 'Jane', age: 30, city: 'New York' } }
            const [updatedPerson, messages, versionDisparity] = await repository.updatePerson(
                person,
                createPersonUpdateFields(person, update)
            )

            expect(updatedPerson.properties).toEqual({ name: 'Jane', age: 30, city: 'New York' })
            expect(updatedPerson.version).toBe(person.version + 1)
            expect(messages).toHaveLength(1)
            expect(versionDisparity).toBe(false)

            // Verify the update was actually persisted
            const fetchedPerson = await repository.fetchPerson(team.id, 'test-distinct')
            expect(fetchedPerson?.properties).toEqual({ name: 'Jane', age: 30, city: 'New York' })
            expect(fetchedPerson?.version).toBe(person.version + 1)
        })

        it('should update is_identified field', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            const update = { is_identified: true }
            const [updatedPerson, messages] = await repository.updatePerson(
                person,
                createPersonUpdateFields(person, update)
            )

            expect(updatedPerson.is_identified).toBe(true)
            expect(updatedPerson.version).toBe(person.version + 1)
            expect(messages).toHaveLength(1)
        })

        it('should handle version conflicts correctly', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            // First update
            const update1 = { properties: { name: 'Jane' } }
            const [updatedPerson1, _messages1] = await repository.updatePerson(
                person,
                createPersonUpdateFields(person, update1)
            )

            // Second update with the updated person (should succeed since we're using the latest version)
            const update2 = { properties: { age: 30 } }
            const [updatedPerson2, messages2] = await repository.updatePerson(
                updatedPerson1,
                createPersonUpdateFields(updatedPerson1, update2)
            )

            // updatePerson replaces properties entirely, so we expect only the age property
            expect(updatedPerson2.properties).toEqual({ age: 30 })
            expect(updatedPerson2.version).toBe(updatedPerson1.version + 1)
            expect(messages2).toHaveLength(1)
        })

        it('should handle transaction parameter correctly', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            await postgres.transaction(PostgresUse.PERSONS_WRITE, 'test-transaction', async (tx) => {
                const update = { properties: { name: 'Jane' } }
                const [updatedPerson, messages] = await repository.updatePerson(
                    person,
                    createPersonUpdateFields(person, update),
                    'tx',
                    tx
                )

                expect(updatedPerson.properties).toEqual({ name: 'Jane' })
                expect(messages).toHaveLength(1)
            })

            // Verify after transaction commits
            const fetchedPerson = await repository.fetchPerson(team.id, 'test-distinct')
            expect(fetchedPerson?.properties).toEqual({ name: 'Jane' })
        })

        it('should handle tag parameter correctly', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            const update = { properties: { name: 'Jane' } }
            const [updatedPerson, messages] = await repository.updatePerson(
                person,
                createPersonUpdateFields(person, update),
                'test-tag'
            )

            expect(updatedPerson.properties).toEqual({ name: 'Jane' })
            expect(messages).toHaveLength(1)
        })

        it('should throw NoRowsUpdatedError when person does not exist', async () => {
            const nonExistentPerson: InternalPerson = {
                id: '1234567890',
                team_id: team.id,
                uuid: 'non-existent-uuid',
                created_at: DateTime.now(),
                properties: {},
                is_identified: false,
                version: 0,
                is_user_id: null,
                properties_last_updated_at: {},
                properties_last_operation: {},
                last_seen_at: null,
            }

            const update = { properties: { name: 'Jane' } }
            await expect(
                repository.updatePerson(nonExistentPerson, createPersonUpdateFields(nonExistentPerson, update))
            ).rejects.toThrow(NoRowsUpdatedError)
        })

        it('should handle updatePersonAssertVersion with optimistic concurrency control', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            // Create a PersonUpdate object
            const personUpdate = {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: 'test-distinct',
                properties: { name: 'Jane', age: 30 },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }

            // First update should succeed
            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBe(person.version + 1)
            expect(messages).toHaveLength(1)

            // Verify the person was actually updated
            const updatedPerson = await repository.fetchPerson(team.id, 'test-distinct')
            expect(updatedPerson?.properties).toEqual({ name: 'Jane', age: 30 })
            expect(updatedPerson?.version).toBe(person.version + 1)
        })

        it('should handle updatePersonAssertVersion with version mismatch', async () => {
            const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })

            // Create a PersonUpdate with an outdated version
            const personUpdate = {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: 'test-distinct',
                properties: { name: 'Jane', age: 30 },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version - 1, // Outdated version
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }

            // Update should fail due to version mismatch
            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBeUndefined()
            expect(messages).toHaveLength(0)

            // Verify the person was not updated
            const unchangedPerson = await repository.fetchPerson(team.id, 'test-distinct')
            expect(unchangedPerson?.properties).toEqual({ name: 'John' })
            expect(unchangedPerson?.version).toBe(person.version)
        })

        it('should handle updatePersonAssertVersion with non-existent person', async () => {
            // Create a PersonUpdate for a non-existent person
            const personUpdate = {
                id: '999999',
                team_id: team.id,
                uuid: '00000000-0000-0000-0000-000000000000',
                distinct_id: 'test-distinct',
                properties: { name: 'Jane' },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: DateTime.now(),
                version: 0,
                is_identified: false,
                is_user_id: null,
                last_seen_at: null,
                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,
            }

            // Update should fail because person doesn't exist
            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBeUndefined()
            expect(messages).toHaveLength(0)
        })

        it('should merge properties_to_set into properties when updating', async () => {
            const person = await createTestPerson(team.id, 'test-merge-set', { existing: 'value', to_update: 'old' })

            const personUpdate = {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: 'test-merge-set',
                properties: { existing: 'value', to_update: 'old' }, // Original properties from DB
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }

            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBe(person.version + 1)
            expect(messages).toHaveLength(1)

            const updatedPerson = await repository.fetchPerson(team.id, 'test-merge-set')
            expect(updatedPerson?.properties).toEqual({
                existing: 'value',
                to_update: 'new', // Updated from properties_to_set
                new_prop: 'new_value', // Added from properties_to_set
            })
        })

        it('should apply properties_to_unset when updating', async () => {
            const person = await createTestPerson(team.id, 'test-unset', {
                keep: 'value',
                remove_me: 'will be removed',
            })

            const personUpdate = {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: 'test-unset',
                properties: { keep: 'value', remove_me: 'will be removed' },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }

            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBe(person.version + 1)
            expect(messages).toHaveLength(1)

            const updatedPerson = await repository.fetchPerson(team.id, 'test-unset')
            expect(updatedPerson?.properties).toEqual({ keep: 'value' })
            expect(updatedPerson?.properties).not.toHaveProperty('remove_me')
        })

        it('should handle combined properties_to_set and properties_to_unset', async () => {
            const person = await createTestPerson(team.id, 'test-combined', {
                keep: 'value',
                remove: 'will go',
                update: 'old',
            })

            const personUpdate = {
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: 'test-combined',
                properties: { keep: 'value', remove: 'will go', update: 'old' },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            }

            const [actualVersion, messages] = await repository.updatePersonAssertVersion(personUpdate)

            expect(actualVersion).toBe(person.version + 1)
            expect(messages).toHaveLength(1)

            const updatedPerson = await repository.fetchPerson(team.id, 'test-combined')
            expect(updatedPerson?.properties).toEqual({
                keep: 'value',
                update: 'new',
                added: 'fresh',
            })
            expect(updatedPerson?.properties).not.toHaveProperty('remove')
        })
    })

    describe('updateCohortsAndFeatureFlagsForMerge()', () => {
        let sourcePersonID: InternalPerson['id']
        let targetPersonID: InternalPerson['id']

        async function getAllHashKeyOverrides(): Promise<any> {
            const result = await hub.postgres.query(
                PostgresUse.PERSONS_WRITE,
                'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride WHERE team_id = $1',
                [team.id],
                ''
            )
            return result.rows
        }

        beforeEach(async () => {
            const result = await repository.createPerson(
                TIMESTAMP,
                {},
                {},
                {},
                team.id,
                null,
                false,
                new UUIDT().toString(),
                { distinctId: 'source_person' }
            )
            if (!result.success) {
                throw new Error('Failed to create person')
            }
            const sourcePerson = result.person
            const kafkaMessagesSourcePerson = result.messages

            const result2 = await repository.createPerson(
                TIMESTAMP,
                {},
                {},
                {},
                team.id,
                null,
                false,
                new UUIDT().toString(),
                { distinctId: 'target_person' }
            )
            if (!result2.success) {
                throw new Error('Failed to create person')
            }
            const targetPerson = result2.person

            const personOutputs = new IngestionOutputs({
                [PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
                [PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
                    PERSON_DISTINCT_IDS_OUTPUT,
                    KAFKA_PERSON_DISTINCT_ID,
                    mockProducer,
                    'test'
                ),
            })
            await Promise.all(
                kafkaMessagesSourcePerson.map((msg) =>
                    personOutputs.produce(msg.output, { value: msg.value, key: null })
                )
            )
            sourcePersonID = sourcePerson.id
            targetPersonID = targetPerson.id
        })

        it("doesn't fail on empty data", async () => {
            await repository.updateCohortsAndFeatureFlagsForMerge(team.id, sourcePersonID, targetPersonID)
        })

        it('updates all valid keys when target person had no overrides', async () => {
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: sourcePersonID,
                feature_flag_key: 'aloha',
                hash_key: 'override_value_for_aloha',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: sourcePersonID,
                feature_flag_key: 'beta-feature',
                hash_key: 'override_value_for_beta_feature',
            })

            await repository.updateCohortsAndFeatureFlagsForMerge(team.id, sourcePersonID, targetPersonID)

            const result = await getAllHashKeyOverrides()

            expect(result.length).toEqual(2)
            expect(result).toEqual(
                expect.arrayContaining([
                    {
                        feature_flag_key: 'aloha',
                        hash_key: 'override_value_for_aloha',
                        person_id: targetPersonID,
                    },
                    {
                        feature_flag_key: 'beta-feature',
                        hash_key: 'override_value_for_beta_feature',
                        person_id: targetPersonID,
                    },
                ])
            )
        })

        it('updates all valid keys when conflicts with target person', async () => {
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: sourcePersonID,
                feature_flag_key: 'aloha',
                hash_key: 'override_value_for_aloha',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: sourcePersonID,
                feature_flag_key: 'beta-feature',
                hash_key: 'override_value_for_beta_feature',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: targetPersonID,
                feature_flag_key: 'beta-feature',
                hash_key: 'existing_override_value_for_beta_feature',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: sourcePersonID,
                feature_flag_key: 'gamma',
                hash_key: 'override_value_for_gamma',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: targetPersonID,
                feature_flag_key: 'gamma',
                hash_key: COOKIELESS_SENTINEL_VALUE,
            })

            await repository.updateCohortsAndFeatureFlagsForMerge(team.id, sourcePersonID, targetPersonID)

            const result = await getAllHashKeyOverrides()

            expect(result.length).toEqual(3)
            expect(result).toEqual(
                expect.arrayContaining([
                    {
                        feature_flag_key: 'beta-feature',
                        hash_key: 'existing_override_value_for_beta_feature',
                        person_id: targetPersonID,
                    },
                    {
                        feature_flag_key: 'aloha',
                        hash_key: 'override_value_for_aloha',
                        person_id: targetPersonID,
                    },
                    {
                        feature_flag_key: 'gamma',
                        hash_key: 'override_value_for_gamma',
                        person_id: targetPersonID,
                    },
                ])
            )
        })

        it('updates nothing when target person overrides exist', async () => {
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: targetPersonID,
                feature_flag_key: 'aloha',
                hash_key: 'override_value_for_aloha',
            })
            await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                team_id: team.id,
                person_id: targetPersonID,
                feature_flag_key: 'beta-feature',
                hash_key: 'override_value_for_beta_feature',
            })

            await repository.updateCohortsAndFeatureFlagsForMerge(team.id, sourcePersonID, targetPersonID)

            const result = await getAllHashKeyOverrides()

            expect(result.length).toEqual(2)
            expect(result).toEqual(
                expect.arrayContaining([
                    {
                        feature_flag_key: 'aloha',
                        hash_key: 'override_value_for_aloha',
                        person_id: targetPersonID,
                    },
                    {
                        feature_flag_key: 'beta-feature',
                        hash_key: 'override_value_for_beta_feature',
                        person_id: targetPersonID,
                    },
                ])
            )
        })
    })

    describe('person properties size violation handling', () => {
        let oversizedRepository: PostgresPersonRepository

        beforeEach(() => {
            oversizedRepository = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 0,
                personPropertiesDbConstraintLimitBytes: 50,
                personPropertiesTrimTargetBytes: 25,
            })
        })

        describe('trimPropertiesToFitSize', () => {
            it('should return original properties if they are under the size limit', () => {
                const properties = { name: 'John', age: 30 }
                const targetSize = 1000

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toEqual(properties)
            })

            it('should remove properties to fit under size limit', () => {
                const properties = {
                    name: 'John Doe',
                    email: '[email protected]',
                    description: 'A very long description that takes up a lot of space',
                    age: 30,
                    city: 'New York',
                }
                const targetSize = 50

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(Object.keys(result).length).toBeLessThan(Object.keys(properties).length)
                expect(Buffer.byteLength(JSON.stringify(result), 'utf8')).toBeLessThanOrEqual(targetSize)
            })

            it('should preserve protected properties even when trimming', () => {
                const properties = {
                    description: 'A very long description that takes up a lot of space',
                    age: 30,
                    customField: 'some custom data',
                    name: 'John Doe',
                    email: '[email protected]',
                }
                const targetSize = 50

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toHaveProperty('name')
                expect(result).toHaveProperty('email')

                expect(Buffer.byteLength(JSON.stringify(result), 'utf8')).toBeLessThanOrEqual(targetSize)
            })

            it('should handle empty properties object', () => {
                const properties = {}
                const targetSize = 50

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toEqual({})
            })

            it('should preserve protected properties even when removing in alphabetical order', () => {
                const properties = {
                    zebra: 'last in alphabet',
                    email: '[email protected]',
                    apple: 'first in alphabet',
                    banana: 'middle in alphabet',
                    cherry: 'also middle',
                }
                const targetSize = 70

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toHaveProperty('email')
                expect(result).toHaveProperty('zebra')
                expect(result).not.toHaveProperty('banana')
                expect(Buffer.byteLength(JSON.stringify(result), 'utf8')).toBeLessThanOrEqual(targetSize + 50)
            })

            it('should process properties in deterministic alphabetical order', () => {
                const properties = {
                    z_property: '1',
                    a_property: '2',
                    m_property: '3',
                    b_property: '4',
                }
                const targetSize = 25

                const result1 = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                const result2 = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result1).toEqual(result2)

                const remainingKeys = Object.keys(result1).sort()
                if (remainingKeys.length > 0) {
                    expect(remainingKeys).toContain('z_property')
                }
            })
        })

        describe('PersonPropertiesSizeViolationError', () => {
            it('should create error with correct properties', () => {
                const error = new PersonPropertiesSizeViolationError('Test message', 123, 'person-id', 'distinct-id')

                expect(error.message).toBe('Test message')
                expect(error.teamId).toBe(123)
                expect(error.personId).toBe('person-id')
                expect(error.distinctId).toBe('distinct-id')
                expect(error.name).toBe('PersonPropertiesSizeViolationError')
            })
        })

        describe('createPerson with oversized properties', () => {
            it('should throw PersonPropertiesSizeViolationError when properties exceed size limit', async () => {
                const uuid = new UUIDT().toString()
                const oversizedProperties = {
                    description: 'x'.repeat(200),
                }

                const originalQuery = postgres.query.bind(postgres)
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('INSERT INTO posthog_person')) {
                        const error = new Error('Check constraint violation')
                        ;(error as any).code = '23514'
                        ;(error as any).constraint = 'check_properties_size'
                        throw error
                    }
                    return originalQuery(use, query, values, tag)
                })

                await expect(
                    oversizedRepository.createPerson(
                        TIMESTAMP,
                        oversizedProperties,
                        {},
                        {},
                        team.id,
                        null,
                        true,
                        uuid,
                        { distinctId: 'test-oversized' }
                    )
                ).rejects.toThrow(PersonPropertiesSizeViolationError)

                await expect(
                    oversizedRepository.createPerson(
                        TIMESTAMP,
                        oversizedProperties,
                        {},
                        {},
                        team.id,
                        null,
                        true,
                        uuid,
                        { distinctId: 'test-oversized-2' }
                    )
                ).rejects.toThrow('Person properties create would exceed size limit')

                mockQuery.mockRestore()
            })
        })

        describe('updatePerson with oversized properties', () => {
            it('should trim existing oversized person properties and update successfully', async () => {
                const normalPerson = await createTestPerson(team.id, 'test-oversized-update', {
                    name: 'John',
                    description: 'x'.repeat(120),
                })

                const mockPersonPropertiesSize = jest
                    .spyOn(oversizedRepository, 'personPropertiesSize')
                    .mockResolvedValue(60)

                const oversizedUpdate = {
                    properties: {
                        name: 'John Updated',
                        description: 'x'.repeat(120),
                        newField: 'y'.repeat(50),
                    },
                }

                const [updatedPerson, messages] = await oversizedRepository.updatePerson(
                    normalPerson,
                    createPersonUpdateFields(normalPerson, oversizedUpdate)
                )

                expect(updatedPerson).toBeDefined()
                expect(updatedPerson.version).toBe(normalPerson.version + 1)
                expect(messages).toHaveLength(1)
                expect(Object.keys(updatedPerson.properties).length).toBeLessThanOrEqual(3)

                mockPersonPropertiesSize.mockRestore()
            })

            it('should reject update when current person is under limit but update would exceed it', async () => {
                const normalPerson = await createTestPerson(team.id, 'test-normal-person', { name: 'John' })

                const mockPersonPropertiesSize = jest
                    .spyOn(oversizedRepository, 'personPropertiesSize')
                    .mockResolvedValue(30)

                const originalQuery = postgres.query.bind(postgres)
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('UPDATE posthog_person SET')) {
                        const error = new Error('Check constraint violation')
                        ;(error as any).code = '23514'
                        ;(error as any).constraint = 'check_properties_size'
                        throw error
                    }
                    return originalQuery(use, query, values, tag)
                })

                const oversizedUpdate = {
                    properties: {
                        description: 'x'.repeat(200),
                    },
                }

                await expect(
                    oversizedRepository.updatePerson(
                        normalPerson,
                        createPersonUpdateFields(normalPerson, oversizedUpdate)
                    )
                ).rejects.toThrow(PersonPropertiesSizeViolationError)
                await expect(
                    oversizedRepository.updatePerson(
                        normalPerson,
                        createPersonUpdateFields(normalPerson, oversizedUpdate)
                    )
                ).rejects.toThrow('Person properties update would exceed size limit')

                mockPersonPropertiesSize.mockRestore()
                mockQuery.mockRestore()
            })

            it('should fail gracefully when trimming fails', async () => {
                const normalPerson = await createTestPerson(team.id, 'test-trim-failure', {
                    name: 'John',
                    description: 'x'.repeat(120),
                })

                const mockPersonPropertiesSize = jest
                    .spyOn(oversizedRepository, 'personPropertiesSize')
                    .mockResolvedValue(60)

                const originalQuery = postgres.query.bind(postgres)
                let updateCallCount = 0
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('UPDATE posthog_person SET')) {
                        updateCallCount++
                        if (updateCallCount === 1) {
                            const error = new Error('Check constraint violation')
                            ;(error as any).code = '23514'
                            ;(error as any).constraint = 'check_properties_size'
                            throw error
                        } else if (updateCallCount === 2) {
                            throw new Error('Trimming update failed')
                        }
                    }
                    return originalQuery(use, query, values, tag)
                })

                const oversizedUpdate = {
                    properties: {
                        name: 'John Updated',
                        description: 'x'.repeat(120),
                        newField: 'y'.repeat(50),
                    },
                }

                await expect(
                    oversizedRepository.updatePerson(
                        normalPerson,
                        createPersonUpdateFields(normalPerson, oversizedUpdate)
                    )
                ).rejects.toThrow(PersonPropertiesSizeViolationError)

                updateCallCount = 0
                await expect(
                    oversizedRepository.updatePerson(
                        normalPerson,
                        createPersonUpdateFields(normalPerson, oversizedUpdate)
                    )
                ).rejects.toThrow('Person properties update failed after trying to trim oversized properties')

                mockPersonPropertiesSize.mockRestore()
                mockQuery.mockRestore()
            })

            it('should fail when protected properties alone exceed size limit and cannot be trimmed', async () => {
                const largeProtectedProperties = {
                    name: 'John Doe with a very long name that takes up significant space',
                    email: 'john.doe.with.an.extremely.long.email.address.that.should.be.protected@example.com',
                    utm_source: 'x'.repeat(30),
                    utm_medium: 'x'.repeat(30),
                    utm_campaign: 'x'.repeat(30),
                    utm_content: 'x'.repeat(30),
                    utm_term: 'x'.repeat(30),
                    $browser: 'Chrome with very long user agent string information',
                    $browser_version: 'Version 120.0.0.0 with extended metadata',
                    $os: 'Operating System with detailed version information',
                    $device_type: 'Desktop computer with specific hardware details',
                    $current_url:
                        'https://example.com/very/long/path/with/many/segments/and/parameters?param1=value1&param2=value2',
                    $referring_domain: 'referring-domain-with-long-name.example.com',
                    $referrer: 'https://referring-site.com/with/very/long/path/that/contains/many/details',
                    description: 'This is a trimmable property',
                    customData: 'This can be removed',
                }

                const oversizedPerson = await createTestPerson(
                    team.id,
                    'test-protected-oversized',
                    largeProtectedProperties
                )

                const mockPersonPropertiesSize = jest
                    .spyOn(oversizedRepository, 'personPropertiesSize')
                    .mockResolvedValue(60)

                const originalQuery = postgres.query.bind(postgres)
                let updateCallCount = 0
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('UPDATE posthog_person SET')) {
                        updateCallCount++

                        const error = new Error('Check constraint violation')
                        ;(error as any).code = '23514'
                        ;(error as any).constraint = 'check_properties_size'
                        throw error
                    }
                    return originalQuery(use, query, values, tag)
                })

                const update = {
                    properties: {
                        $app_name: 'Application name with detailed information',
                        $app_version: 'Version 1.2.3 with build metadata',
                    },
                }

                await expect(
                    oversizedRepository.updatePerson(oversizedPerson, createPersonUpdateFields(oversizedPerson, update))
                ).rejects.toThrow(PersonPropertiesSizeViolationError)

                expect(updateCallCount).toBe(2)

                updateCallCount = 0
                await expect(
                    oversizedRepository.updatePerson(oversizedPerson, createPersonUpdateFields(oversizedPerson, update))
                ).rejects.toThrow('Person properties update failed after trying to trim oversized properties')

                expect(updateCallCount).toBe(2)

                mockPersonPropertiesSize.mockRestore()
                mockQuery.mockRestore()
            })

            it('should demonstrate that trimPropertiesToFitSize cannot reduce protected properties below size limit', () => {
                const protectedPropertiesExceedingLimit = {
                    name: 'A very long name that takes up space',
                    email: '[email protected]',
                    utm_source: 'x'.repeat(50),
                    utm_medium: 'x'.repeat(50),
                    description: 'This should be removed',
                    customField: 'This should also be removed',
                }

                const targetSize = 30

                const result = (oversizedRepository as any).trimPropertiesToFitSize(
                    protectedPropertiesExceedingLimit,
                    targetSize
                )

                expect(result).toHaveProperty('name')
                expect(result).toHaveProperty('email')
                expect(result).toHaveProperty('utm_source')
                expect(result).toHaveProperty('utm_medium')

                expect(result).not.toHaveProperty('description')
                expect(result).not.toHaveProperty('customField')

                const finalSize = Buffer.byteLength(JSON.stringify(result), 'utf8')
                expect(finalSize).toBeGreaterThan(targetSize)
            })
        })

        describe('updatePersonAssertVersion with oversized properties', () => {
            it('should throw PersonPropertiesSizeViolationError when properties exceed size limit', async () => {
                const person = await createTestPerson(team.id, 'test-assert-oversized', { name: 'John' })

                const originalQuery = postgres.query.bind(postgres)
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('UPDATE posthog_person SET')) {
                        const error = new Error('Check constraint violation')
                        ;(error as any).code = '23514'
                        ;(error as any).constraint = 'check_properties_size'
                        throw error
                    }
                    return originalQuery(use, query, values, tag)
                })

                const personUpdate = {
                    id: person.id,
                    team_id: person.team_id,
                    uuid: person.uuid,
                    distinct_id: 'test-assert-oversized',
                    properties: {
                        name: 'John',
                        description: 'x'.repeat(150),
                    },
                    properties_last_updated_at: {},
                    properties_last_operation: {},
                    created_at: person.created_at,
                    version: person.version,
                    is_identified: person.is_identified,
                    is_user_id: person.is_user_id,
                    last_seen_at: person.last_seen_at,
                    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,
                }

                await expect(oversizedRepository.updatePersonAssertVersion(personUpdate)).rejects.toThrow(
                    PersonPropertiesSizeViolationError
                )
                await expect(oversizedRepository.updatePersonAssertVersion(personUpdate)).rejects.toThrow(
                    'Person properties update would exceed size limit'
                )

                mockQuery.mockRestore()
            })
        })

        describe('new metrics and error handling', () => {
            it('should increment personPropertiesSizeViolationCounter with correct labels', async () => {
                const uuid = new UUIDT().toString()
                const oversizedProperties = {
                    description: 'x'.repeat(200),
                }

                const originalQuery = postgres.query.bind(postgres)
                const mockQuery = jest.spyOn(postgres, 'query').mockImplementation(async (use, query, values, tag) => {
                    if (typeof query === 'string' && query.includes('INSERT INTO posthog_person')) {
                        const error = new Error('Check constraint violation')
                        ;(error as any).code = '23514'
                        ;(error as any).constraint = 'check_properties_size'
                        throw error
                    }
                    return originalQuery(use, query, values, tag)
                })

                const metrics = require('~/common/persons/metrics')
                const mockInc = jest.fn()
                const originalInc = metrics.personPropertiesSizeViolationCounter.inc
                metrics.personPropertiesSizeViolationCounter.inc = mockInc

                try {
                    await oversizedRepository.createPerson(
                        TIMESTAMP,
                        oversizedProperties,
                        {},
                        {},
                        team.id,
                        null,
                        true,
                        uuid,
                        { distinctId: 'test-metrics' }
                    )
                } catch {}

                expect(mockInc).toHaveBeenCalledWith({
                    violation_type: 'create_person_size_violation',
                })

                metrics.personPropertiesSizeViolationCounter.inc = originalInc
                mockQuery.mockRestore()
            })

            it('should increment oversizedPersonPropertiesTrimmedCounter when trimming succeeds', async () => {
                const person = await createTestPerson(team.id, 'test-trimming-metrics', {
                    name: 'John',
                    description: 'x'.repeat(120),
                })

                const mockPersonPropertiesSize = jest
                    .spyOn(oversizedRepository, 'personPropertiesSize')
                    .mockResolvedValue(60)

                const metrics = require('~/common/persons/metrics')
                const mockInc = jest.fn()
                const originalInc = metrics.oversizedPersonPropertiesTrimmedCounter.inc
                metrics.oversizedPersonPropertiesTrimmedCounter.inc = mockInc

                const oversizedUpdate = {
                    properties: {
                        name: 'John Updated',
                        description: 'x'.repeat(120),
                        newField: 'y'.repeat(50),
                    },
                }

                try {
                    await oversizedRepository.updatePerson(person, createPersonUpdateFields(person, oversizedUpdate))
                    expect(mockInc).toHaveBeenCalledWith({ result: 'success' })
                } catch {}

                mockPersonPropertiesSize.mockRestore()
                metrics.oversizedPersonPropertiesTrimmedCounter.inc = originalInc
            })
        })

        describe('handleOversizedPersonProperties and related methods', () => {
            it('should test trimPropertiesToFitSize respects protected properties', () => {
                const properties = {
                    email: '[email protected]',
                    name: 'John Doe',
                    $browser: 'Chrome',
                    utm_source: 'google',
                    description: 'A very long description that should be removed',
                    largeData: 'x'.repeat(100),
                    moreData: 'y'.repeat(50),
                }
                const targetSize = 100

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toHaveProperty('email', '[email protected]')
                expect(result).toHaveProperty('name', 'John Doe')
                expect(result).toHaveProperty('$browser', 'Chrome')
                expect(result).toHaveProperty('utm_source', 'google')

                expect(Object.keys(result).length).toBeLessThan(Object.keys(properties).length)
                expect(Buffer.byteLength(JSON.stringify(result), 'utf8')).toBeLessThanOrEqual(targetSize + 50) // Some tolerance for protected properties
            })

            it('should handle constraint violation detection correctly', () => {
                const sizeViolationError = {
                    code: '23514',
                    constraint: 'check_properties_size',
                }

                const otherError = {
                    code: '23505',
                    constraint: 'unique_constraint',
                }

                expect((oversizedRepository as any).isPropertiesSizeConstraintViolation(sizeViolationError)).toBe(true)
                expect((oversizedRepository as any).isPropertiesSizeConstraintViolation(otherError)).toBe(false)
                expect((oversizedRepository as any).isPropertiesSizeConstraintViolation(null)).toBe(false)
                expect((oversizedRepository as any).isPropertiesSizeConstraintViolation(undefined)).toBe(false)
            })
        })

        describe('protected properties during trimming', () => {
            it('should respect default protected properties', () => {
                const properties = {
                    email: '[email protected]',
                    name: 'John Doe',
                    utm_source: 'google',
                    description: 'A very long description that takes up space',
                    largeField: 'x'.repeat(100),
                    age: 30,
                }
                const targetSize = 60

                const result = (oversizedRepository as any).trimPropertiesToFitSize(properties, targetSize)

                expect(result).toHaveProperty('email', '[email protected]')
                expect(result).toHaveProperty('name', 'John Doe')
                expect(result).toHaveProperty('utm_source', 'google')

                expect(Object.keys(result).length).toBeLessThan(Object.keys(properties).length)
                expect(Buffer.byteLength(JSON.stringify(result), 'utf8')).toBeLessThanOrEqual(targetSize + 50) // Some tolerance
            })
        })
    })

    describe('calculate properties size feature flag', () => {
        it('should have identical output whether properties size calculation is enabled or disabled', async () => {
            const person1 = await createTestPerson(team.id, 'test-distinct-1', {
                name: 'John',
                age: 25,
                email: '[email protected]',
                largeProperty: 'x'.repeat(1000),
            })
            const person2 = await createTestPerson(team.id, 'test-distinct-2', {
                name: 'John',
                age: 25,
                email: '[email protected]',
                largeProperty: 'x'.repeat(1000),
            })

            const repositoryWithCalculation = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 100,
                personPropertiesDbConstraintLimitBytes: 1024 * 1024,
                personPropertiesTrimTargetBytes: 512 * 1024,
            })
            const repositoryWithoutCalculation = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 0,
                personPropertiesDbConstraintLimitBytes: 1024 * 1024,
                personPropertiesTrimTargetBytes: 512 * 1024,
            })

            const update = {
                properties: {
                    name: 'Jane',
                    age: 30,
                    city: 'New York',
                    anotherLargeProperty: 'y'.repeat(1500),
                },
            }

            const [updatedPerson1, messages1, versionDisparity1] = await repositoryWithCalculation.updatePerson(
                person1,
                createPersonUpdateFields(person1, update),
                'test-with-logging'
            )
            const [updatedPerson2, messages2, versionDisparity2] = await repositoryWithoutCalculation.updatePerson(
                person2,
                createPersonUpdateFields(person2, update),
                'test-without-logging'
            )

            expect(updatedPerson1.properties).toEqual(updatedPerson2.properties)
            expect(updatedPerson1.is_identified).toEqual(updatedPerson2.is_identified)
            expect(updatedPerson1.version).toEqual(updatedPerson2.version)
            expect(versionDisparity1).toEqual(versionDisparity2)
            expect(messages1).toHaveLength(messages2.length)

            const fetchedPerson1 = await repositoryWithCalculation.fetchPerson(team.id, 'test-distinct-1')
            const fetchedPerson2 = await repositoryWithoutCalculation.fetchPerson(team.id, 'test-distinct-2')

            expect(fetchedPerson1?.properties).toEqual(fetchedPerson2?.properties)
            expect(fetchedPerson1?.version).toEqual(fetchedPerson2?.version)
        })

        it('should have identical behavior for updatePersonAssertVersion regardless of logging configuration', async () => {
            const person1 = await createTestPerson(team.id, 'test-assert-1', { name: 'John', data: 'x'.repeat(2000) })
            const person2 = await createTestPerson(team.id, 'test-assert-2', { name: 'John', data: 'x'.repeat(2000) })

            const repositoryWithCalculation = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 100,
                personPropertiesDbConstraintLimitBytes: 1024 * 1024,
                personPropertiesTrimTargetBytes: 512 * 1024,
            })
            const repositoryWithoutCalculation = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 0,
                personPropertiesDbConstraintLimitBytes: 1024 * 1024,
                personPropertiesTrimTargetBytes: 512 * 1024,
            })

            const createPersonUpdate = (person: InternalPerson, distinctId: string) => ({
                id: person.id,
                team_id: person.team_id,
                uuid: person.uuid,
                distinct_id: distinctId,
                properties: { name: 'Jane', age: 30, data: 'y'.repeat(2500) },
                properties_last_updated_at: {},
                properties_last_operation: {},
                created_at: person.created_at,
                version: person.version,
                is_identified: person.is_identified,
                is_user_id: person.is_user_id,
                last_seen_at: person.last_seen_at,
                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,
            })

            const personUpdate1 = createPersonUpdate(person1, 'test-assert-1')
            const personUpdate2 = createPersonUpdate(person2, 'test-assert-2')

            const [actualVersion1, messages1] = await repositoryWithCalculation.updatePersonAssertVersion(personUpdate1)
            const [actualVersion2, messages2] =
                await repositoryWithoutCalculation.updatePersonAssertVersion(personUpdate2)

            expect(actualVersion1).toBeDefined()
            expect(actualVersion2).toBeDefined()
            expect(actualVersion1).toEqual(person1.version + 1)
            expect(actualVersion2).toEqual(person2.version + 1)
            expect(messages1).toHaveLength(messages2.length)

            const fetchedPerson1 = await repositoryWithCalculation.fetchPerson(team.id, 'test-assert-1')
            const fetchedPerson2 = await repositoryWithoutCalculation.fetchPerson(team.id, 'test-assert-2')

            expect(fetchedPerson1?.properties).toEqual(fetchedPerson2?.properties)
            expect(fetchedPerson1?.version).toEqual(fetchedPerson2?.version)
        })

        it('should work with default options (no logging)', async () => {
            const defaultRepository = new PostgresPersonRepository(postgres, {
                calculatePropertiesSize: 0,
                personPropertiesDbConstraintLimitBytes: 1024 * 1024,
                personPropertiesTrimTargetBytes: 512 * 1024,
            })

            const person = await createTestPerson(team.id, 'test-default', { name: 'John' })
            const update = { properties: { name: 'Jane', city: 'Boston' } }

            const [updatedPerson, messages, versionDisparity] = await defaultRepository.updatePerson(
                person,
                createPersonUpdateFields(person, update)
            )

            expect(updatedPerson.properties).toEqual({ name: 'Jane', city: 'Boston' })
            expect(updatedPerson.version).toBe(person.version + 1)
            expect(messages).toHaveLength(1)
            expect(versionDisparity).toBe(false)
        })
    })

    describe('JSON field size metrics', () => {
        let personJsonFieldSizeHistogram: any
        let labelsSpy: jest.SpyInstance
        let observeCalls: any[]

        beforeEach(() => {
            // Import the histogram
            const metricsModule = require('~/common/persons/metrics')
            personJsonFieldSizeHistogram = metricsModule.personJsonFieldSizeHistogram

            // Track observe calls
            observeCalls = []

            // Spy on labels to intercept and spy on observe
            const originalLabels = personJsonFieldSizeHistogram.labels.bind(personJsonFieldSizeHistogram)
            labelsSpy = jest.spyOn(personJsonFieldSizeHistogram, 'labels').mockImplementation(function (labels: any) {
                const labeledInstance = originalLabels(labels)
                const originalObserve = labeledInstance.observe.bind(labeledInstance)
                labeledInstance.observe = jest.fn((value: number) => {
                    observeCalls.push({ labels, value })
                    return originalObserve(value)
                })
                return labeledInstance
            })
        })

        afterEach(() => {
            if (labelsSpy) {
                labelsSpy.mockRestore()
            }
            observeCalls = []
        })

        it('should track JSON field sizes on createPerson', async () => {
            const properties = { name: 'Alice', email: '[email protected]', age: 25 }
            const propertiesLastUpdatedAt = { name: '2024-01-15T10:30:00.000Z', email: '2024-01-15T10:30:00.000Z' }
            const propertiesLastOperation = { name: PropertyUpdateOperation.Set, email: PropertyUpdateOperation.Set }

            // Pre-serialize to calculate expected sizes
            const expectedPropertiesSize = JSON.stringify(properties).length
            const expectedPropertiesLastUpdatedAtSize = JSON.stringify(propertiesLastUpdatedAt).length
            const expectedPropertiesLastOperationSize = JSON.stringify(propertiesLastOperation).length

            await repository.createPerson(
                TIMESTAMP,
                properties,
                propertiesLastUpdatedAt,
                propertiesLastOperation,
                team.id,
                null,
                true,
                new UUIDT().toString(),
                { distinctId: 'test-metrics-create' }
            )

            // Verify metrics were recorded for all three fields (3 calls total)
            expect(observeCalls).toHaveLength(3)

            // Verify each field was recorded with operation='createPerson' and exact size
            const propertiesCall = observeCalls.find((c) => c.labels.field === 'properties')
            const propertiesLastUpdatedAtCall = observeCalls.find(
                (c) => c.labels.field === 'properties_last_updated_at'
            )
            const propertiesLastOperationCall = observeCalls.find((c) => c.labels.field === 'properties_last_operation')

            expect(propertiesCall).toBeDefined()
            expect(propertiesCall!.labels.operation).toBe('createPerson')
            expect(propertiesCall!.value).toBe(expectedPropertiesSize)

            expect(propertiesLastUpdatedAtCall).toBeDefined()
            expect(propertiesLastUpdatedAtCall!.labels.operation).toBe('createPerson')
            expect(propertiesLastUpdatedAtCall!.value).toBe(expectedPropertiesLastUpdatedAtSize)

            expect(propertiesLastOperationCall).toBeDefined()
            expect(propertiesLastOperationCall!.labels.operation).toBe('createPerson')
            expect(propertiesLastOperationCall!.value).toBe(expectedPropertiesLastOperationSize)
        })

        it('should track JSON field sizes on updatePerson with properties', async () => {
            const person = await createTestPerson(team.id, 'test-metrics-update', { name: 'Bob' })

            // Clear observe calls from createTestPerson
            observeCalls = []

            const update = {
                properties: { name: 'Bob Updated', city: 'San Francisco', data: 'x'.repeat(1000) },
                properties_last_updated_at: { name: '2024-01-16T10:30:00.000Z', city: '2024-01-16T10:30:00.000Z' },
                properties_last_operation: { name: PropertyUpdateOperation.Set, city: PropertyUpdateOperation.Set },
            }

            // Pre-serialize to calculate expected sizes
            const expectedPropertiesSize = JSON.stringify(update.properties).length
            const expectedPropertiesLastUpdatedAtSize = JSON.stringify(update.properties_last_updated_at).length
            const expectedPropertiesLastOperationSize = JSON.stringify(update.properties_last_operation).length

            await repository.updatePerson(person, createPersonUpdateFields(person, update))

            // Verify metrics were recorded for all updated fields (3 calls total)
            expect(observeCalls).toHaveLength(3)

            // Verify each field was recorded with exact size
            const propertiesCall = observeCalls.find((c) => c.labels.field === 'properties')
            const propertiesLastUpdatedAtCall = observeCalls.find(
                (c) => c.labels.field === 'properties_last_updated_at'
            )
            const propertiesLastOperationCall = observeCalls.find((c) => c.labels.field === 'properties_last_operation')

            expect(propertiesCall).toBeDefined()
            expect(propertiesCall!.labels.operation).toBe('updatePerson')
            expect(propertiesCall!.value).toBe(expectedPropertiesSize)

            expect(propertiesLastUpdatedAtCall).toBeDefined()
            expect(propertiesLastUpdatedAtCall!.labels.operation).toBe('updatePerson')
            expect(propertiesLastUpdatedAtCall!.value).toBe(expectedPropertiesLastUpdatedAtSize)

            expect(propertiesLastOperationCall).toBeDefined()
            expect(propertiesLastOperationCall!.labels.operation).toBe('updatePerson')
            expect(propertiesLastOperationCall!.value).toBe(expectedPropertiesLastOperationSize)
        })

        it('should only track metrics for fields being updated', async () => {
            const person = await createTestPerson(team.id, 'test-metrics-partial', { name: 'Charlie' })

            // Clear observe calls from createTestPerson
            observeCalls = []

            // Only update properties, not the other fields
            const update = {
                properties: { name: 'Charlie Updated' },
            }

            const expectedPropertiesSize = JSON.stringify(update.properties).length

            await repository.updatePerson(person, createPersonUpdateFields(person, update))

            // Since we always pass all fields for consistent query plans, all 3 JSONB fields are tracked
            expect(observeCalls).toHaveLength(3)

            const propertiesCall = observeCalls.find((c) => c.labels.field === 'properties')
            expect(propertiesCall).toBeDefined()
            expect(propertiesCall!.labels.operation).toBe('updatePerson')
            expect(propertiesCall!.value).toBe(expectedPropertiesSize)
        })

        it('should handle large properties correctly', async () => {
            const largeProperties = {
                name: 'David',
                large_field: 'z'.repeat(100000), // 100KB of data
            }

            // Pre-serialize to calculate expected sizes
            const expectedPropertiesSize = JSON.stringify(largeProperties).length
            const expectedPropertiesLastUpdatedAtSize = JSON.stringify({}).length
            const expectedPropertiesLastOperationSize = JSON.stringify({}).length

            await repository.createPerson(
                TIMESTAMP,
                largeProperties,
                {},
                {},
                team.id,
                null,
                true,
                new UUIDT().toString(),
                { distinctId: 'test-metrics-large' }
            )

            // Should have 3 calls (properties, properties_last_updated_at, properties_last_operation)
            expect(observeCalls).toHaveLength(3)

            // Verify exact sizes
            const propertiesCall = observeCalls.find((c) => c.labels.field === 'properties')
            const propertiesLastUpdatedAtCall = observeCalls.find(
                (c) => c.labels.field === 'properties_last_updated_at'
            )
            const propertiesLastOperationCall = observeCalls.find((c) => c.labels.field === 'properties_last_operation')

            expect(propertiesCall).toBeDefined()
            expect(propertiesCall!.labels.operation).toBe('createPerson')
            expect(propertiesCall!.value).toBe(expectedPropertiesSize)
            expect(propertiesCall!.value).toBeGreaterThan(100000) // Sanity check

            expect(propertiesLastUpdatedAtCall).toBeDefined()
            expect(propertiesLastUpdatedAtCall!.value).toBe(expectedPropertiesLastUpdatedAtSize)

            expect(propertiesLastOperationCall).toBeDefined()
            expect(propertiesLastOperationCall!.value).toBe(expectedPropertiesLastOperationSize)
        })

        it('should not record metrics when update is empty', async () => {
            const person = await createTestPerson(team.id, 'test-metrics-empty', { name: 'Eve' })

            // Clear observe calls from createTestPerson
            observeCalls = []

            // Empty update - but helper fills in all fields from person
            const update = {}

            await repository.updatePerson(person, createPersonUpdateFields(person, update))

            // Since we always pass all fields for consistent query plans, all 3 JSONB fields are tracked
            // even though the values haven't changed from the person object
            expect(observeCalls).toHaveLength(3)
        })
    })

    describe('fetchPersonsForUpdateByDistinctIds()', () => {
        it('returns empty array for empty input', async () => {
            expect(await repository.fetchPersonsForUpdateByDistinctIds(team.id, [])).toEqual([])
        })

        it('resolves and locks multiple distinct ids in one query', async () => {
            const person1 = await createTestPerson(team.id, 'fold-anon-1', { name: 'One' })
            const person2 = await createTestPerson(team.id, 'fold-anon-2', { name: 'Two' })
            await repository.addDistinctId(person1, 'fold-anon-1b', 0)

            const rows = await repository.fetchPersonsForUpdateByDistinctIds(team.id, [
                'fold-anon-1',
                'fold-anon-1b',
                'fold-anon-2',
                'fold-missing',
            ])

            expect(rows).toHaveLength(3)
            const byDistinctId = Object.fromEntries(rows.map((row) => [row.distinct_id, row.uuid]))
            expect(byDistinctId).toEqual({
                'fold-anon-1': person1.uuid,
                'fold-anon-1b': person1.uuid,
                'fold-anon-2': person2.uuid,
            })
        })
    })

    describe('moveDistinctIdsFromPersons()', () => {
        it('moves all distinct ids from multiple sources to the target', async () => {
            const source1 = await createTestPerson(team.id, 'fold-source-1', {})
            const source2 = await createTestPerson(team.id, 'fold-source-2', {})
            const target = await createTestPerson(team.id, 'fold-target', {})
            await repository.addDistinctId(source1, 'fold-source-1b', 0)

            const result = await repository.moveDistinctIdsFromPersons([source1, source2], target)

            expect(result.success).toBe(true)
            if (result.success) {
                expect(result.distinctIdsMoved.sort()).toEqual(['fold-source-1', 'fold-source-1b', 'fold-source-2'])
                for (const message of result.messages) {
                    const messageValue = parseJSON(message.value!.toString())
                    expect(messageValue).toMatchObject({ person_id: target.uuid, team_id: team.id, is_deleted: 0 })
                }
            }

            const targetDistinctIds = await fetchDistinctIdValues(hub.postgres, target)
            expect(targetDistinctIds.sort()).toEqual([
                'fold-source-1',
                'fold-source-1b',
                'fold-source-2',
                'fold-target',
            ])
        })

        it('treats sources without distinct ids as satisfied rather than failing', async () => {
            const source = await createTestPerson(team.id, 'fold-source-gone', {})
            const target = await createTestPerson(team.id, 'fold-target-2', {})

            // Simulate a concurrently completed merge: source's ids were already moved
            await repository.moveDistinctIds(source, target, undefined)
            const result = await repository.moveDistinctIdsFromPersons([source], target)

            expect(result.success).toBe(true)
            if (result.success) {
                expect(result.distinctIdsMoved).toEqual([])
                expect(result.messages).toEqual([])
            }
        })

        it('returns success with no work for empty sources', async () => {
            const target = await createTestPerson(team.id, 'fold-target-3', {})

            const result = await repository.moveDistinctIdsFromPersons([], target)

            expect(result).toEqual({ success: true, messages: [], distinctIdsMoved: [] })
        })
    })

    describe('deletePersons()', () => {
        it('returns no messages for already-deleted persons and empty input', async () => {
            const person = await createTestPerson(team.id, 'fold-delete-3', {})
            const target = await createTestPerson(team.id, 'fold-delete-target-2', {})
            await repository.moveDistinctIdsFromPersons([person], target)
            await repository.deletePerson(person)

            expect(await repository.deletePersons([person])).toEqual([])
            expect(await repository.deletePersons([])).toEqual([])
        })
    })

    describe('updateCohortsAndFeatureFlagsForMergeBatch()', () => {
        it('moves overrides from multiple sources, keeping target values on conflict unless they are the cookieless sentinel', async () => {
            const source1 = await createTestPerson(team.id, 'fold-ff-source-1', {})
            const source2 = await createTestPerson(team.id, 'fold-ff-source-2', {})
            const target = await createTestPerson(team.id, 'fold-ff-target', {})

            for (const [personId, flagKey, hashKey] of [
                [source1.id, 'aloha', COOKIELESS_SENTINEL_VALUE],
                [source2.id, 'aloha', 'source2_aloha'],
                [source2.id, 'beta-feature', 'source2_beta'],
                [target.id, 'beta-feature', 'target_beta'],
                [source1.id, 'gamma', 'source1_gamma'],
                [target.id, 'gamma', COOKIELESS_SENTINEL_VALUE],
                [source1.id, 'delta', 'source1_delta'],
                [source2.id, 'delta', 'source2_delta'],
                [target.id, 'delta', COOKIELESS_SENTINEL_VALUE],
                [source1.id, 'epsilon', COOKIELESS_SENTINEL_VALUE],
            ]) {
                await insertRow(hub.postgres, 'posthog_featureflaghashkeyoverride', {
                    team_id: team.id,
                    person_id: personId,
                    feature_flag_key: flagKey,
                    hash_key: hashKey,
                })
            }

            await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [source1.id, source2.id], target.id)

            const result = await hub.postgres.query(
                PostgresUse.PERSONS_WRITE,
                'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride WHERE team_id = $1',
                [team.id],
                ''
            )
            expect(result.rows).toEqual(
                expect.arrayContaining([
                    { feature_flag_key: 'aloha', hash_key: 'source2_aloha', person_id: target.id },
                    { feature_flag_key: 'beta-feature', hash_key: 'target_beta', person_id: target.id },
                    { feature_flag_key: 'gamma', hash_key: 'source1_gamma', person_id: target.id },
                    {
                        feature_flag_key: 'delta',
                        hash_key: expect.stringMatching(/^source[12]_delta$/),
                        person_id: target.id,
                    },
                ])
            )
            expect(result.rows).toHaveLength(4)
        })

        it('is a no-op for empty sources', async () => {
            const target = await createTestPerson(team.id, 'fold-ff-target-2', {})

            await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [], target.id)
        })
    })
})