: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(ingestion): retry the shadow person merge like personhog mode does (#104013)
Zach Brown93d122e03d7b
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex 52948a447282..17ea90c542e9 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -21,7 +21,7 @@ import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } fromimport { MergeMode, PersonMergeCallFailedError } from './person-merge-types'import { EventOps, applyEventPropertyUpdates, computeOpsScalarUpdates, foldOps, refineEventOps } from './person-update'import { mergeOpIdFromRequest } from './person-uuid'-import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsStore } from './persons-store'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsStore, isFoldRequest } from './persons-store'import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'export const personhogStoreFlushCounter = new Counter({@@ -711,7 +711,7 @@ export class PersonhogPersonsStore implements PersonsStore {// sequential path, where each event gets its own durability// decision. The trigger id marks a fold request, so a single-pair// fold aborts the same way instead of dodging every guard.- if (request.sources.length > 1 || request.triggerSourceDistinctId !== undefined) {+ if (isFoldRequest(request)) {const overLimit = result.results.some((source) => source.outcome === 'skipped_move_limit')const conflicted = result.results.some((source) => source.outcome === 'skipped_conflict' || source.settled === falsediff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.tsindex 5c7e26a5cec0..b283652b6b32 100644--- a/nodejs/src/ingestion/common/persons/persons-store.ts+++ b/nodejs/src/ingestion/common/persons/persons-store.ts@@ -110,6 +110,11 @@ export interface MergePersonsRequest {createdAtMs: number}+/** The trigger id marks a fold request, so a single-pair fold counts as one too. */+export function isFoldRequest(request: MergePersonsRequest): boolean {+ return request.sources.length > 1 || request.triggerSourceDistinctId !== undefined+}+export type MergeFoldAbortReason = 'limit' | 'conflict' | 'refused' | 'deadlock' | 'error'export interface MergePersonsResult {diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.tsindex 6f1ecc36f1f8..eb37cd918c8f 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts@@ -8,8 +8,10 @@ import {personhogStoreShadowErrorsCounter,personhogStoreShadowSkipsCounter,} from '~/common/persons/metrics'+import { defaultRetryConfig } from '~/common/utils/retries'import { InternalPerson } from '~/types'+import { PersonMergeCallFailedError } from './person-merge-types'import { EventOps } from './person-update'import { PersonhogPersonsStore } from './personhog-persons-store'import { MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'@@ -99,6 +101,17 @@ describe('RoutingPersonsStore', () => {const makeStore = (stores: ReturnType<typeof makeStores>, mode: 'personhog' | 'shadow') =>new RoutingPersonsStore(stores.pg, stores.personhog, mode)+ const mergeRequest = () => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],+ eventUuid: 'uuid-1',+ })++ beforeEach(() => {+ defaultRetryConfig.RETRY_INTERVAL_DEFAULT = 0+ })+describe('shadow divergence detection', () => {const divergences = (): Record<string, string>[] =>(personhogStoreShadowDivergenceCounter.labels as jest.Mock).mock.calls.map(([labels]) => labels)@@ -179,7 +192,7 @@ describe('RoutingPersonsStore', () => {})const store = makeStore(stores, 'shadow')- await store.mergePersons({} as never, 0)+ await store.mergePersons(mergeRequest() as never, 0)// Which person survives decides where every later event in the// batch lands, and a row diff cannot see it: both sides end with@@ -199,7 +212,7 @@ describe('RoutingPersonsStore', () => {})const store = makeStore(stores, 'shadow')- await store.mergePersons({} as never, 0)+ await store.mergePersons(mergeRequest() as never, 0)expect(divergences()).toContainEqual({ verb: 'mergePersons', field: 'outcome' })})@@ -219,7 +232,7 @@ describe('RoutingPersonsStore', () => {})const store = makeStore(stores, 'shadow')- await store.mergePersons({} as never, 0)+ await store.mergePersons(mergeRequest() as never, 0)expect(divergences()).toContainEqual({ verb: 'mergePersons', field: 'outcome' })})@@ -237,7 +250,7 @@ describe('RoutingPersonsStore', () => {})const store = makeStore(stores, 'shadow')- await store.mergePersons({} as never, 0)+ await store.mergePersons(mergeRequest() as never, 0)expect(divergences()).toEqual([{ verb: 'mergePersons', field: 'fold_disposition' }])})@@ -264,40 +277,51 @@ describe('RoutingPersonsStore', () => {createdAtMs: 1_000,})- it('a fold only the shadow aborted re-drives each pair as a sequential shadow merge', async () => {- const stores = makeStores()- stores.pg.mergePersons.mockResolvedValue({- survivor: person(1, '1'),- results: [- { sourceDistinctId: 'anon-1', outcome: 'merged' },- { sourceDistinctId: 'anon-2', outcome: 'merged' },- ],- })- stores.personhogMock.mergePersons- .mockResolvedValueOnce({ survivor: null, results: [], foldAborted: 'conflict' })- .mockResolvedValue({+ it.each([+ ['aborted', () => Promise.resolve({ survivor: null, results: [], foldAborted: 'conflict' as const }), []],+ [+ 'failed with no verdict',+ () => Promise.reject(new PersonMergeCallFailedError('no verdict', new Error('shed'))),+ [{ verb: 'mergePersons', error: 'PersonMergeCallFailedError' }],+ ],+ ])(+ 'a fold only the shadow %s re-drives each pair as a sequential shadow merge',+ async (_how, shadowFold, counted) => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ stores.personhogMock.mergePersons.mockImplementationOnce(shadowFold).mockResolvedValue({survivor: person(1, '1'),results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],})- const store = makeStore(stores, 'shadow')-- await store.mergePersons(foldRequest() as never, 7)+ const store = makeStore(stores, 'shadow')- // The fold call, then one plain merge per pair: the pair's own- // event uuid roots the op id, no trigger marks it fold-shaped,- // and the ops are empty.- expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)- const pairCalls = stores.personhogMock.mergePersons.mock.calls.slice(1)- expect(pairCalls.map((call: any[]) => call[0].sources)).toEqual([- [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],- [{ distinctId: 'anon-2', eventUuid: 'uuid-2' }],- ])- expect(pairCalls.map((call: any[]) => call[0].eventUuid)).toEqual(['uuid-1', 'uuid-2'])- for (const call of pairCalls) {- expect(call[0].triggerSourceDistinctId).toBeUndefined()- expect(call[0].eventOps.set).toEqual({})+ await store.mergePersons(foldRequest() as never, 7)++ // The fold call, then one plain merge per pair: the pair's own+ // event uuid roots the op id, no trigger marks it fold-shaped,+ // and the ops are empty.+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)+ const pairCalls = stores.personhogMock.mergePersons.mock.calls.slice(1)+ expect(pairCalls.map((call: any[]) => call[0].sources)).toEqual([+ [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],+ [{ distinctId: 'anon-2', eventUuid: 'uuid-2' }],+ ])+ expect(pairCalls.map((call: any[]) => call[0].eventUuid)).toEqual(['uuid-1', 'uuid-2'])+ for (const call of pairCalls) {+ expect(call[0].triggerSourceDistinctId).toBeUndefined()+ expect(call[0].eventOps.set).toEqual({})+ }+ expect(+ (personhogStoreShadowErrorsCounter.labels as jest.Mock).mock.calls.map(([labels]) => labels)+ ).toEqual(counted)}- })+ )it('a fold both backends executed re-drives nothing', async () => {const stores = makeStores()@@ -316,7 +340,10 @@ describe('RoutingPersonsStore', () => {expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(1)})- it('a failing re-drive pair does not stop the remaining pairs', async () => {+ it.each([+ ['clears on retry', 1, 4],+ ['fails through every attempt', 3, 5],+ ])('a re-drive pair that %s does not stop the remaining pairs', async (_how, failures, expectedCalls) => {const stores = makeStores()stores.pg.mergePersons.mockResolvedValue({survivor: person(1, '1'),@@ -325,18 +352,65 @@ describe('RoutingPersonsStore', () => {{ sourceDistinctId: 'anon-2', outcome: 'merged' },],})- stores.personhogMock.mergePersons- .mockResolvedValueOnce({ survivor: null, results: [], foldAborted: 'conflict' })- .mockRejectedValueOnce(new Error('redrive transport failure'))- .mockResolvedValue({- survivor: person(1, '1'),- results: [{ sourceDistinctId: 'anon-2', outcome: 'merged' }],- })+ stores.personhogMock.mergePersons.mockResolvedValueOnce({+ survivor: null,+ results: [],+ foldAborted: 'conflict',+ })+ for (let i = 0; i < failures; i++) {+ stores.personhogMock.mergePersons.mockRejectedValueOnce(new Error('redrive transport failure'))+ }+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-2', outcome: 'merged' }],+ })const store = makeStore(stores, 'shadow')await expect(store.mergePersons(foldRequest() as never, 7)).resolves.toBeDefined()- expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)+ expect(stores.personhogMock.mergePersons.mock.lastCall?.[0].sources).toEqual([+ { distinctId: 'anon-2', eventUuid: 'uuid-2' },+ ])+ })++ it.each([+ ['a plain merge starts no further attempt', mergeRequest, [], 1],+ [+ 'a fold re-drive starts no further pair',+ foldRequest,+ [{ survivor: null, results: [], foldAborted: 'conflict' as const }],+ 2,+ ],+ ])('abandoned at the shadow ceiling, %s', async (_name, request, answeredFirst, expectedCalls) => {+ jest.useFakeTimers()+ try {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ let failHanging: (error: Error) => void = () => {}+ const hanging = new Promise<never>((_resolve, reject) => (failHanging = reject))+ for (const answer of answeredFirst) {+ stores.personhogMock.mergePersons.mockResolvedValueOnce(answer)+ }+ stores.personhogMock.mergePersons.mockReturnValueOnce(hanging)+ const store = makeStore(stores, 'shadow')++ const pending = store.mergePersons(request() as never, 7)+ await jest.advanceTimersByTimeAsync(60_000)+ await pending+ failHanging(new PersonMergeCallFailedError('no verdict', new Error('deadline')))+ await jest.advanceTimersByTimeAsync(1_000)++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)+ } finally {+ jest.useRealTimers()+ }})it('a fold both backends aborted records nothing', async () => {@@ -349,7 +423,7 @@ describe('RoutingPersonsStore', () => {})const store = makeStore(stores, 'shadow')- await store.mergePersons({} as never, 0)+ await store.mergePersons(mergeRequest() as never, 0)expect(divergences()).toEqual([])})@@ -637,7 +711,7 @@ describe('RoutingPersonsStore', () => {const pgResult = { survivor: person(1, '7'), results: [] }stores.pg.mergePersons.mockResolvedValue(pgResult)const store = makeStore(stores, 'shadow')- const request = { teamId: 1, targetDistinctId: 'd' } as never+ const request = mergeRequest() as neverawait expect(store.mergePersons(request, 0)).resolves.toBe(pgResult)@@ -645,17 +719,37 @@ describe('RoutingPersonsStore', () => {expect(stores.personhogMock.mergePersons).toHaveBeenCalledWith(request, 0)})- it('a shadow merge failure is swallowed and counted, never failing the batch', async () => {+ const noVerdict = (): Error => new PersonMergeCallFailedError('no verdict', new Error('shed'))++ it.each([+ ['a no-verdict failure that clears is retried under the same request', [noVerdict()], 2, null],+ [+ 'a failure through every attempt is swallowed and counted',+ [noVerdict(), noVerdict(), noVerdict()],+ 3,+ 'PersonMergeCallFailedError',+ ],+ [+ 'a deterministic refusal is counted without a retry',+ [new ConnectError('refused', Code.InvalidArgument)],+ 1,+ 'InvalidArgument',+ ],+ ])('shadow merge: %s', async (_name, failures, expectedCalls, countedAs) => {const stores = makeStores()stores.pg.mergePersons.mockResolvedValue(emptyMergeResult())- stores.personhogMock.mergePersons.mockRejectedValue(new Error('identity down'))+ for (const failure of failures) {+ stores.personhogMock.mergePersons.mockRejectedValueOnce(failure)+ }const store = makeStore(stores, 'shadow')+ const request = mergeRequest() as never- await expect(store.mergePersons({} as never, 0)).resolves.toEqual(emptyMergeResult())- expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({- verb: 'mergePersons',- error: 'Error',- })+ await expect(store.mergePersons(request, 0)).resolves.toEqual(emptyMergeResult())++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)+ expect(stores.personhogMock.mergePersons).toHaveBeenLastCalledWith(request, 0)+ const counted = (personhogStoreShadowErrorsCounter.labels as jest.Mock).mock.calls.map(([labels]) => labels)+ expect(counted).toEqual(countedAs === null ? [] : [{ verb: 'mergePersons', error: countedAs }])})it('prefetch warms both worlds', async () => {diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.tsindex 34dbee0d959c..83e0ba4df6a7 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts@@ -1,3 +1,4 @@+import { ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import { errorClassLabel } from '~/common/personhog/metrics'@@ -14,13 +15,21 @@ import { PersonMessage } from '~/common/persons/person-message'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'import { CreatePersonResult } from '~/common/utils/db/db'import { logger } from '~/common/utils/logger'+import { promiseRetry } from '~/common/utils/retries'import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'import { EventOps } from './person-update'import { PersonhogPersonsStore } from './personhog-persons-store'-import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'+import {+ FlushResult,+ MergePersonsRequest,+ MergePersonsResult,+ PersonsBackend,+ PersonsStore,+ isFoldRequest,+} from './persons-store'import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'export type PersonsStoreMode = 'pg' | 'personhog' | 'shadow'@@ -144,10 +153,11 @@ export class RoutingPersonsStore implements PersonsStore {* the consumer's poll budget, so a verb that outruns the ceiling is* abandoned and counted as lost fidelity; the bound is per verb.*/- private async shadowed(verb: string, run: () => Promise<unknown>): Promise<void> {+ private async shadowed(verb: string, run: (abandoned: AbortSignal) => Promise<unknown>): Promise<void> {const stopTimer = personhogStoreShadowDurationSeconds.labels({ verb }).startTimer()let timer: ReturnType<typeof setTimeout> | undefined- const running = run()+ const abandon = new AbortController()+ const running = run(abandon.signal)// The abandoned leg keeps running against the personhog side; its// settlement is swallowed here so a rejection arriving after the// ceiling cannot surface as an unhandled one.@@ -156,20 +166,27 @@ export class RoutingPersonsStore implements PersonsStore {await Promise.race([running,new Promise<never>((_resolve, reject) => {- timer = setTimeout(() => reject(new ShadowVerbTimeoutError(verb)), SHADOW_VERB_TIMEOUT_MS)+ timer = setTimeout(() => {+ abandon.abort()+ reject(new ShadowVerbTimeoutError(verb))+ }, SHADOW_VERB_TIMEOUT_MS)}),])} catch (error) {- // Labelled by class as well as verb: the failures a rollout- // must tell apart read identically under one number.- personhogStoreShadowErrorsCounter.labels({ verb, error: errorClassLabel(error) }).inc()- logger.warn('personhog shadow verb failed', { verb, error: String(error) })+ this.recordShadowFailure(verb, error)} finally {clearTimeout(timer)stopTimer()}}+ private recordShadowFailure(verb: string, error: unknown): void {+ // Labelled by class as well as verb: the failures a rollout+ // must tell apart read identically under one number.+ personhogStoreShadowErrorsCounter.labels({ verb, error: errorClassLabel(error) }).inc()+ logger.warn('personhog shadow verb failed', { verb, error: String(error) })+ }+/*** The whole mode semantics, once: personhog mode runs the personhog* call, shadow runs pg as the authoritative result and the personhog@@ -180,19 +197,19 @@ export class RoutingPersonsStore implements PersonsStore {pg: () => Promise<T>,personhog: () => Promise<T>,opts?: {- shadow?: () => Promise<unknown>+ shadow?: (abandoned: AbortSignal) => Promise<unknown>compare?: (authoritative: T, shadow: unknown) => void- after?: (authoritative: T, shadow: unknown) => Promise<void>+ after?: (authoritative: T, shadow: unknown, abandoned: AbortSignal) => Promise<void>}): Promise<T> {if (this.mode === 'personhog') {return personhog()}const result = await pg()- await this.shadowed(verb, async () => {- const shadow = await (opts?.shadow ?? personhog)()+ await this.shadowed(verb, async (abandoned) => {+ const shadow = await (opts?.shadow ? opts.shadow(abandoned) : personhog())this.compared(verb, () => opts?.compare?.(result, shadow))- await opts?.after?.(result, shadow)+ await opts?.after?.(result, shadow, abandoned)})return result}@@ -422,15 +439,54 @@ export class RoutingPersonsStore implements PersonsStore {() => this.pg.mergePersons(request, batchId),() => this.personhog.mergePersons(request, batchId),{+ shadow: (abandoned) => this.shadowMerge(request, batchId, abandoned),compare: (authoritative, shadow) => this.compareMerge(authoritative, shadow),- after: (authoritative, shadow) => this.redriveShadowFoldPairs(request, batchId, authoritative, shadow),+ after: (authoritative, shadow, abandoned) =>+ this.redriveShadowFoldPairs(request, batchId, authoritative, shadow, abandoned),})}+ /** The merge service's retries wrap the routed call, which never throws for the shadow side. */+ private 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]+ )+ }++ /** A fold is never retried as a fold: one that throws aborts, and its pairs take the re-drive. */+ private async shadowMerge(+ request: MergePersonsRequest,+ batchId: number,+ abandoned: AbortSignal+ ): Promise<MergePersonsResult> {+ if (!isFoldRequest(request)) {+ return this.retriedShadowMerge(request, batchId, abandoned)+ }+ try {+ return await this.personhog.mergePersons(request, batchId)+ } catch (error) {+ this.recordShadowFailure('mergePersons', error)+ return { survivor: null, results: [], foldAborted: 'error' }+ }+ }+/**- * A fold only the shadow aborted gets its pairs re-driven, single- * shot, as the fallback merges the service cannot issue (it sees only+ * A fold only the shadow aborted gets its pairs re-driven, as the+ * fallback merges the service cannot issue (it sees only* the executed authoritative result). Per-pair op ids let the pair's* own event attach on redelivery; ops stay empty because plan events* route theirs through the shadowed update path regardless.@@ -439,7 +495,8 @@ export class RoutingPersonsStore implements PersonsStore {request: MergePersonsRequest,batchId: number,authoritative: MergePersonsResult,- shadow: unknown+ shadow: unknown,+ abandoned: AbortSignal): Promise<void> {const shadowResult = shadow as MergePersonsResultif (authoritative.foldAborted !== undefined || shadowResult?.foldAborted === undefined) {@@ -447,7 +504,7 @@ export class RoutingPersonsStore implements PersonsStore {}for (const source of request.sources) {try {- const result = await this.personhog.mergePersons(+ const result = await this.retriedShadowMerge({teamId: request.teamId,targetDistinctId: request.targetDistinctId,@@ -465,7 +522,8 @@ export class RoutingPersonsStore implements PersonsStore {mergeMode: request.mergeMode,createdAtMs: request.createdAtMs,},- batchId+ batchId,+ abandoned)const outcome = result.results[0]?.outcome ?? 'error'personhogStoreShadowFoldRedriveCounter.labels({ outcome }).inc()