: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(personhog): make the shadow person-store comparison accurate (#107053)
Zach Brown95a0b842f0fc
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.tsindex ea722b72488e..ddb397e21b5a 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts@@ -704,6 +704,70 @@ describe('PersonhogPersonsStore', () => {expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)})+ it.each([true, false])(+ 'a miss cached for an extra id before the create does not outlive it (created: %p)',+ async (created) => {+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({ person, created } as never)+ repository.fetchPersonById.mockResolvedValue(person as never)+ const bound = store.forBatch(0)+ expect(await bound.fetchForUpdate(1, 'd2')).toBeNull()++ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ true,+ 'advisory-uuid',+ { distinctId: 'd1' },+ [{ distinctId: 'd2' }]+ )+ repository.resolvePersonsByDistinctIds.mockClear()+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd2', person }] as never)++ const fetched = await bound.fetchForUpdate(1, 'd2')++ expect(fetched?.id).toBe('7')+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ }+ )++ it('a resolve in flight across a create does not re-record the miss purged for an extra id', async () => {+ repository.fetchPersonById.mockResolvedValue(person as never)+ const bound = store.forBatch(0)+ let answerMiss: () => void = () => {}+ repository.resolvePersonsByDistinctIds.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ answerMiss = () => resolve([])+ }) as never+ )+ const straddling = bound.fetchForUpdate(1, 'd2')++ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ true,+ 'advisory-uuid',+ { distinctId: 'd1' },+ [{ distinctId: 'd2' }]+ )+ answerMiss()+ expect(await straddling).toBeNull()++ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd2', person }] as never)+ const fetched = await bound.fetchForUpdate(1, 'd2')++ expect(fetched?.id).toBe('7')+ expect(edgeOf('1:d1')).toBe('1:7')+ })+it('a create that finds an existing person leaves its id readable for updates', async () => {// The found branch pays a leader read to get current state. That// state satisfies the update read class, so the id it resolves must@@ -735,6 +799,115 @@ describe('PersonhogPersonsStore', () => {expect(repository.fetchPersonById).not.toHaveBeenCalled()})+ it('a create answer declined by a purge still clears the absence it contradicts', async () => {+ const bound = store.forBatch(0)+ // Identity has no mapping yet, so the update read caches an absence.+ expect(await bound.fetchForUpdate(1, 'd1')).toBeNull()+ expect(edgeOf('1:d1')).toBeNull()++ // Another pod attaches d1 and a purge lands mid-call, so the answer is not installed.+ let release!: (value: unknown) => void+ repository.getOrCreatePersonByDistinctId.mockReturnValueOnce(+ new Promise((resolve) => {+ release = resolve+ }) as never+ )+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ const creating = bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ { seed: 'value' },+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd1' },+ undefined+ )+ ;(store as any).bumpGeneration(1)+ release({ person, created: false })+ await creating++ // The next update read must re-resolve rather than serve the stale absence.+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)+ expect((await bound.fetchForUpdate(1, 'd1'))?.id).toBe('7')+ })++ it("an update read serves identity's answer when the leader no longer holds it, instead of caching an absence", async () => {+ const bound = store.forBatch(0)+ // Identity still names person 7 while a merge has just tombstoned it on the leader.+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)+ repository.fetchPersonById.mockResolvedValueOnce(null)++ const fetched = await bound.fetchForUpdate(1, 'd1')++ expect(fetched?.id).toBe('7')+ expect(edgeOf('1:d1')).toBeUndefined()+ })++ it('an update read over an edge the leader no longer holds re-resolves through identity', async () => {+ const bound = store.forBatch(0)+ ;(store as any).setDistinctIdToPersonId('1:d1', '1:9')+ repository.fetchPersonById.mockResolvedValueOnce(null).mockResolvedValueOnce({ ...person } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)++ const fetched = await bound.fetchForUpdate(1, 'd1')++ expect(fetched?.id).toBe('7')+ expect(edgeOf('1:d1')).toBe('1:7')+ })++ it.each([+ ['another person', '1:7'],+ ['the same person', '1:9'],+ ])(+ 'an update read over a stale edge leaves an edge to %s a newer read installed during its leader read',+ async (_case, newer) => {+ const bound = store.forBatch(0)+ ;(store as any).setDistinctIdToPersonId('1:d1', '1:9')+ let leaderCalled!: () => void+ const called = new Promise<void>((resolve) => (leaderCalled = resolve))+ let release!: (answer: null) => void+ repository.fetchPersonById+ .mockImplementationOnce((() => {+ leaderCalled()+ return new Promise((resolve) => (release = resolve))+ }) as never)+ .mockResolvedValueOnce({ ...person } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)++ const fetching = bound.fetchForUpdate(1, 'd1')+ await called+ // A purge and a newer read replace the edge while the leader read is out.+ ;(store as any).bumpGeneration(1)+ ;(store as any).setDistinctIdToPersonId('1:d1', newer)+ release(null)+ await fetching++ expect(edgeOf('1:d1')).toBe(newer)+ }+ )++ it('a prefetch leaves an id unresolved when the leader no longer holds the person identity named', async () => {+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)+ repository.fetchPersonById.mockResolvedValueOnce(null)++ await store.prefetchPersons([{ teamId: 1, distinctId: 'd1', batchId: 0 }])++ expect(edgeOf('1:d1')).toBeUndefined()+ })+it('drops a size-rejected segment from the lane rather than retrying it forever', async () => {repository.updatePersonProperties.mockRejectedValue(new PersonhogPropertiesSizeError('too big', 1, '7'))const bound = store.forBatch(0)diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex 17ea90c542e9..de4967a161ec 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -102,7 +102,7 @@ function moveLimitFor(mergeMode: MergeMode, syncMergeMoveLimit: number): number}/** The event name stamped on creation calls; per-event names are consumed at fold time. */-const CREATE_EVENT_NAME = '$create_person'+export const CREATE_EVENT_NAME = '$create_person'/** The event name stamped on direct diff updates, which carry no originating event. */const DIRECT_UPDATE_EVENT_NAME = '$direct_update'@@ -390,10 +390,14 @@ export class PersonhogPersonsStore implements PersonsStore {batchId: number,options: { grade: 'check' | 'update'; generation: number; fillOnly?: boolean }): InternalPerson | null {+ const distinctKey = `${teamId}:${distinctId}`if (options.generation !== this.generationOf(teamId)) {+ // A cached absence this answer contradicts is wrong even when the answer is not installed.+ if (fetched !== null && this.resolutions.get(distinctKey) === null) {+ this.resolutions.delete(distinctKey)+ }return this.snapshot(fetched)}- const distinctKey = `${teamId}:${distinctId}`if (fetched === null) {// A stale absence must not overwrite presence; a live mapping// stands and serves its best available view.@@ -432,7 +436,7 @@ export class PersonhogPersonsStore implements PersonsStore {}}- /** Check grade only: the personless step discards properties there, and the update grade reads the leader. */+ /** Identity's answer without properties, for reads the leader cannot serve. */private identityDocument(identity: PersonIdentity): InternalPerson {return { ...identity, properties: {}, properties_last_updated_at: {}, properties_last_operation: null }}@@ -459,23 +463,51 @@ export class PersonhogPersonsStore implements PersonsStore {return cached}const generation = this.generationOf(teamId)- const edge = this.resolutions.get(`${teamId}:${distinctId}`)+ const distinctKey = `${teamId}:${distinctId}`+ const edge = this.resolutions.get(distinctKey)if (edge != null) {// The edge is trusted but only a checking read backs it, which// lags the leader; the update path pays one leader read.const person = await this.repository.fetchPersonById(teamId, edge.slice(edge.indexOf(':') + 1), CALLER_TAG)- return this.cacheFetchedPerson(teamId, distinctId, person, batchId, { grade: 'update', generation })+ if (person !== null) {+ return this.cacheFetchedPerson(teamId, distinctId, person, batchId, { grade: 'update', generation })+ }+ // The leader no longer holds this person; identity decides where the id lives now. A purge or a newer+ // read during the leader read owns the entry, so only the edge this read found is removed.+ if (this.generationOf(teamId) === generation && this.resolutions.get(distinctKey) === edge) {+ this.clearPersonCacheForPersonId(edge, 'stale_write_answer')+ this.resolutions.delete(distinctKey)+ }}const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)if (!resolved?.person) {return this.cacheFetchedPerson(teamId, distinctId, null, batchId, { grade: 'update', generation })}- // A null read here means the person vanished mid-flight; the miss- // is cached and the caller's create path re-resolves.const person = await this.repository.fetchPersonById(teamId, resolved.person.id, CALLER_TAG)+ if (person === null) {+ // The person died mid-call; serve identity's answer rather than cache an absence.+ this.clearPersonCacheForPersonId(`${teamId}:${resolved.person.id}`, 'stale_write_answer')+ return this.identityDocument(resolved.person)+ }return this.cacheFetchedPerson(teamId, distinctId, person, batchId, { grade: 'update', generation })}+ private purgeExtraDistinctIds(+ teamId: number,+ extraDistinctIds: { distinctId: string }[] | undefined,+ generation: number+ ): number {+ if (!extraDistinctIds?.length) {+ return generation+ }+ for (const { distinctId } of extraDistinctIds) {+ this.removeDistinctIdFromCache(teamId, distinctId, 'extra_distinct_id')+ }+ const unpurged = generation === this.generationOf(teamId)+ this.bumpGeneration(teamId)+ return unpurged ? this.generationOf(teamId) : generation+ }+async createPerson(createdAt: DateTime,properties: Properties,@@ -504,6 +536,7 @@ export class PersonhogPersonsStore implements PersonsStore {CALLER_TAG)const { created } = createResult+ const recordGeneration = this.purgeExtraDistinctIds(teamId, extraDistinctIds, generation)let person: InternalPersonif (createResult.created) {person = createResult.person@@ -520,11 +553,9 @@ export class PersonhogPersonsStore implements PersonsStore {}const recorded = this.cacheFetchedPerson(teamId, primaryDistinctId.distinctId, person, batchId, {grade: 'update',- generation,+ generation: recordGeneration,})- // Extras are never cached: the service can leave a conflicting- // extra mapped to its existing person. No messages: the identity- // service publishes its own on creation.+ // No messages: the identity service publishes its own on creation.return { success: true, person: recorded ?? this.snapshot(person), messages: [], created }}@@ -957,7 +988,8 @@ export class PersonhogPersonsStore implements PersonsStore {return}const person = await this.repository.fetchPersonById(entry.teamId, entry.person.id, CALLER_TAG)- if (!this.prefetchingBatches.has(batchId)) {+ // Merged away since identity answered; the update read resolves it.+ if (!this.prefetchingBatches.has(batchId) || person === null) {return}// Fill-only: this response raced everything thediff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.tsindex eb37cd918c8f..1f9b035e0bab 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts@@ -8,6 +8,7 @@ import {personhogStoreShadowErrorsCounter,personhogStoreShadowSkipsCounter,} from '~/common/persons/metrics'+import { logger } from '~/common/utils/logger'import { defaultRetryConfig } from '~/common/utils/retries'import { InternalPerson } from '~/types'@@ -413,7 +414,8 @@ describe('RoutingPersonsStore', () => {}})- it('a fold both backends aborted records nothing', async () => {+ it('a fold both backends aborted records and logs nothing', async () => {+ const info = jest.spyOn(logger, 'info')const stores = makeStores()stores.pg.mergePersons.mockResolvedValue({ survivor: null, results: [], foldAborted: 'limit' })stores.personhogMock.mergePersons.mockResolvedValue({@@ -426,6 +428,7 @@ describe('RoutingPersonsStore', () => {await store.mergePersons(mergeRequest() as never, 0)expect(divergences()).toEqual([])+ expect(info).not.toHaveBeenCalledWith('personhog shadow merge verdicts differ', expect.anything())})it('tells shadow failures apart by class, not just by verb', async () => {@@ -706,6 +709,55 @@ describe('RoutingPersonsStore', () => {expect(stores.personhogMock.createPerson.mock.calls[0][7]).toBe('caller-supplied-uuid')})+ it.each([+ ['found', false, 1],+ ['created', true, 0],+ ])(+ 'shadow createPerson re-applies the creation properties only when personhog %s the person pg created',+ async (_case, shadowCreated, applied) => {+ const stores = makeStores()+ const shadowPerson = person(1, '99')+ stores.pg.createPerson.mockResolvedValue({+ success: true,+ person: person(1, '7'),+ messages: [],+ created: true,+ } as never)+ stores.personhogMock.createPerson.mockResolvedValue({+ success: true,+ person: shadowPerson,+ messages: [],+ created: shadowCreated,+ } as never)+ const store = makeStore(stores, 'shadow')++ await store.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ { plan: 'pro' },+ {},+ {},+ 1,+ null,+ false,+ 'caller-supplied-uuid',+ { distinctId: 'd1' },+ undefined,+ undefined,+ 0+ )++ expect(stores.personhogMock.applyEventOps).toHaveBeenCalledTimes(applied)+ if (applied) {+ expect(stores.personhogMock.applyEventOps).toHaveBeenCalledWith(+ shadowPerson,+ expect.objectContaining({ setOnce: { plan: 'pro' }, shouldForceUpdate: true }),+ 'd1',+ 0+ )+ }+ }+ )+it('mergePersons replays the same request against the personhog backend, pg staying authoritative', async () => {const stores = makeStores()const pgResult = { survivor: person(1, '7'), results: [] }@@ -752,6 +804,36 @@ describe('RoutingPersonsStore', () => {expect(counted).toEqual(countedAs === null ? [] : [{ verb: 'mergePersons', error: countedAs }])})+ it.each([+ ['settles on a retry', 1, 2, 'merged'],+ ['stays unsettled through every attempt', 3, 3, 'skipped_conflict'],+ ])('shadow merge that %s', async (_name, unsettledAttempts, expectedCalls, finalOutcome) => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ for (let i = 0; i < unsettledAttempts; i++) {+ stores.personhogMock.mergePersons.mockResolvedValueOnce({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict', settled: false }],+ })+ }+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons(mergeRequest() as never, 0)++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)+ // The outcome the comparator saw: settled after a retry, or the last unsettled verdict.+ const divergences = (personhogStoreShadowDivergenceCounter.labels as jest.Mock).mock.calls.map(([l]) => l)+ expect(divergences.some((d) => d.field === 'outcome')).toBe(finalOutcome !== 'merged')+ expect(personhogStoreShadowErrorsCounter.labels).not.toHaveBeenCalled()+ })+it('prefetch warms both worlds', async () => {const stores = makeStores()const store = makeStore(stores, 'shadow')diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.tsindex 83e0ba4df6a7..9f9bbee3d340 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts@@ -20,8 +20,9 @@ import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-wriimport { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'+import { PersonMergeUnsettledError } from './person-merge-types'import { EventOps } from './person-update'-import { PersonhogPersonsStore } from './personhog-persons-store'+import { CREATE_EVENT_NAME, PersonhogPersonsStore } from './personhog-persons-store'import {FlushResult,MergePersonsRequest,@@ -350,10 +351,48 @@ export class RoutingPersonsStore implements PersonsStore {extraDistinctIds,tx,batchId- )+ ),+ {+ after: (authoritative, shadow, abandoned) =>+ this.reconcileShadowCreate(+ authoritative,+ shadow as CreatePersonResult,+ properties,+ primaryDistinctId.distinctId,+ batchId,+ abandoned+ ),+ })}+ /** Postgres created the person and personhog only found it: apply the creation properties set-once. */+ private async reconcileShadowCreate(+ authoritative: CreatePersonResult,+ shadow: CreatePersonResult,+ properties: Properties,+ distinctId: string,+ batchId: number,+ abandoned: AbortSignal+ ): Promise<void> {+ if (+ abandoned.aborted ||+ !(authoritative.success && authoritative.created) ||+ !(shadow.success && !shadow.created)+ ) {+ return+ }+ const ops: EventOps = {+ set: {},+ setOnce: properties,+ unset: [],+ denied: false,+ shouldForceUpdate: true,+ eventName: CREATE_EVENT_NAME,+ }+ await this.personhog.applyEventOps(shadow.person, ops, distinctId, batchId)+ }+applyEventOps(person: InternalPerson,ops: EventOps,@@ -440,7 +479,7 @@ export class RoutingPersonsStore implements PersonsStore {() => this.personhog.mergePersons(request, batchId),{shadow: (abandoned) => this.shadowMerge(request, batchId, abandoned),- compare: (authoritative, shadow) => this.compareMerge(authoritative, shadow),+ compare: (authoritative, shadow) => this.compareMerge(request, authoritative, shadow),after: (authoritative, shadow, abandoned) =>this.redriveShadowFoldPairs(request, batchId, authoritative, shadow, abandoned),}@@ -448,23 +487,39 @@ export class RoutingPersonsStore implements PersonsStore {}/** The merge service's retries wrap the routed call, which never throws for the shadow side. */- private retriedShadowMerge(+ private async retriedShadowMerge(request: MergePersonsRequest,batchId: number,abandoned: AbortSignal): Promise<MergePersonsResult> {- return promiseRetry(- // An abandoned verb starts no new write; one already in flight still finishes.- () =>- abandoned.aborted- ? Promise.reject(new ShadowVerbTimeoutError('mergePersons'))- : this.personhog.mergePersons(request, batchId),- 'shadow_merge_persons',- undefined,- undefined,- undefined,- [ConnectError, ShadowVerbTimeoutError]- )+ let unsettled: MergePersonsResult | undefined+ try {+ return await promiseRetry(+ async () => {+ // An abandoned verb starts no new write; one already in flight still finishes.+ if (abandoned.aborted) {+ throw new ShadowVerbTimeoutError('mergePersons')+ }+ const result = await this.personhog.mergePersons(request, batchId)+ // Unsettled means a retry under the same op id may settle it.+ if (result.results.some((source) => source.settled === false)) {+ unsettled = result+ throw new PersonMergeUnsettledError('shadow merge verdict is unsettled')+ }+ return result+ },+ 'shadow_merge_persons',+ undefined,+ undefined,+ undefined,+ [ConnectError, ShadowVerbTimeoutError]+ )+ } catch (error) {+ if (error instanceof PersonMergeUnsettledError && unsettled !== undefined) {+ return unsettled+ }+ throw error+ }}/** A fold is never retried as a fold: one that throws aborts, and its pairs take the re-drive. */@@ -554,10 +609,33 @@ export class RoutingPersonsStore implements PersonsStore {* disagreement is the most consequential divergence; the vocabularies* differ between backends, so a difference is a finding, not an alarm.*/- private compareMerge(authoritative: unknown, shadow: unknown): void {+ private compareMerge(request: MergePersonsRequest, authoritative: unknown, shadow: unknown): void {const left = authoritative as MergePersonsResultconst right = shadow as MergePersonsResultpersonhogStoreShadowComparedCounter.labels({ verb: 'mergePersons' }).inc()+ // Sorted by source: the backends report the same verdicts in different orders.+ const verdicts = (result: MergePersonsResult): string =>+ result.foldAborted !== undefined+ ? `aborted:${result.foldAborted}`+ : result.results+ .map((source) => `${source.sourceDistinctId}=${source.outcome}`)+ .sort()+ .join(',')+ const bothAborted = left.foldAborted !== undefined && right.foldAborted !== undefined+ const disagree =+ (left.survivor?.uuid ?? null) !== (right.survivor?.uuid ?? null) || verdicts(left) !== verdicts(right)+ if (disagree && !bothAborted) {+ logger.info('personhog shadow merge verdicts differ', {+ team_id: request.teamId,+ target_distinct_id: request.targetDistinctId,+ trigger_source_distinct_id: request.triggerSourceDistinctId,+ sources: request.sources.map((source) => source.distinctId),+ pg_survivor: left.survivor?.uuid ?? null,+ pg: verdicts(left),+ personhog_survivor: right.survivor?.uuid ?? null,+ personhog: verdicts(right),+ })+ }// An aborted fold carries no verdicts, so the disposition itself is// what the backends can disagree on: one record when only one side// aborted, nothing when both did.