: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(persons): retry cancelled personhog calls and defer abandoned shadow merges (#117179)
Zach Brown7b66715b380e
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 3be4932cb6aa..26d552c697ce 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -131,6 +131,8 @@ export type CommonConfig = BaseServerConfig & {PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS: stringPERSONHOG_TLS: booleanPERSONHOG_TIMEOUT_MS: number+ /** Per-call deadline on the identity connection; it outlasts identity's own leader attempts. */+ PERSONHOG_IDENTITY_TIMEOUT_MS: number/** Deadline for the identity merge saga call; must exceed the engine's lifecycle_execute_timeout_secs. */PERSONHOG_MERGE_TIMEOUT_MS: numberPERSONHOG_READ_MAX_BYTES: number@@ -373,6 +375,7 @@ export function getDefaultCommonConfig(): CommonConfig {PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS: '',PERSONHOG_TLS: false,PERSONHOG_TIMEOUT_MS: 3000,+ PERSONHOG_IDENTITY_TIMEOUT_MS: 3000,PERSONHOG_MERGE_TIMEOUT_MS: 35_000,PERSONHOG_READ_MAX_BYTES: 128 * 1024 * 1024,PERSONHOG_WRITE_MAX_BYTES: 4 * 1024 * 1024,diff --git a/nodejs/src/common/personhog/grpc-retry.test.ts b/nodejs/src/common/personhog/grpc-retry.test.tsindex 6ee8acc3ceaf..0f2439b9659e 100644--- a/nodejs/src/common/personhog/grpc-retry.test.ts+++ b/nodejs/src/common/personhog/grpc-retry.test.ts@@ -35,6 +35,7 @@ describe('withRetry', () => {['Aborted', Code.Aborted],['Internal', Code.Internal],['Unknown', Code.Unknown],+ ['Canceled', Code.Canceled],])('retries on %s', async (_name, code) => {let callCount = 0await withRetry(@@ -61,7 +62,6 @@ describe('withRetry', () => {['FailedPrecondition', Code.FailedPrecondition],['OutOfRange', Code.OutOfRange],['DataLoss', Code.DataLoss],- ['Canceled', Code.Canceled],])('does not retry on %s', async (_name, code) => {let callCount = 0const error: unknown = await withRetry(diff --git a/nodejs/src/common/personhog/grpc-retry.ts b/nodejs/src/common/personhog/grpc-retry.tsindex 28c1296c0462..d5a8da3fc33c 100644--- a/nodejs/src/common/personhog/grpc-retry.ts+++ b/nodejs/src/common/personhog/grpc-retry.ts@@ -11,6 +11,8 @@ const RETRYABLE_CODES = new Set([Code.Aborted,Code.Internal,Code.Unknown,+ // No caller passes an abort signal, so Canceled is always a stream the peer reset, as a pod leaving does.+ Code.Canceled,])function isRetryable(error: unknown): error is ConnectError {diff --git a/nodejs/src/common/personhog/identity-clients.ts b/nodejs/src/common/personhog/identity-clients.tsindex 2fa1e0d66599..bf5d772cff1d 100644--- a/nodejs/src/common/personhog/identity-clients.ts+++ b/nodejs/src/common/personhog/identity-clients.ts@@ -17,13 +17,16 @@ export function createIdentityClients(identity: PersonhogIdentityOperationsclose: () => void} {- // A zero or negative deadline would kill every merge client-side.+ // A zero or negative deadline would kill every merge client-side, or disable the deadline on every other call.if (options.mergeTimeoutMs !== undefined &&(!Number.isInteger(options.mergeTimeoutMs) || options.mergeTimeoutMs < 1)) {throw new Error(`PERSONHOG_MERGE_TIMEOUT_MS must be an integer >= 1, got ${options.mergeTimeoutMs}`)}+ if (config.timeoutMs !== undefined && (!Number.isInteger(config.timeoutMs) || config.timeoutMs < 1)) {+ throw new Error(`PERSONHOG_IDENTITY_TIMEOUT_MS must be an integer >= 1, got ${config.timeoutMs}`)+ }const { transport, stateMonitor } = createPersonhogTransport(config)return {identity: new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport), options),diff --git a/nodejs/src/common/personhog/identity.test.ts b/nodejs/src/common/personhog/identity.test.tsindex 8017a94ccee8..6859aed0a68d 100644--- a/nodejs/src/common/personhog/identity.test.ts+++ b/nodejs/src/common/personhog/identity.test.ts@@ -11,9 +11,15 @@ import { DistinctIdKey, PersonhogIdentityOperations } from './identity'import { createIdentityClients } from './identity-clients'describe('PersonhogIdentityOperations', () => {- it('refuses a merge timeout that would kill every merge client-side', () => {- expect(() => createIdentityClients({} as never, { mergeTimeoutMs: 0 })).toThrow('PERSONHOG_MERGE_TIMEOUT_MS')- })+ it.each([+ ['merge', {}, { mergeTimeoutMs: 0 }, 'PERSONHOG_MERGE_TIMEOUT_MS'],+ ['request', { timeoutMs: 0 }, {}, 'PERSONHOG_IDENTITY_TIMEOUT_MS'],+ ])(+ 'refuses a zero %s timeout, which would kill or unbound every call client-side',+ (_name, config, options, key) => {+ expect(() => createIdentityClients(config as never, options)).toThrow(key)+ }+ )function makeOps(handlers: {getPersonsByDistinctIds?: jest.Mockdiff --git a/nodejs/src/common/personhog/index.ts b/nodejs/src/common/personhog/index.tsindex 96adab25e199..a1a18ab36c89 100644--- a/nodejs/src/common/personhog/index.ts+++ b/nodejs/src/common/personhog/index.ts@@ -25,6 +25,7 @@ export type PersonHogConfig = Pick<| 'PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS'| 'PERSONHOG_TLS'| 'PERSONHOG_TIMEOUT_MS'+ | 'PERSONHOG_IDENTITY_TIMEOUT_MS'| 'PERSONHOG_MERGE_TIMEOUT_MS'| 'PERSONHOG_READ_MAX_BYTES'| 'PERSONHOG_WRITE_MAX_BYTES'diff --git a/nodejs/src/common/personhog/personhog-person-read-repository.test.ts b/nodejs/src/common/personhog/personhog-person-read-repository.test.tsindex 0b5518afea6e..04016ea15e30 100644--- a/nodejs/src/common/personhog/personhog-person-read-repository.test.ts+++ b/nodejs/src/common/personhog/personhog-person-read-repository.test.ts@@ -166,6 +166,7 @@ describe('PersonHogPersonReadRepository', () => {['Aborted', Code.Aborted],['Internal', Code.Internal],['Unknown', Code.Unknown],+ ['Canceled', Code.Canceled],])('retries on %s and succeeds', async (_name, code) => {const { client, handlers } = createMockClientAndHandlers()let callCount = 0@@ -196,7 +197,6 @@ describe('PersonHogPersonReadRepository', () => {['FailedPrecondition', Code.FailedPrecondition],['OutOfRange', Code.OutOfRange],['DataLoss', Code.DataLoss],- ['Canceled', Code.Canceled],])('does not retry on %s', async (_name, code) => {const { client, handlers } = createMockClientAndHandlers()handlers.getPersonsByDistinctIds.mockImplementation(() => {diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.tsindex cab7e2a87bd1..e6216519566b 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts@@ -403,30 +403,32 @@ describe('RoutingPersonsStore', () => {})it.each([- ['a plain merge starts no further attempt', mergeRequest, [], 1],+ ['a plain merge starts no further attempt', mergeRequest, [], 1, 1],['a fold re-drive starts no further pair',foldRequest,[{ survivor: null, results: [], foldAborted: 'conflict' as const }],2,+ 2,],- ])('abandoned at the shadow ceiling, %s', async (_name, request, answeredFirst, expectedCalls) => {+ ])('abandoned at the shadow ceiling, %s', async (_name, request, answeredFirst, expectedCalls, redriven) => {jest.useFakeTimers()try {const stores = makeStores()- stores.pg.mergePersons.mockResolvedValue({+ const settled = {survivor: person(1, '1'),results: [- { sourceDistinctId: 'anon-1', outcome: 'merged' },- { sourceDistinctId: 'anon-2', outcome: 'merged' },+ { sourceDistinctId: 'anon-1', outcome: 'merged' as const },+ { sourceDistinctId: 'anon-2', outcome: 'merged' as const },],- })+ }+ stores.pg.mergePersons.mockResolvedValue(settled)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)+ stores.personhogMock.mergePersons.mockReturnValueOnce(hanging).mockResolvedValue(settled)const store = makeStore(stores, 'shadow')const pending = store.mergePersons(request() as never, 7)@@ -436,6 +438,14 @@ describe('RoutingPersonsStore', () => {await jest.advanceTimersByTimeAsync(1_000)expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)++ // The abandoned merge and the pairs it kept from starting are re-driven at the next flush.+ await jest.advanceTimersByTimeAsync(5_000)+ const flushing = store.flush()+ await jest.advanceTimersByTimeAsync(1_000)+ await flushing++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls + redriven)} finally {jest.useRealTimers()}@@ -816,39 +826,33 @@ describe('RoutingPersonsStore', () => {const retriesRecorded = (): number =>(personhogStoreShadowCreateRetriesCounter.labels as jest.Mock).mock.calls.length- it.each([- ['retriable', retriable()],- ['cancelled', new ConnectError('canceled', Code.Canceled)],- ])(- 'a shadow createPerson whose failure is %s retries in place and lands before the event returns',- async (_case, failure) => {- jest.useFakeTimers()- try {- const stores = makeStores()- stores.pg.createPerson.mockResolvedValue(createdByPg)- stores.personhogMock.createPerson- .mockRejectedValueOnce(failure)- .mockResolvedValueOnce(createdByPersonhog(true))- const store = makeStore(stores, 'shadow')- const errorsBefore = shadowErrorsRecorded()+ it('a shadow createPerson whose failure is retriable retries in place and lands before the event returns', async () => {+ jest.useFakeTimers()+ try {+ const stores = makeStores()+ stores.pg.createPerson.mockResolvedValue(createdByPg)+ stores.personhogMock.createPerson+ .mockRejectedValueOnce(retriable())+ .mockResolvedValueOnce(createdByPersonhog(true))+ const store = makeStore(stores, 'shadow')+ const errorsBefore = shadowErrorsRecorded()- const creating = createIn(store)- await jest.advanceTimersByTimeAsync(1_000)- const result = await creating-- expect(result).toBe(createdByPg)- expect(stores.personhogMock.createPerson).toHaveBeenCalledTimes(2)- expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()- expect(shadowErrorsRecorded()).toBe(errorsBefore)- expect(personhogStoreShadowCreateRetriesCounter.labels).toHaveBeenCalledWith({ outcome: 'retried' })- expect(personhogStoreShadowCreateRetriesCounter.labels).toHaveBeenCalledWith({- outcome: 'recovered',- })- } finally {- jest.useRealTimers()- }+ const creating = createIn(store)+ await jest.advanceTimersByTimeAsync(1_000)+ const result = await creating++ expect(result).toBe(createdByPg)+ expect(stores.personhogMock.createPerson).toHaveBeenCalledTimes(2)+ expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()+ expect(shadowErrorsRecorded()).toBe(errorsBefore)+ expect(personhogStoreShadowCreateRetriesCounter.labels).toHaveBeenCalledWith({ outcome: 'retried' })+ expect(personhogStoreShadowCreateRetriesCounter.labels).toHaveBeenCalledWith({+ outcome: 'recovered',+ })+ } finally {+ jest.useRealTimers()}- )+ })it('a shadow createPerson refused for a deterministic reason fails once, counted, with no retry', async () => {const stores = makeStores()diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.tsindex b354b11e5d6d..9b4818cfbe18 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts@@ -1,4 +1,4 @@-import { Code, ConnectError } from '@connectrpc/connect'+import { ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import { errorClassLabel } from '~/common/personhog/metrics'@@ -138,12 +138,9 @@ const SHADOW_CREATE_RETRY_SLEEP_MS = 1_000const SHADOW_CREATE_RETRY_MAX_SLEEP_MS = 8_000const SHADOW_CREATE_RETRY_DEADLINE_MS = 20_000-/** Transient per the transport's own classification, or a stream reset; identity's get-or-create is safe to repeat. */+/** Transient per the transport's own classification; identity's get-or-create is safe to repeat. */function isTransientCreateFailure(error: unknown): boolean {- return (- (error as { isRetriable?: boolean } | null)?.isRetriable === true ||- (error instanceof ConnectError && error.code === Code.Canceled)- )+ return (error as { isRetriable?: boolean } | null)?.isRetriable === true}/**@@ -651,7 +648,8 @@ export class RoutingPersonsStore implements PersonsStore {}return unsettled}- if (error instanceof PersonMergeCallFailedError && defer) {+ // Abandoned at the ceiling, the merge is re-driven at a flush under the same op id.+ if ((error instanceof PersonMergeCallFailedError || error instanceof ShadowVerbTimeoutError) && defer) {this.deferShadowMerge(request, batchId)}throw errordiff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 3190fe42e0aa..774fa3cafd2f 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -379,7 +379,7 @@ export class IngestionApiServer implements NodeServer {{addr: this.config.PERSONHOG_IDENTITY_ADDR,useTls: this.config.PERSONHOG_TLS,- timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,+ timeoutMs: this.config.PERSONHOG_IDENTITY_TIMEOUT_MS,clientName: 'ingestion-persons-store',initialStreamWindowBytes: this.config.PERSONHOG_INITIAL_STREAM_WINDOW_BYTES,initialConnectionWindowBytes: this.config.PERSONHOG_INITIAL_CONNECTION_WINDOW_BYTES,