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.

fix(ingestion): retry a failed shadow create in place (#114062)

Zach Brownb5cab847615d
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index 40d831d836f0..a8d713287508 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -196,6 +196,12 @@ export const personhogStoreShadowMergeRedriveCounter = new Counter({
labelNames: ['outcome'],
})
+export const personhogStoreShadowCreateRetriesCounter = new Counter({
+ name: 'personhog_store_shadow_create_retries_total',
+ help: 'Shadow create attempts past the first (retried) and creates that landed after a retry (recovered); one that misses its deadline counts under personhog_store_shadow_errors_total',
+ labelNames: ['outcome'],
+})
+
export const personhogStoreShadowCompareFailedCounter = new Counter({
name: 'personhog_store_shadow_compare_failed_total',
help: 'Shadow comparisons that threw, which is a fault in the comparison rather than in either backend',
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
index 79cfad228b0e..cab7e2a87bd1 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
@@ -4,6 +4,7 @@ import { DateTime } from 'luxon'
import {
personhogStoreShadowCompareFailedCounter,
personhogStoreShadowComparedCounter,
+ personhogStoreShadowCreateRetriesCounter,
personhogStoreShadowDivergenceCounter,
personhogStoreShadowErrorsCounter,
personhogStoreShadowMergeRedriveCounter,
@@ -23,6 +24,7 @@ const mockShadowTimerStop = jest.fn()
jest.mock('~/common/persons/metrics', () => ({
personhogStoreShadowErrorsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personhogStoreShadowCreateRetriesCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowSkipsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowDivergenceCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowComparedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
@@ -805,62 +807,120 @@ describe('RoutingPersonsStore', () => {
created: true,
} as never
+ const retriable = (): Error =>
+ Object.assign(new ConnectError('timed out', Code.DeadlineExceeded), { isRetriable: true })
+ const createdByPersonhog = (created: boolean) =>
+ ({ success: true, person: person(1, '99'), messages: [], created }) as never
+ const shadowErrorsRecorded = (): number =>
+ (personhogStoreShadowErrorsCounter.labels as jest.Mock).mock.calls.length
+ const retriesRecorded = (): number =>
+ (personhogStoreShadowCreateRetriesCounter.labels as jest.Mock).mock.calls.length
+
it.each([
- [
- 'retriable, holds its properties set-once',
- Object.assign(new ConnectError('timed out', Code.DeadlineExceeded), { isRetriable: true }),
- false,
- { set: {}, setOnce: { plan: 'pro' }, unset: [], denied: false, shouldForceUpdate: true },
- ],
- [
- 'retriable for an identified person, holds the identity too',
- Object.assign(new ConnectError('timed out', Code.DeadlineExceeded), { isRetriable: true }),
- true,
- { setOnce: { plan: 'pro' }, isIdentified: true },
- ],
- ['deterministic, holds nothing', new ConnectError('rejected', Code.InvalidArgument), false, null],
- ])('a shadow createPerson whose failure is %s', async (_case, failure, isIdentified, held) => {
+ ['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()
+
+ 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()
stores.pg.createPerson.mockResolvedValue(createdByPg)
- stores.personhogMock.createPerson.mockRejectedValue(failure)
+ stores.personhogMock.createPerson.mockRejectedValue(new ConnectError('rejected', Code.InvalidArgument))
const store = makeStore(stores, 'shadow')
+ const errorsBefore = shadowErrorsRecorded()
+ const retriesBefore = retriesRecorded()
- const result = await createIn(store, isIdentified)
+ expect(await createIn(store)).toBe(createdByPg)
- expect(result).toBe(createdByPg)
- expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith(
- expect.objectContaining({ verb: 'createPerson' })
- )
- if (held === null) {
- expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()
- } else {
- expect(stores.personhogMock.holdEventOps).toHaveBeenCalledWith(
- 1,
- 'd1',
- expect.objectContaining({ ...held, eventName: '$create_person' }),
- 0
- )
- }
+ expect(stores.personhogMock.createPerson).toHaveBeenCalledTimes(1)
+ expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()
+ expect(shadowErrorsRecorded()).toBe(errorsBefore + 1)
+ expect(retriesRecorded()).toBe(retriesBefore)
})
- it('a shadow createPerson that fails after the ceiling abandoned it holds nothing', async () => {
+ it.each([
+ [false, { setOnce: { plan: 'pro' }, shouldForceUpdate: true }],
+ [true, { setOnce: { plan: 'pro' }, shouldForceUpdate: true, isIdentified: true }],
+ ])(
+ 'a retried create that finds the person (identified=%p) applies its creation properties set-once',
+ async (isIdentified, expected) => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ stores.pg.createPerson.mockResolvedValue(createdByPg)
+ const existing = createdByPersonhog(false) as { person: InternalPerson }
+ stores.personhogMock.createPerson
+ .mockRejectedValueOnce(retriable())
+ .mockResolvedValueOnce(existing as never)
+ const store = makeStore(stores, 'shadow')
+
+ const creating = createIn(store, isIdentified)
+ await jest.advanceTimersByTimeAsync(1_000)
+ await creating
+
+ // Under the event's own batch: the create is still inside the event when it lands.
+ expect(stores.personhogMock.applyEventOps).toHaveBeenCalledWith(
+ existing.person,
+ expect.objectContaining({ ...expected, eventName: '$create_person' }),
+ 'd1',
+ 0
+ )
+ } finally {
+ jest.useRealTimers()
+ }
+ }
+ )
+
+ it('a create still failing at the deadline is counted once', async () => {
jest.useFakeTimers()
try {
const stores = makeStores()
stores.pg.createPerson.mockResolvedValue(createdByPg)
- let fail: (error: Error) => void = () => {}
- stores.personhogMock.createPerson.mockReturnValue(
- new Promise<never>((_resolve, reject) => (fail = reject))
- )
+ stores.personhogMock.createPerson.mockRejectedValue(retriable())
const store = makeStore(stores, 'shadow')
+ const errorsBefore = shadowErrorsRecorded()
const creating = createIn(store)
- await jest.advanceTimersByTimeAsync(60_000)
- await creating
- fail(Object.assign(new ConnectError('timed out', Code.DeadlineExceeded), { isRetriable: true }))
- await jest.advanceTimersByTimeAsync(1)
+ await jest.advanceTimersByTimeAsync(40_000)
+ expect(await creating).toBe(createdByPg)
+ const attempts = stores.personhogMock.createPerson.mock.calls.length
+ // 1 s doubling to 8 s with 5% jitter fits five or six attempts in 20 s; a try count gives another number.
+ expect(attempts).toBeGreaterThanOrEqual(5)
+ expect(attempts).toBeLessThanOrEqual(6)
expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()
+ expect(shadowErrorsRecorded()).toBe(errorsBefore + 1)
+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenLastCalledWith(
+ expect.objectContaining({ verb: 'createPerson' })
+ )
} finally {
jest.useRealTimers()
}
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
index c5062102aff7..b354b11e5d6d 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
@@ -1,10 +1,11 @@
-import { ConnectError } from '@connectrpc/connect'
+import { Code, ConnectError } from '@connectrpc/connect'
import { DateTime } from 'luxon'
import { errorClassLabel } from '~/common/personhog/metrics'
import {
personhogStoreShadowCompareFailedCounter,
personhogStoreShadowComparedCounter,
+ personhogStoreShadowCreateRetriesCounter,
personhogStoreShadowDivergenceCounter,
personhogStoreShadowDurationSeconds,
personhogStoreShadowErrorsCounter,
@@ -16,7 +17,7 @@ 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 { promiseRetry, retryIfRetriable } from '~/common/utils/retries'
import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'
@@ -128,6 +129,39 @@ const SHADOW_MERGE_DEFERRED_LIMIT = 1_000
type DeferredShadowMerge = { request: MergePersonsRequest; batchId: number; notBefore: number; expiresAt: number }
+/**
+ * A failed shadow create retries in place; the event's distinct-id sequencing keeps later events behind it.
+ * The deadline is soft: the last attempt starts before it and may run two transport budgets past it, so the create
+ * ends under 40 s of the worker's 60 s sub-batch ack deadline. The batch's flush has its own ceiling after that.
+ */
+const SHADOW_CREATE_RETRY_SLEEP_MS = 1_000
+const SHADOW_CREATE_RETRY_MAX_SLEEP_MS = 8_000
+const 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. */
+function isTransientCreateFailure(error: unknown): boolean {
+ return (
+ (error as { isRetriable?: boolean } | null)?.isRetriable === true ||
+ (error instanceof ConnectError && error.code === Code.Canceled)
+ )
+}
+
+/**
+ * The creation properties as set-once ops, for a person that turned out to exist on the personhog side. Forced, as
+ * the leader drops an unforced set-once of a filtered key even onto a bare stub.
+ */
+function creationOps(properties: Properties, isIdentified: boolean): EventOps {
+ return {
+ set: {},
+ setOnce: properties,
+ unset: [],
+ denied: false,
+ shouldForceUpdate: true,
+ eventName: CREATE_EVENT_NAME,
+ ...(isIdentified ? { isIdentified: true } : {}),
+ }
+}
+
/** Raised when a shadow verb outruns its ceiling and the batch abandons it. */
class ShadowVerbTimeoutError extends Error {
constructor(verb: string) {
@@ -390,35 +424,29 @@ export class RoutingPersonsStore implements PersonsStore {
batchId
),
{
- shadow: (abandoned) =>
- this.shadowCreate(
- () =>
- this.personhog.createPerson(
- createdAt,
- properties,
- propertiesLastUpdatedAt,
- propertiesLastOperation,
- teamId,
- isUserId,
- isIdentified,
- uuid,
- primaryDistinctId,
- extraDistinctIds,
- tx,
- batchId
- ),
- teamId,
- properties,
- isIdentified,
- primaryDistinctId.distinctId,
- batchId,
- abandoned
+ shadow: () =>
+ this.shadowCreate(() =>
+ this.personhog.createPerson(
+ createdAt,
+ properties,
+ propertiesLastUpdatedAt,
+ propertiesLastOperation,
+ teamId,
+ isUserId,
+ isIdentified,
+ uuid,
+ primaryDistinctId,
+ extraDistinctIds,
+ tx,
+ batchId
+ )
),
after: (authoritative, shadow, abandoned) =>
this.reconcileShadowCreate(
authoritative,
shadow as CreatePersonResult,
properties,
+ isIdentified,
primaryDistinctId.distinctId,
batchId,
abandoned
@@ -428,40 +456,38 @@ export class RoutingPersonsStore implements PersonsStore {
}
/**
- * A create the client gave up on may have left the person without its properties, and the event does not retry
- * here, so its properties are held set-once for the distinct id. A deterministic rejection would fail again, and
- * an abandoned create's batch may be released, so neither is held.
+ * A failed create retries in place, whatever failed: Postgres holds the person now, so no later event would
+ * create it on the personhog side. The deadline, not a try count, bounds the loop.
*/
- private async shadowCreate(
- create: () => Promise<CreatePersonResult>,
- teamId: number,
- properties: Properties,
- isIdentified: boolean,
- distinctId: string,
- batchId: number,
- abandoned: AbortSignal
- ): Promise<CreatePersonResult> {
- try {
- return await create()
- } catch (error) {
- if (!abandoned.aborted && (error as { isRetriable?: boolean })?.isRetriable === true) {
- this.personhog.holdEventOps(
- teamId,
- distinctId,
- {
- set: {},
- setOnce: properties,
- unset: [],
- denied: false,
- shouldForceUpdate: true,
- eventName: CREATE_EVENT_NAME,
- ...(isIdentified ? { isIdentified: true } : {}),
- },
- batchId
- )
+ private async shadowCreate(create: () => Promise<CreatePersonResult>): Promise<CreatePersonResult> {
+ let attempts = 0
+ const result = await retryIfRetriable(
+ async () => {
+ attempts += 1
+ if (attempts > 1) {
+ personhogStoreShadowCreateRetriesCounter.labels({ outcome: 'retried' }).inc()
+ }
+ try {
+ return await create()
+ } catch (error) {
+ if (isTransientCreateFailure(error)) {
+ throw error
+ }
+ const failure = error instanceof Object ? error : new Error(String(error))
+ throw Object.assign(failure, { isRetriable: false })
+ }
+ },
+ {
+ tries: Number.POSITIVE_INFINITY,
+ sleepMs: SHADOW_CREATE_RETRY_SLEEP_MS,
+ maxSleepMs: SHADOW_CREATE_RETRY_MAX_SLEEP_MS,
+ softDeadlineMs: SHADOW_CREATE_RETRY_DEADLINE_MS,
}
- throw error
+ )
+ if (attempts > 1) {
+ personhogStoreShadowCreateRetriesCounter.labels({ outcome: 'recovered' }).inc()
}
+ return result
}
/** Postgres created the person and personhog only found it: apply the creation properties set-once. */
@@ -469,6 +495,7 @@ export class RoutingPersonsStore implements PersonsStore {
authoritative: CreatePersonResult,
shadow: CreatePersonResult,
properties: Properties,
+ isIdentified: boolean,
distinctId: string,
batchId: number,
abandoned: AbortSignal
@@ -480,15 +507,7 @@ export class RoutingPersonsStore implements PersonsStore {
) {
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)
+ await this.personhog.applyEventOps(shadow.person, creationOps(properties, isIdentified), distinctId, batchId)
}
applyEventOps(
diff --git a/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
index 563cbb6400ad..96bf4e524bbd 100644
--- a/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
+++ b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts
@@ -9,6 +9,7 @@
// `docker compose -f docker-compose.dev.yml --profile ingestion up`, or a
// `hogli start` dev stack (the `personhog` capability). Addresses override
// via PERSONHOG_E2E_ROUTER_ADDR / PERSONHOG_E2E_IDENTITY_ADDR.
+import { Code, ConnectError } from '@connectrpc/connect'
import { DateTime } from 'luxon'
import { isDeepStrictEqual } from 'node:util'
import { Pool } from 'pg'
@@ -33,6 +34,7 @@ import { createIdentityClients } from '~/common/personhog/identity-clients'
import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'
import {
personhogStoreShadowComparedCounter,
+ personhogStoreShadowCreateRetriesCounter,
personhogStoreShadowDivergenceCounter,
personhogStoreShadowErrorsCounter,
} from '~/common/persons/metrics'
@@ -110,12 +112,13 @@ describe('personhog shadow parity (e2e)', () => {
* One ingestion pod: its own caches over the shared databases and the
* shared personhog cluster, so two pods can interleave on one person.
*/
- const newPod = (): RoutingPersonsStore =>
+ /** One ingestion pod over the shared databases; the personhog repository can be wrapped to fail one call. */
+ const newPod = (repository: PersonHogPersonWriteRepository = writeRepository): RoutingPersonsStore =>
new RoutingPersonsStore(
new BatchWritingPersonsStore(new PostgresPersonRepository(hub.postgres), outputs(), {
metricEmissionIntervalMs: 0,
}),
- new PersonhogPersonsStore(writeRepository, {
+ new PersonhogPersonsStore(repository, {
maxConcurrentUpdates: 10,
updateAllProperties: false,
syncMergeMoveLimit: 10_000,
@@ -344,12 +347,114 @@ describe('personhog shadow parity (e2e)', () => {
personhogStoreShadowDivergenceCounter.reset()
personhogStoreShadowComparedCounter.reset()
personhogStoreShadowErrorsCounter.reset()
+ personhogStoreShadowCreateRetriesCounter.reset()
})
afterEach(() => {
routing.releaseBatch(batchId)
})
+ describe('shadow creates', () => {
+ /**
+ * A personhog repository whose first create of one distinct id fails. With `after`, identity commits the
+ * person first and the failure follows, which leaves the person without its properties: what a cancellation
+ * between the stub commit and the property push leaves.
+ */
+ const failingCreateRepository = (
+ distinctId: string,
+ failure: () => Error,
+ after = false
+ ): PersonHogPersonWriteRepository => {
+ let failed = false
+ const real = writeRepository.getOrCreatePersonByDistinctId.bind(writeRepository)
+ return new Proxy(writeRepository, {
+ get(target, property, receiver) {
+ if (property !== 'getOrCreatePersonByDistinctId') {
+ return Reflect.get(target, property, receiver)
+ }
+ return async (entry: Parameters<typeof real>[0], callerTag?: string) => {
+ if (failed || entry.distinctId !== distinctId) {
+ return real(entry, callerTag)
+ }
+ failed = true
+ if (after) {
+ await real({ ...entry, setProperties: {}, setOnceProperties: {} }, callerTag)
+ }
+ throw failure()
+ }
+ },
+ })
+ }
+
+ const retriableUnavailable = (): Error =>
+ Object.assign(new ConnectError('Server at capacity', Code.Unavailable), { isRetriable: true })
+
+ it.each([
+ ['refused before identity committed', false, retriableUnavailable],
+ ['cancelled after identity committed', true, () => new ConnectError('canceled', Code.Canceled)],
+ ])('a shadow create %s still lands the person and its creation properties', async (_name, after, failure) => {
+ const distinctId = id(`create-${after ? 'cancelled' : 'refused'}`)
+ const pod = newPod(failingCreateRepository(distinctId, failure, after))
+ await pod.createPerson(
+ DateTime.utc(),
+ { plan: 'free' },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ uuidFromDistinctId(teamId, distinctId),
+ { distinctId },
+ undefined,
+ undefined,
+ batchId
+ )
+ // The retry lands inside the create, so nothing is recorded as a shadow failure.
+ expect(await shadowErrors()).toBe(0)
+ expect(await counterTotal(personhogStoreShadowCreateRetriesCounter)).toBe(2)
+ await pod.flush()
+ pod.releaseBatch(batchId)
+
+ // The next event for the id is an update, as Postgres already holds the person; the shadow has to
+ // catch up on its own.
+ batchId += 1
+ const person = await pod.fetchForUpdate(teamId, distinctId, batchId)
+ await pod.applyEventOps(person!, ops({ $set: { visits: 2 } }, '$pageview'), distinctId, batchId)
+ await pod.flush()
+ pod.releaseBatch(batchId)
+
+ await expectDurableRowParity(distinctId)
+ })
+
+ it('a set-once right behind a create that failed after identity committed yields to the creation value', async () => {
+ const distinctId = id('create-order')
+ const pod = newPod(
+ failingCreateRepository(distinctId, () => new ConnectError('canceled', Code.Canceled), true)
+ )
+ await pod.createPerson(
+ DateTime.utc(),
+ { plan: 'free' },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ uuidFromDistinctId(teamId, distinctId),
+ { distinctId },
+ undefined,
+ undefined,
+ batchId
+ )
+ // The event behind the create in its distinct id's sequence: Postgres ignores the set-once.
+ const person = await pod.fetchForUpdate(teamId, distinctId, batchId)
+ await pod.applyEventOps(person!, ops({ $set_once: { plan: 'pro' } }), distinctId, batchId)
+ await pod.flush()
+ pod.releaseBatch(batchId)
+
+ await expectDurableRowParity(distinctId)
+ })
+ })
+
it('creation and updates read back identically through both backends', async () => {
const distinctId = id('reader')
await createThroughBoth(distinctId, { plan: 'free' }, batchId)