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.

11.4 KB
Raw Blame
import { DateTime } from 'luxon'

import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
import { UUIDT } from '~/common/utils/utils'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { InternalPerson } from '~/types'

import { PersonContext } from './person-context'
import { PersonCreateService } from './person-create-service'
import { createDefaultSyncMergeMode } from './person-merge-types'

jest.mock('~/ingestion/common/ingestion-warnings', () => ({
    emitIngestionWarning: jest.fn().mockResolvedValue(undefined),
}))

const mockEmitIngestionWarning = emitIngestionWarning as jest.MockedFunction<typeof emitIngestionWarning>

describe('PersonCreateService', () => {
    let mockPersonStore: any
    let mockOutputs: any
    let personContext: PersonContext
    let personCreateService: PersonCreateService
    const teamId = 123

    beforeEach(() => {
        jest.clearAllMocks()

        mockOutputs = {
            produce: jest.fn().mockResolvedValue(undefined),
        }

        mockPersonStore = {
            createPerson: jest.fn(),
            fetchForUpdate: jest.fn(),
        }

        const mockEvent = {
            uuid: new UUIDT().toString(),
            distinct_id: 'test-distinct-id',
            properties: {},
        }

        const mockTeam = {
            id: teamId,
        }

        personContext = new PersonContext(
            mockEvent as any,
            mockTeam as any,
            'test-distinct-id',
            DateTime.now(),
            true,
            mockOutputs,
            mockPersonStore,
            0,
            createDefaultSyncMergeMode(),
            false,
            false
        )

        personCreateService = new PersonCreateService(personContext.personStore, personContext.outputs)
    })

    describe('createPerson', () => {
        const createdAt = DateTime.now()
        const properties = { name: 'John Doe' }
        const propertiesOnce = { email: '[email protected]' }
        const isUserId = null
        const isIdentified = true
        const creatorEventUuid = new UUIDT().toString()
        const primaryDistinctId = { distinctId: 'test-distinct-id', version: 0 }

        it('should successfully create a person when store succeeds', async () => {
            const mockPerson = {
                id: '1',
                uuid: new UUIDT().toString(),
                team_id: teamId,
                properties: { ...propertiesOnce, ...properties, $creator_event_uuid: creatorEventUuid },
                created_at: createdAt,
                version: 0,
                is_identified: true,
                is_user_id: isUserId,
                properties_last_updated_at: {},
                properties_last_operation: {},
                last_seen_at: null,
            }

            const mockResult = {
                success: true,
                person: mockPerson,
                messages: [{ output: 'persons' as const, value: Buffer.from('test') }],
                created: true,
            }

            mockPersonStore.createPerson.mockResolvedValue(mockResult)

            const [person, created, messages] = await personCreateService.createPerson(
                createdAt,
                properties,
                propertiesOnce,
                teamId,
                isUserId,
                isIdentified,
                creatorEventUuid,
                primaryDistinctId
            )

            expect(person).toEqual(mockPerson)
            expect(created).toBe(true)
            // The caller owns the produce, so a transactional caller can defer it past commit.
            expect(messages).toEqual(mockResult.messages)
            expect(mockOutputs.produce).not.toHaveBeenCalled()
        })

        it('should handle PersonPropertiesSizeViolationError and log ingestion warning', async () => {
            const sizeViolationError = new PersonPropertiesSizeViolationError(
                'Person properties exceed size limit',
                teamId,
                'test-person-id',
                'test-distinct-id'
            )

            mockPersonStore.createPerson.mockRejectedValue(sizeViolationError)

            await expect(
                personCreateService.createPerson(
                    createdAt,
                    properties,
                    propertiesOnce,
                    teamId,
                    isUserId,
                    isIdentified,
                    creatorEventUuid,
                    primaryDistinctId
                )
            ).rejects.toThrow(PersonPropertiesSizeViolationError)

            expect(mockEmitIngestionWarning).toHaveBeenCalledWith(mockOutputs, teamId, {
                type: 'person_properties_size_violation',
                details: {
                    // uuidFromDistinctId(teamId, 'test-distinct-id')
                    personId: 'f75d0be1-213b-5c13-8aec-acd632d76425',
                    distinctId: 'test-distinct-id',
                    eventUuid: creatorEventUuid,
                    teamId: teamId,
                    message: 'Person properties exceeds size limit and was rejected',
                },
                pipelineStep: 'person-store',
            })
        })

        it('should handle creation conflict and fetch existing person', async () => {
            const conflictResult = {
                success: false,
                error: 'CreationConflict',
                distinctIds: ['test-distinct-id'],
            }

            const existingPerson = {
                id: '2',
                uuid: new UUIDT().toString(),
                team_id: teamId,
                properties: {},
                created_at: createdAt,
                version: 1,
                is_identified: false,
                is_user_id: null,
                properties_last_updated_at: {},
                properties_last_operation: {},
                last_seen_at: null,
            }

            mockPersonStore.createPerson.mockResolvedValue(conflictResult)
            mockPersonStore.fetchForUpdate.mockResolvedValue(existingPerson)

            const [person, created, , idOwned] = await personCreateService.createPerson(
                createdAt,
                properties,
                propertiesOnce,
                teamId,
                isUserId,
                isIdentified,
                creatorEventUuid,
                primaryDistinctId
            )

            expect(person).toEqual(existingPerson)
            expect(created).toBe(false)
            expect(idOwned).toBe(true)
            expect(mockPersonStore.fetchForUpdate).toHaveBeenCalledWith(teamId, 'test-distinct-id')
        })

        it('should resolve to the row holding the uuid when no distinct ID resolves it', async () => {
            // The holder owns a different distinct ID, so recovery by distinct ID finds nothing.
            // Before this returned the holder, the create threw an error the pipeline rethrows
            // until the consumer dies with uncommitted offsets.
            const makePerson = (id: string): InternalPerson => ({
                id,
                uuid: new UUIDT().toString(),
                team_id: teamId,
                properties: {},
                created_at: createdAt,
                version: 1,
                is_identified: false,
                is_user_id: null,
                properties_last_updated_at: {},
                properties_last_operation: {},
                last_seen_at: null,
            })
            const holder = makePerson('999')
            mockPersonStore.createPerson.mockResolvedValue({
                success: false,
                error: 'CreationConflict',
                distinctIds: ['test-distinct-id'],
                conflictingPerson: holder,
            })
            mockPersonStore.fetchForUpdate.mockResolvedValue(null)

            const [person, created, , idOwned] = await personCreateService.createPerson(
                createdAt,
                properties,
                propertiesOnce,
                teamId,
                isUserId,
                isIdentified,
                creatorEventUuid,
                primaryDistinctId
            )

            expect(person).toEqual(holder)
            expect(created).toBe(false)
            expect(idOwned).toBe(false)
        })

        it('should prefer the distinct ID match over the uuid holder when both exist', async () => {
            // A concurrent create of the same distinct ID is the common case and must keep
            // resolving to that person, not to whatever holds the uuid.
            const makePerson = (id: string): InternalPerson => ({
                id,
                uuid: new UUIDT().toString(),
                team_id: teamId,
                properties: {},
                created_at: createdAt,
                version: 1,
                is_identified: false,
                is_user_id: null,
                properties_last_updated_at: {},
                properties_last_operation: {},
                last_seen_at: null,
            })
            const holder = makePerson('999')
            const byDistinctId = makePerson('2')
            mockPersonStore.createPerson.mockResolvedValue({
                success: false,
                error: 'CreationConflict',
                distinctIds: ['test-distinct-id'],
                conflictingPerson: holder,
            })
            mockPersonStore.fetchForUpdate.mockResolvedValue(byDistinctId)

            const [person] = await personCreateService.createPerson(
                createdAt,
                properties,
                propertiesOnce,
                teamId,
                isUserId,
                isIdentified,
                creatorEventUuid,
                primaryDistinctId
            )

            expect(person).toEqual(byDistinctId)
        })

        it('should throw error when creation conflict occurs but person cannot be fetched', async () => {
            const conflictResult = {
                success: false,
                error: 'CreationConflict',
                distinctIds: ['test-distinct-id'],
            }

            mockPersonStore.createPerson.mockResolvedValue(conflictResult)
            mockPersonStore.fetchForUpdate.mockResolvedValue(null)

            await expect(
                personCreateService.createPerson(
                    createdAt,
                    properties,
                    propertiesOnce,
                    teamId,
                    isUserId,
                    isIdentified,
                    creatorEventUuid,
                    primaryDistinctId
                )
            ).rejects.toThrow('Person creation failed with constraint violation, but could not fetch existing person')
        })

        it('should re-throw other errors without logging ingestion warning', async () => {
            const genericError = new Error('Some other database error')
            mockPersonStore.createPerson.mockRejectedValue(genericError)

            await expect(
                personCreateService.createPerson(
                    createdAt,
                    properties,
                    propertiesOnce,
                    teamId,
                    isUserId,
                    isIdentified,
                    creatorEventUuid,
                    primaryDistinctId
                )
            ).rejects.toThrow('Some other database error')

            expect(mockEmitIngestionWarning).not.toHaveBeenCalled()
        })
    })
})