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): hold and re-drive personhog shadow ops the shadow cannot yet apply (#112107)

Zach Brownf099b65e54d2
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index 20106acfafa9..188e5bb95a68 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -190,6 +190,12 @@ export const personhogStoreShadowFoldRedriveCounter = new Counter({
labelNames: ['outcome'],
})
+export const personhogStoreShadowMergeRedriveCounter = new Counter({
+ name: 'personhog_store_shadow_merge_redrive_total',
+ help: 'Shadow merges re-driven at a flush after their retries ended unsettled: settled, deferred to a later flush, or dropped; abandoned counts a re-queue at the ceiling before the final outcome',
+ 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/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
index ddb397e21b5a..cb4918a7a23a 100644
--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
@@ -11,6 +11,7 @@ import { PersonMergeCallFailedError, createDefaultSyncMergeMode } from './person
import { EventOps, extractEventOps } from './person-update'
import { mergeOpIdFromRequest } from './person-uuid'
import {
+ HELD_LANES_LIMIT,
PersonhogPersonsStore,
PersonhogUnsupportedFieldError,
personhogStoreCachePurgeCounter,
@@ -346,6 +347,32 @@ describe('PersonhogPersonsStore', () => {
expect(repository.resolvePersonsByDistinctIds.mock.calls[0][0]).toHaveLength(ids.length)
})
+ it.each([['fetchForUpdate' as const], ['fetchForChecking' as const]])(
+ '%s issued while the prefetch is out waits for it instead of resolving the id alone',
+ async (read) => {
+ let answer: () => void = () => {}
+ repository.resolvePersonsByDistinctIds
+ .mockImplementationOnce(
+ (() =>
+ new Promise((resolve) => {
+ answer = () => resolve([{ teamId: 1, distinctId: 'd1', person: { ...person } }])
+ })) as never
+ )
+ .mockResolvedValue([{ teamId: 1, distinctId: 'd1', person: { ...person } }] as never)
+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)
+ const bound = store.forBatch(0)
+
+ // The pipeline fires the prefetch without awaiting it.
+ const prefetching = store.prefetchPersons([{ teamId: 1, distinctId: 'd1', batchId: 0 }])
+ const reading = bound[read](1, 'd1')
+ answer()
+ await prefetching
+
+ expect((await reading)?.id).toBe('7')
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ }
+ )
+
it('a stale null result cannot downgrade a live mapping', async () => {
repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
repository.fetchPersonById.mockResolvedValue({ ...person })
@@ -958,6 +985,242 @@ describe('PersonhogPersonsStore', () => {
expect((store as any).projections.get('1:9')).toBeUndefined()
})
+ describe('held lanes', () => {
+ it('writes held ops, folded, to whoever owns the distinct id at flush and drops a cached absence', async () => {
+ const bound = store.forBatch(0)
+ ;(store as any).resolutions.set('1:d1', null)
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ store.holdEventOps(1, 'd1', ops({ $set: { b: '2' } }), 0)
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([
+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },
+ ] as never)
+
+ await bound.flush()
+
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(
+ expect.objectContaining({ personId: '9', setProperties: { a: '1', b: '2' } }),
+ expect.any(String)
+ )
+ expect(edgeOf('1:d1')).toBeUndefined()
+ })
+
+ it('keeps held ops nobody owns yet across the shadow release and writes them once the id resolves', async () => {
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ repository.resolvePersonsByDistinctIds
+ .mockResolvedValueOnce([] as never)
+ .mockResolvedValue([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }] as never)
+ personhogStoreFlushCounter.reset()
+
+ await store.forBatch(0).flush()
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ const outcomes = (await personhogStoreFlushCounter.get()).values
+ .filter((entry) => entry.value > 0)
+ .map((entry) => entry.labels.outcome)
+ expect(outcomes).toEqual(['held_deferred'])
+ store.abandonBatch(0)
+ // A flush inside the re-check interval asks identity nothing.
+ await store.forBatch(1).flush()
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ const later = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 6_000)
+ try {
+ await store.forBatch(2).flush()
+ } finally {
+ later.mockRestore()
+ }
+
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(2)
+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(
+ expect.objectContaining({ personId: '9', setProperties: { a: '1' } }),
+ expect.any(String)
+ )
+ })
+
+ it('resolves every held lane due in one identity call per flush', async () => {
+ for (const distinctId of ['d1', 'd2', 'd3']) {
+ store.holdEventOps(1, distinctId, ops({ $set: { a: distinctId } }), 0)
+ }
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([
+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },
+ { teamId: 1, distinctId: 'd2', person: null },
+ { teamId: 1, distinctId: 'd3', person: { ...person, id: '11' } },
+ ] as never)
+
+ await store.forBatch(0).flush()
+
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledWith(
+ [
+ { teamId: 1, distinctId: 'd1' },
+ { teamId: 1, distinctId: 'd2' },
+ { teamId: 1, distinctId: 'd3' },
+ ],
+ expect.any(String)
+ )
+ const written = repository.updatePersonProperties.mock.calls.map(([request]) => [
+ (request as { personId: string }).personId,
+ (request as { setProperties: unknown }).setProperties,
+ ])
+ expect(written).toHaveLength(2)
+ expect(written).toEqual(
+ expect.arrayContaining([
+ ['9', { a: 'd1' }],
+ ['11', { a: 'd3' }],
+ ])
+ )
+ })
+
+ it('a failed held resolve still writes the lanes with an owner and leaves the held lane for the next flush', async () => {
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { b: '2' } }), 'd2')
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ repository.resolvePersonsByDistinctIds
+ .mockRejectedValueOnce(new Error('identity unavailable') as never)
+ .mockResolvedValue([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }] as never)
+
+ await bound.flush()
+ const writtenTo = () =>
+ repository.updatePersonProperties.mock.calls.map(
+ ([request]) => (request as { personId: string }).personId
+ )
+ expect(writtenTo()).toEqual(['7'])
+
+ await bound.flush()
+ expect(writtenTo()).toEqual(['7', '9'])
+ expect(repository.updatePersonProperties).toHaveBeenLastCalledWith(
+ expect.objectContaining({ personId: '9', setProperties: { a: '1' } }),
+ expect.any(String)
+ )
+ })
+
+ it('sheds the earliest-held lane, counted, once held lanes pass the cap', async () => {
+ personhogStoreFlushCounter.reset()
+ for (let i = 0; i <= HELD_LANES_LIMIT; i++) {
+ store.holdEventOps(1, `held-${i}`, ops({ $set: { a: '1' } }), 0)
+ }
+
+ expect(store.hasHeldOps(1, 'held-0')).toBe(false)
+ expect(store.hasHeldOps(1, 'held-1')).toBe(true)
+ expect(store.hasHeldOps(1, `held-${HELD_LANES_LIMIT}`)).toBe(true)
+ const shed = (await personhogStoreFlushCounter.get()).values.find(
+ (entry) => entry.labels.outcome === 'held_dropped_limit'
+ )
+ expect(shed?.value).toBe(1)
+ })
+
+ it('a lane that found its owner no longer counts toward the cap', async () => {
+ // 'waiting' is held before 'owned', so only the owned lane leaving the count keeps 'waiting' under the cap.
+ store.holdEventOps(1, 'waiting', ops({ $set: { a: '1' } }), 0)
+ store.holdEventOps(1, 'owned', ops({ $set: { a: '1' } }), 0)
+ repository.resolvePersonsByDistinctIds.mockImplementation(((keys: { distinctId: string }[]) =>
+ Promise.resolve(
+ keys.map(({ distinctId }) => ({
+ teamId: 1,
+ distinctId,
+ person: distinctId === 'owned' ? { ...person, id: '9' } : null,
+ }))
+ )) as never)
+ await store.forBatch(0).flush()
+ personhogStoreFlushCounter.reset()
+
+ for (let i = 0; i < HELD_LANES_LIMIT - 1; i++) {
+ store.holdEventOps(1, `held-${i}`, ops({ $set: { a: '1' } }), 0)
+ }
+
+ expect(store.hasHeldOps(1, 'waiting')).toBe(true)
+ const shed = (await personhogStoreFlushCounter.get()).values.find(
+ (entry) => entry.labels.outcome === 'held_dropped_limit'
+ )
+ expect(shed).toBeUndefined()
+ })
+
+ it('drops held ops, counted, once nobody has owned the distinct id for the whole window', async () => {
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ personhogStoreFlushCounter.reset()
+ const now = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 61_000)
+ try {
+ await store.forBatch(0).flush()
+ } finally {
+ now.mockRestore()
+ }
+
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ const outcomes = (await personhogStoreFlushCounter.get()).values
+ .filter((entry) => entry.value > 0)
+ .map((entry) => entry.labels.outcome)
+ expect(outcomes).toEqual(['held_unowned'])
+ store.abandonBatch(0)
+ expect((store as any).entries.size).toBe(0)
+ })
+
+ it('a held write whose owner was merged away in between follows the redirect', async () => {
+ const bound = store.forBatch(0)
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ repository.resolvePersonsByDistinctIds
+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }] as never)
+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '11' } }] as never)
+ repository.updatePersonProperties
+ .mockRejectedValueOnce(new NoRowsUpdatedError('merged away'))
+ .mockResolvedValue({ person: { ...person, id: '11', version: 3 }, updated: true } as never)
+
+ await bound.flush()
+
+ expect(repository.updatePersonProperties).toHaveBeenLastCalledWith(
+ expect.objectContaining({ personId: '11', setProperties: { a: '1' } }),
+ expect.any(String)
+ )
+ })
+
+ it('does not hold an op the denylist keeps off persons', () => {
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }, '$exception'), 0)
+ expect((store as any).entries.size).toBe(0)
+ })
+
+ const creation = (properties: Record<string, unknown>) => ({
+ set: {},
+ setOnce: properties,
+ unset: [],
+ denied: false,
+ shouldForceUpdate: true,
+ eventName: '$create_person',
+ })
+
+ it('reports held ops until the flush writes them', async () => {
+ const bound = store.forBatch(0)
+ expect(store.hasHeldOps(1, 'd1')).toBe(false)
+ store.holdEventOps(1, 'd1', creation({ k: 'initial' }), 0)
+ expect(store.hasHeldOps(1, 'd1')).toBe(true)
+ expect(store.hasHeldOps(1, 'd2')).toBe(false)
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([
+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },
+ ] as never)
+
+ await bound.flush()
+
+ expect(store.hasHeldOps(1, 'd1')).toBe(false)
+ })
+
+ it('ops held into a lane a flush already resolved and wrote resolve the owner afresh', async () => {
+ const bound = store.forBatch(0)
+ store.holdEventOps(1, 'd1', ops({ $set: { a: '1' } }), 0)
+ repository.resolvePersonsByDistinctIds
+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }] as never)
+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '11' } }] as never)
+ await bound.flush()
+ // The batch still references the emptied lane, so it is the same entry the next hold lands in.
+ store.holdEventOps(1, 'd1', creation({ k: 'initial' }), 0)
+
+ await bound.flush()
+
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(2)
+ expect(repository.updatePersonProperties).toHaveBeenLastCalledWith(
+ expect.objectContaining({ personId: '11', setOnceProperties: { k: 'initial' } }),
+ expect.any(String)
+ )
+ })
+ })
+
describe('round-6 closures', () => {
const mergeReq = (sources = ['anon-1', 'anon-2']) => ({
teamId: 1,
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
index de4967a161ec..85a2082d5b7e 100644
--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
@@ -143,8 +143,36 @@ interface OpsLaneEntry {
settleWrite?: () => void
/** Set when a shadow-mode release abandoned this entry mid-write; the settle sheds it once unreferenced. */
abandoned?: boolean
+ /** Set while the person is unknown here; the flush resolves the distinct id before writing. */
+ unresolved?: boolean
+ /** When the lane was held, epoch ms; bounds how long an id nobody owns yet keeps its ops. */
+ heldSince?: number
+ /** When a flush last asked identity who owns the lane's id, epoch ms. */
+ lastResolvedAt?: number
}
+/** The lane for a distinct id with no known person; a numeric person id never starts with '?'. */
+function heldLaneKey(teamId: number, distinctId: string): string {
+ return `${teamId}:?${distinctId}`
+}
+
+/**
+ * How long a held lane outlives flushes that find nobody owning its id. The
+ * owner usually appears when another pod's shadow merge finishes, and that
+ * merge may itself have been deferred to its pod's flush, so the window is
+ * the ceiling one shadow verb may take rather than one flush.
+ */
+const HELD_LANE_MAX_AGE_MS = 60_000
+
+/** How soon after one answer a flush may ask again who owns a held lane's id. */
+const HELD_RESOLVE_INTERVAL_MS = 5_000
+
+/**
+ * The most held lanes one store keeps. Expired lanes stay through an identity outage so the first resolve after it
+ * can place them, so this bound is what keeps the outage from growing memory; past it the earliest-held lane is shed.
+ */
+export const HELD_LANES_LIMIT = 10_000
+
/**
* The personhog person store: resolution and creation through the identity
* service, person state through the leader's strong reads, and property
@@ -169,6 +197,10 @@ export class PersonhogPersonsStore implements PersonsStore {
* batch released must not record for a batch nothing can release again.
*/
private prefetchingBatches: Set<number> = new Set()
+ /** Keys of the held lanes still waiting for an owner, earliest hold first. */
+ private heldLaneOrder: Set<string> = new Set()
+ /** Prefetches still resolving, by distinct key. */
+ private pendingPrefetches: Map<string, Promise<void>> = new Map()
// The cache mirrors BatchWritingPersonsCache structure for structure,
// with two differences the names carry: `projections` holds a whole
@@ -447,6 +479,15 @@ export class PersonhogPersonsStore implements PersonsStore {
if (cached !== undefined) {
return cached
}
+ // A prefetch still resolving this id answers it; resolving alone would duplicate that call.
+ const pending = this.pendingPrefetches.get(`${teamId}:${distinctId}`)
+ if (pending) {
+ await pending
+ const prefetched = this.getCachedPerson(teamId, distinctId, 'check')
+ if (prefetched !== undefined) {
+ return prefetched
+ }
+ }
const generation = this.generationOf(teamId)
const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)
const document = resolved?.person ? this.identityDocument(resolved.person) : null
@@ -462,6 +503,15 @@ export class PersonhogPersonsStore implements PersonsStore {
if (cached !== undefined) {
return cached
}
+ // As in fetchForChecking: the prefetch caches an update-grade answer.
+ const pending = this.pendingPrefetches.get(`${teamId}:${distinctId}`)
+ if (pending) {
+ await pending
+ const prefetched = this.getCachedPerson(teamId, distinctId, 'update')
+ if (prefetched !== undefined) {
+ return prefetched
+ }
+ }
const generation = this.generationOf(teamId)
const distinctKey = `${teamId}:${distinctId}`
const edge = this.resolutions.get(distinctKey)
@@ -616,16 +666,7 @@ export class PersonhogPersonsStore implements PersonsStore {
segments: [ops],
})
} else {
- const last = existing.segments.length - 1
- const lastSegment = existing.segments[last]
- // Folding into a segment already on the wire would change the
- // payload underneath the write or lose this event.
- const folded = lastSegment === undefined || existing.inFlight ? null : foldOps(lastSegment, ops)
- if (folded === null) {
- existing.segments.push(ops)
- } else {
- existing.segments[last] = folded
- }
+ this.appendSegment(existing, ops)
}
// Replaces the projection outright. A purge during personNow's read
// outdates the view; the install declines and the next touch
@@ -638,6 +679,89 @@ export class PersonhogPersonsStore implements PersonsStore {
return [this.snapshot(projected), []]
}
+ private appendSegment(entry: OpsLaneEntry, ops: EventOps): void {
+ const last = entry.segments.length - 1
+ const lastSegment = entry.segments[last]
+ // Folding into a segment already on the wire would change the
+ // payload underneath the write or lose this event.
+ const folded = lastSegment === undefined || entry.inFlight ? null : foldOps(lastSegment, ops)
+ if (folded === null) {
+ entry.segments.push(ops)
+ } else {
+ entry.segments[last] = folded
+ }
+ }
+
+ /**
+ * Buffers ops for a distinct id this store cannot resolve yet, such as
+ * one another pod attached to a person whose shadow merge has not
+ * finished. Each flush resolves the id through identity and writes to
+ * its owner once there is one; an id nobody owns for the whole hold
+ * window drops its ops, counted, rather than wait on a person that may
+ * never come.
+ */
+ holdEventOps(teamId: number, distinctId: string, ops: EventOps, batchId: number): void {
+ if (ops.denied && ops.isIdentified === undefined && ops.lastSeenAtMs === undefined) {
+ return
+ }
+ const laneKey = heldLaneKey(teamId, distinctId)
+ this.referenceEntry(batchId, laneKey)
+ const existing = this.entries.get(laneKey)
+ if (!existing) {
+ this.entries.set(laneKey, {
+ teamId,
+ personId: '',
+ distinctId,
+ segments: [ops],
+ unresolved: true,
+ heldSince: Date.now(),
+ })
+ this.trackHeldLane(laneKey)
+ return
+ }
+ // Ops held into a lane a flush emptied are a new hold, resolved afresh: the owner a past flush found may
+ // have changed since. A lane mid-write keeps its owner for what follows its in-flight segments.
+ if (existing.segments.length === 0 && !existing.inFlight) {
+ existing.unresolved = true
+ existing.heldSince = Date.now()
+ existing.lastResolvedAt = undefined
+ this.trackHeldLane(laneKey)
+ }
+ this.appendSegment(existing, ops)
+ }
+
+ /** Records a new hold as the latest, then sheds the earliest-held lanes past the cap, counted. */
+ private trackHeldLane(laneKey: string): void {
+ this.heldLaneOrder.delete(laneKey)
+ this.heldLaneOrder.add(laneKey)
+ for (const oldest of this.heldLaneOrder) {
+ if (this.heldLaneOrder.size <= HELD_LANES_LIMIT) {
+ return
+ }
+ this.heldLaneOrder.delete(oldest)
+ const entry = this.entries.get(oldest)
+ // A key whose lane resolved or went since is only removed.
+ if (!entry?.unresolved || entry.segments.length === 0) {
+ continue
+ }
+ personhogStoreFlushCounter.inc({ outcome: 'held_dropped_limit' })
+ entry.segments.length = 0
+ if (!this.entryHeldByAnyBatch(oldest)) {
+ this.entries.delete(oldest)
+ }
+ }
+ }
+
+ /** Whether ops held for this distinct id are still unwritten; later ops for the id must queue behind them. */
+ hasHeldOps(teamId: number, distinctId: string): boolean {
+ return (this.entries.get(heldLaneKey(teamId, distinctId))?.segments.length ?? 0) > 0
+ }
+
+ /** A held lane still inside its window outlives the batch release and the shed. */
+ private heldLaneAlive(entry: OpsLaneEntry): boolean {
+ return entry.unresolved === true && Date.now() - (entry.heldSince ?? 0) < HELD_LANE_MAX_AGE_MS
+ }
+
/**
* Runs the identity service's merge saga. Any verdict purges local
* state for the merge's persons rather than repairing it; a call with
@@ -940,23 +1064,10 @@ export class PersonhogPersonsStore implements PersonsStore {
return [this.snapshot(updated), [], false]
}
- /**
- * The update fetch's two-step done once for the whole batch, so
- * per-event processing hits the cache. Best-effort.
- */
- async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
- const seen = new Set<string>()
- const unresolved = teamDistinctIds.filter((entry) => {
- const key = `${entry.teamId}:${entry.distinctId}:${entry.batchId}`
- if (seen.has(key)) {
- return false
- }
- seen.add(key)
- return this.getCachedPerson(entry.teamId, entry.distinctId, 'check') === undefined
- })
- if (unresolved.length === 0) {
- return
- }
+ /** Resolves and reads the batch's unresolved ids, caching what it finds. Never rejects. */
+ private async prefetchUnresolved(
+ unresolved: { teamId: number; distinctId: string; batchId: number }[]
+ ): Promise<void> {
const generations = new Map<number, number>()
for (const entry of unresolved) {
this.prefetchingBatches.add(entry.batchId)
@@ -1009,6 +1120,41 @@ export class PersonhogPersonsStore implements PersonsStore {
}
}
+ /**
+ * The update fetch's two-step done once for the whole batch, so
+ * per-event processing hits the cache. Best-effort. The pipeline does
+ * not await it, so reads of an id it covers wait for it instead of
+ * resolving the id alone.
+ */
+ async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
+ const seen = new Set<string>()
+ const unresolved = teamDistinctIds.filter((entry) => {
+ const key = `${entry.teamId}:${entry.distinctId}:${entry.batchId}`
+ if (seen.has(key)) {
+ return false
+ }
+ seen.add(key)
+ return this.getCachedPerson(entry.teamId, entry.distinctId, 'check') === undefined
+ })
+ if (unresolved.length === 0) {
+ return
+ }
+ const fetched = this.prefetchUnresolved(unresolved)
+ const distinctKeys = unresolved.map((entry) => `${entry.teamId}:${entry.distinctId}`)
+ for (const distinctKey of distinctKeys) {
+ this.pendingPrefetches.set(distinctKey, fetched)
+ }
+ try {
+ await fetched
+ } finally {
+ for (const distinctKey of distinctKeys) {
+ if (this.pendingPrefetches.get(distinctKey) === fetched) {
+ this.pendingPrefetches.delete(distinctKey)
+ }
+ }
+ }
+ }
+
/**
* Writes the batch's folded lanes to the leader, one call per segment;
* nothing publishes, because the leader's changelog is the person feed.
@@ -1065,12 +1211,19 @@ export class PersonhogPersonsStore implements PersonsStore {
}
private async writeEligibleLanes(pass: { deferrals: number }): Promise<void> {
+ // Before the claim, so a held lane that resolves writes in this pass.
+ await this.resolveHeldLanes()
// No await in this block, so the claim snapshot is atomic.
const captured: CapturedLane[] = []
for (const [personKey, entry] of this.entries) {
if (entry.segments.length === 0) {
continue
}
+ // A held lane still without an owner waits for a later flush;
+ // it is not a write the round loop should wait on.
+ if (entry.unresolved) {
+ continue
+ }
// Another writer holds the lane; the round loop waits it out.
if (entry.inFlight) {
pass.deferrals += 1
@@ -1097,7 +1250,12 @@ export class PersonhogPersonsStore implements PersonsStore {
entry.directWriteSettled = undefined
if (entry.segments.length > 0) {
// The settle is the last hand holding an abandoned entry.
- if (entry.abandoned && !this.entryHeldByAnyBatch(personKey) && this.entries.get(personKey) === entry) {
+ if (
+ entry.abandoned &&
+ !this.heldLaneAlive(entry) &&
+ !this.entryHeldByAnyBatch(personKey) &&
+ this.entries.get(personKey) === entry
+ ) {
personhogStoreShadowShedCounter.inc(entry.segments.length)
entry.segments.length = 0
this.entries.delete(personKey)
@@ -1130,6 +1288,10 @@ export class PersonhogPersonsStore implements PersonsStore {
personhogStoreFlushCounter.inc({ outcome: 'redirected' })
break
}
+ if (entry.heldSince !== undefined) {
+ await this.writeHeldSegments(entry, progress)
+ break
+ }
await this.writeSegments(entry, entry.personId, progress)
personhogStoreFlushCounter.inc({ outcome: 'success' })
break
@@ -1279,6 +1441,87 @@ export class PersonhogPersonsStore implements PersonsStore {
}
}
+ /**
+ * One identity call for every held lane due an answer, so a flush
+ * costs one request however many ids wait for an owner. A lane whose
+ * id has an owner becomes an ordinary lane for the write that follows;
+ * one nobody owns waits inside its window and drops after it, counted.
+ */
+ private async resolveHeldLanes(): Promise<void> {
+ const now = Date.now()
+ const due = [...this.entries.entries()].filter(
+ ([, entry]) =>
+ entry.unresolved === true &&
+ entry.segments.length > 0 &&
+ !entry.inFlight &&
+ (entry.lastResolvedAt === undefined ||
+ now - entry.lastResolvedAt >= HELD_RESOLVE_INTERVAL_MS ||
+ !this.heldLaneAlive(entry))
+ )
+ if (due.length === 0) {
+ return
+ }
+ let answers: Awaited<ReturnType<PersonHogPersonWriteRepository['resolvePersonsByDistinctIds']>>
+ try {
+ answers = await this.repository.resolvePersonsByDistinctIds(
+ due.map(([, entry]) => ({ teamId: entry.teamId, distinctId: entry.distinctId })),
+ CALLER_TAG
+ )
+ } catch (error) {
+ // The held lanes stay unresolved and ask again at the next flush; the lanes with an owner still write.
+ personhogStoreFlushCounter.inc({ outcome: 'held_resolve_failed' })
+ logger.warn('held lanes could not be resolved; they wait for the next flush', {
+ lanes: due.length,
+ error: String(error),
+ })
+ return
+ }
+ const ownerByKey = new Map(answers.map((answer) => [`${answer.teamId}:${answer.distinctId}`, answer.person]))
+ for (const [laneKey, entry] of due) {
+ entry.lastResolvedAt = now
+ const distinctKey = `${entry.teamId}:${entry.distinctId}`
+ const owner = ownerByKey.get(distinctKey)
+ if (owner == null) {
+ if (this.heldLaneAlive(entry)) {
+ personhogStoreFlushCounter.inc({ outcome: 'held_deferred' })
+ continue
+ }
+ personhogStoreFlushCounter.inc({ outcome: 'held_unowned' })
+ logger.warn('held ops dropped: the distinct id resolved to nobody for the whole hold window', {
+ team_id: entry.teamId,
+ distinct_id: entry.distinctId,
+ })
+ entry.segments.length = 0
+ this.heldLaneOrder.delete(laneKey)
+ if (!this.entryHeldByAnyBatch(laneKey)) {
+ this.entries.delete(laneKey)
+ }
+ continue
+ }
+ // A cached absence the resolve contradicts; the next read re-resolves.
+ if (this.resolutions.get(distinctKey) === null) {
+ this.resolutions.delete(distinctKey)
+ }
+ entry.personId = owner.id
+ entry.unresolved = false
+ this.heldLaneOrder.delete(laneKey)
+ }
+ }
+
+ /**
+ * The owner's projection cannot know a held lane's ops, so it is
+ * dropped after the write either way; an owner merged away since the
+ * resolve takes the redirect like any other lane.
+ */
+ private async writeHeldSegments(entry: OpsLaneEntry, progress: { remaining: number }): Promise<void> {
+ try {
+ await this.writeSegments(entry, entry.personId, progress)
+ personhogStoreFlushCounter.inc({ outcome: 'held_written' })
+ } finally {
+ this.clearPersonCacheForPersonId(`${entry.teamId}:${entry.personId}`, 'held_write')
+ }
+ }
+
/** An entry still holding unwritten ops outlives its last reference. */
releaseBatch(batchId: number): void {
// Any prefetch still on the wire answers into nothing from here on.
@@ -1313,6 +1556,11 @@ export class PersonhogPersonsStore implements PersonsStore {
continue
}
const entry = this.entries.get(personKey)
+ // A held lane waits out its window for an owner; the flush that
+ // outlives the window drops it.
+ if (entry && entry.segments.length > 0 && this.heldLaneAlive(entry)) {
+ continue
+ }
if (entry?.inFlight) {
// The flag hands the shed to the write's settle instead of
// zeroing segments under it.
@@ -1324,6 +1572,7 @@ export class PersonhogPersonsStore implements PersonsStore {
entry.segments.length = 0
}
this.entries.delete(personKey)
+ this.heldLaneOrder.delete(personKey)
}
this.releaseBatchId(batchId)
}
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 4c608bedb0e9..79cfad228b0e 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
@@ -6,6 +6,7 @@ import {
personhogStoreShadowComparedCounter,
personhogStoreShadowDivergenceCounter,
personhogStoreShadowErrorsCounter,
+ personhogStoreShadowMergeRedriveCounter,
personhogStoreShadowSkipsCounter,
} from '~/common/persons/metrics'
import { logger } from '~/common/utils/logger'
@@ -27,6 +28,7 @@ jest.mock('~/common/persons/metrics', () => ({
personhogStoreShadowComparedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowCompareFailedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowFoldRedriveCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personhogStoreShadowMergeRedriveCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowDurationSeconds: {
labels: jest.fn().mockReturnValue({ startTimer: jest.fn(() => mockShadowTimerStop) }),
},
@@ -94,7 +96,11 @@ describe('RoutingPersonsStore', () => {
// The personhog store implements PersonsStore, so the same
// compile-checked factory serves; the cast to the concrete class
// is the constructor's requirement, not an escape from checking.
- const personhogMock = Object.assign(mockStore(), { abandonBatch: jest.fn() })
+ const personhogMock = Object.assign(mockStore(), {
+ abandonBatch: jest.fn(),
+ holdEventOps: jest.fn(),
+ hasHeldOps: jest.fn().mockReturnValue(false),
+ })
const personhog = personhogMock as unknown as PersonhogPersonsStore
return { pg, personhogMock, personhog }
}
@@ -777,6 +783,89 @@ describe('RoutingPersonsStore', () => {
}
)
+ const createIn = (store: RoutingPersonsStore, isIdentified = false) =>
+ store.createPerson(
+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),
+ { plan: 'pro' },
+ {},
+ {},
+ 1,
+ null,
+ isIdentified,
+ 'caller-supplied-uuid',
+ { distinctId: 'd1' },
+ undefined,
+ undefined,
+ 0
+ )
+ const createdByPg = {
+ success: true,
+ person: person(1, '7'),
+ messages: [],
+ created: true,
+ } as never
+
+ 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) => {
+ const stores = makeStores()
+ stores.pg.createPerson.mockResolvedValue(createdByPg)
+ stores.personhogMock.createPerson.mockRejectedValue(failure)
+ const store = makeStore(stores, 'shadow')
+
+ const result = await createIn(store, isIdentified)
+
+ 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
+ )
+ }
+ })
+
+ it('a shadow createPerson that fails after the ceiling abandoned it holds nothing', 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))
+ )
+ const store = makeStore(stores, 'shadow')
+
+ 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)
+
+ expect(stores.personhogMock.holdEventOps).not.toHaveBeenCalled()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('mergePersons replays the same request against the personhog backend, pg staying authoritative', async () => {
const stores = makeStores()
const pgResult = { survivor: person(1, '7'), results: [] }
@@ -793,34 +882,58 @@ describe('RoutingPersonsStore', () => {
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 no-verdict failure that clears is retried under the same request', [noVerdict()], 2, null, false],
[
- 'a failure through every attempt is swallowed and counted',
+ 'a failure through every attempt is counted and re-driven at a flush',
[noVerdict(), noVerdict(), noVerdict()],
3,
'PersonMergeCallFailedError',
+ true,
],
[
- 'a deterministic refusal is counted without a retry',
+ 'a deterministic refusal is counted without a retry or a re-drive',
[new ConnectError('refused', Code.InvalidArgument)],
1,
'InvalidArgument',
+ false,
],
- ])('shadow merge: %s', async (_name, failures, expectedCalls, countedAs) => {
- const stores = makeStores()
- stores.pg.mergePersons.mockResolvedValue(emptyMergeResult())
- for (const failure of failures) {
- stores.personhogMock.mergePersons.mockRejectedValueOnce(failure)
- }
- const store = makeStore(stores, 'shadow')
- const request = mergeRequest() as never
+ ])('shadow merge: %s', async (_name, failures, expectedCalls, countedAs, redriven) => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ stores.pg.mergePersons.mockResolvedValue(emptyMergeResult())
+ stores.personhogMock.mergePersons.mockResolvedValue(emptyMergeResult())
+ for (const failure of failures) {
+ stores.personhogMock.mergePersons.mockRejectedValueOnce(failure)
+ }
+ const store = makeStore(stores, 'shadow')
+ const request = mergeRequest() as never
- await expect(store.mergePersons(request, 0)).resolves.toEqual(emptyMergeResult())
+ const merging = store.mergePersons(request, 0)
+ await jest.advanceTimersByTimeAsync(1_000)
+ await expect(merging).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 }])
+ 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 }])
+
+ // Past the re-drive delay, a flush re-drives only a merge that never got a verdict.
+ await jest.advanceTimersByTimeAsync(5_000)
+ const flushing = store.flush()
+ await jest.advanceTimersByTimeAsync(1_000)
+ await flushing
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls + (redriven ? 1 : 0))
+ if (redriven) {
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenCalledWith({ outcome: 'settled' })
+ } else {
+ expect(personhogStoreShadowMergeRedriveCounter.labels).not.toHaveBeenCalled()
+ }
+ } finally {
+ jest.useRealTimers()
+ }
})
it.each([
@@ -853,12 +966,210 @@ describe('RoutingPersonsStore', () => {
expect(personhogStoreShadowErrorsCounter.labels).not.toHaveBeenCalled()
})
- it('prefetch warms both worlds', async () => {
+ /** Unsettled through the first `unsettledCalls` calls, settled from then on; call `hangingCall` never answers. */
+ const unsettledUntil = (stores: ReturnType<typeof makeStores>, unsettledCalls: number, hangingCall = 0) => {
+ stores.pg.mergePersons.mockResolvedValue({
+ survivor: person(1, '1'),
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],
+ })
+ stores.personhogMock.mergePersons.mockImplementation(() => {
+ const call = stores.personhogMock.mergePersons.mock.calls.length
+ if (call === hangingCall) {
+ return new Promise<never>(() => {})
+ }
+ return Promise.resolve(
+ call <= unsettledCalls
+ ? {
+ survivor: person(1, '1'),
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict', settled: false }],
+ }
+ : {
+ survivor: person(1, '1'),
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],
+ }
+ )
+ })
+ }
+
+ /** A merge whose three attempts all come back unsettled, so the store defers it. */
+ const deferredMerge = async (store: RoutingPersonsStore, request: unknown) => {
+ const merging = store.mergePersons(request as never, 0)
+ await jest.advanceTimersByTimeAsync(1_000)
+ await merging
+ }
+
+ it.each([
+ ['settles at the first re-drive', 3, [4], ['settled'], 'settled'],
+ ['settles at a later re-drive', 6, [6, 7], ['deferred', 'settled'], 'settled'],
+ [
+ 'stays unsettled and is dropped once its window closes',
+ Infinity,
+ [6, 9, 12, 15, 18],
+ ['deferred', 'deferred', 'deferred', 'deferred', 'dropped'],
+ 'dropped',
+ ],
+ ])(
+ 'a shadow merge unsettled through its retries %s',
+ async (_name, unsettledAttempts, expectedCallsPerFlush, outcomes, finalOutcome) => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ unsettledUntil(stores, unsettledAttempts)
+ const store = makeStore(stores, 'shadow')
+ const request = mergeRequest() as never
+ await deferredMerge(store, request)
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)
+
+ // A flush inside the delay leaves the merge waiting.
+ await store.flush()
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)
+
+ for (const [index, expectedCalls] of expectedCallsPerFlush.entries()) {
+ // Past the delay each time, and the last re-drive lands inside the window with its next
+ // turn outside it, so the drop happens at that re-drive rather than at a later flush.
+ await jest.advanceTimersByTimeAsync(4_500)
+ const flushing = store.flush()
+ await jest.advanceTimersByTimeAsync(1_000)
+ await flushing
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(expectedCalls)
+ expect(stores.personhogMock.mergePersons).toHaveBeenLastCalledWith(request, 0)
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenNthCalledWith(index + 1, {
+ outcome: outcomes[index],
+ })
+ }
+ // Settled or dropped, the merge is gone from the next flush.
+ await jest.advanceTimersByTimeAsync(5_000)
+ await store.flush()
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(
+ expectedCallsPerFlush[expectedCallsPerFlush.length - 1]
+ )
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenLastCalledWith({
+ outcome: finalOutcome,
+ })
+ expect(personhogStoreShadowErrorsCounter.labels).not.toHaveBeenCalled()
+ } finally {
+ jest.useRealTimers()
+ }
+ }
+ )
+
+ it('the ceiling ends a re-drive loop and re-queues the merges it had not run', async () => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ // Two deferred merges; the first re-drive's call, the seventh, never answers.
+ unsettledUntil(stores, 6, 7)
+ const store = makeStore(stores, 'shadow')
+ await deferredMerge(store, mergeRequest())
+ await deferredMerge(store, mergeRequest())
+ await jest.advanceTimersByTimeAsync(5_000)
+
+ const flushing = store.flush()
+ await jest.advanceTimersByTimeAsync(60_000)
+ await flushing
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(7)
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenLastCalledWith({
+ outcome: 'abandoned',
+ })
+
+ // Both windows closed while the leg hung, so the next flush drops both rather than leaving them
+ // behind the call that never answered.
+ await store.flush()
+
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(7)
+ const outcomes = (personhogStoreShadowMergeRedriveCounter.labels as jest.Mock).mock.calls.map(
+ ([labels]) => labels.outcome
+ )
+ expect(outcomes.filter((outcome) => outcome === 'dropped')).toHaveLength(2)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('a flush re-drives a bounded number of deferred merges and the rest wait for the next', async () => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ const deferrals = 17
+ unsettledUntil(stores, deferrals * 3)
+ const store = makeStore(stores, 'shadow')
+ for (let i = 0; i < deferrals; i++) {
+ await deferredMerge(store, mergeRequest())
+ }
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(deferrals * 3)
+
+ await jest.advanceTimersByTimeAsync(5_000)
+ await store.flush()
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(deferrals * 3 + 16)
+ await store.flush()
+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(deferrals * 3 + 17)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('the store keeps a bounded number of deferred merges and drops the oldest past it', async () => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ unsettledUntil(stores, Infinity)
+ const store = makeStore(stores, 'shadow')
+ for (let i = 0; i < 1_000; i++) {
+ await deferredMerge(store, mergeRequest())
+ }
+ expect(personhogStoreShadowMergeRedriveCounter.labels).not.toHaveBeenCalled()
+
+ await deferredMerge(store, mergeRequest())
+
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenCalledTimes(1)
+ expect(personhogStoreShadowMergeRedriveCounter.labels).toHaveBeenCalledWith({ outcome: 'dropped' })
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('a flush runs the lanes before the deferred re-drives', async () => {
+ jest.useFakeTimers()
+ try {
+ const stores = makeStores()
+ stores.pg.mergePersons.mockResolvedValue({
+ survivor: person(1, '1'),
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],
+ })
+ stores.personhogMock.mergePersons.mockResolvedValue({
+ survivor: person(1, '1'),
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict', settled: false }],
+ })
+ const store = makeStore(stores, 'shadow')
+ const merging = store.mergePersons(mergeRequest() as never, 0)
+ await jest.advanceTimersByTimeAsync(1_000)
+ await merging
+ stores.personhogMock.mergePersons.mockClear()
+
+ await jest.advanceTimersByTimeAsync(5_000)
+ const flushing = store.flush()
+ await jest.advanceTimersByTimeAsync(1_000)
+ await flushing
+
+ expect(stores.personhogMock.flush.mock.invocationCallOrder[0]).toBeLessThan(
+ stores.personhogMock.mergePersons.mock.invocationCallOrder[0]
+ )
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('prefetch warms both worlds, starting the shadow one before the authoritative one finishes', async () => {
const stores = makeStores()
const store = makeStore(stores, 'shadow')
- await store.prefetchPersons([{ teamId: 1, distinctId: 'd', batchId: 0 }])
+ let finishPg: () => void = () => {}
+ stores.pg.prefetchPersons.mockReturnValueOnce(new Promise<void>((resolve) => (finishPg = resolve)))
+
+ const prefetching = store.prefetchPersons([{ teamId: 1, distinctId: 'd', batchId: 0 }])
expect(stores.pg.prefetchPersons).toHaveBeenCalled()
expect(stores.personhogMock.prefetchPersons).toHaveBeenCalled()
+ finishPg()
+ await prefetching
})
it('getFlushStats counts a batch once when both worlds reference it', () => {
@@ -902,7 +1213,7 @@ describe('RoutingPersonsStore', () => {
expect((shadowArgs[0] as InternalPerson).id).toBe('99')
})
- it('skips the shadow write, counted, when the person does not exist in the personhog backend', async () => {
+ it('holds the ops for a resolve at flush when the person does not exist in the personhog backend', async () => {
const stores = makeStores()
stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])
stores.personhogMock.fetchForUpdate.mockResolvedValue(null)
@@ -912,7 +1223,37 @@ describe('RoutingPersonsStore', () => {
expect(result.id).toBe('7')
expect(stores.personhogMock.applyEventOps).not.toHaveBeenCalled()
- expect(personhogStoreShadowSkipsCounter.labels).toHaveBeenCalledWith({ verb: 'applyEventOps' })
+ expect(stores.personhogMock.holdEventOps).toHaveBeenCalledWith(1, 'd1', ops, 0)
+ expect(personhogStoreShadowSkipsCounter.labels).not.toHaveBeenCalled()
+ })
+
+ it('holds the ops behind ops already held for the distinct id, without resolving the person', async () => {
+ const stores = makeStores()
+ stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])
+ stores.personhogMock.hasHeldOps.mockReturnValue(true)
+ stores.personhogMock.fetchForUpdate.mockResolvedValue(person(1, '99'))
+ const store = makeStore(stores, 'shadow')
+
+ await store.applyEventOps(person(1, '7'), ops, 'd1', 0)
+
+ expect(stores.personhogMock.hasHeldOps).toHaveBeenCalledWith(1, 'd1')
+ expect(stores.personhogMock.fetchForUpdate).not.toHaveBeenCalled()
+ expect(stores.personhogMock.applyEventOps).not.toHaveBeenCalled()
+ expect(stores.personhogMock.holdEventOps).toHaveBeenCalledWith(1, 'd1', ops, 0)
+ })
+
+ it('skips a direct diff update, counted, when the person does not exist in the personhog backend', async () => {
+ const stores = makeStores()
+ stores.pg.updatePersonWithPropertiesDiffForUpdate.mockResolvedValue([person(1, '7'), [], true])
+ stores.personhogMock.fetchForUpdate.mockResolvedValue(null)
+ const store = makeStore(stores, 'shadow')
+
+ await store.updatePersonWithPropertiesDiffForUpdate(person(1, '7'), { a: '1' }, [], {}, 'd1', 0)
+
+ expect(stores.personhogMock.updatePersonWithPropertiesDiffForUpdate).not.toHaveBeenCalled()
+ expect(personhogStoreShadowSkipsCounter.labels).toHaveBeenCalledWith({
+ verb: 'updatePersonWithPropertiesDiffForUpdate',
+ })
})
})
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
index d98d0a3c0a49..c5062102aff7 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
@@ -9,6 +9,7 @@ import {
personhogStoreShadowDurationSeconds,
personhogStoreShadowErrorsCounter,
personhogStoreShadowFoldRedriveCounter,
+ personhogStoreShadowMergeRedriveCounter,
personhogStoreShadowSkipsCounter,
} from '~/common/persons/metrics'
import { PersonMessage } from '~/common/persons/person-message'
@@ -20,7 +21,7 @@ import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-wri
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'
-import { PersonMergeUnsettledError } from './person-merge-types'
+import { PersonMergeCallFailedError, PersonMergeUnsettledError } from './person-merge-types'
import { EventOps } from './person-update'
import { CREATE_EVENT_NAME, PersonhogPersonsStore } from './personhog-persons-store'
import {
@@ -115,6 +116,18 @@ function stableEqual(left: unknown, right: unknown): boolean {
*/
const SHADOW_VERB_TIMEOUT_MS = 60_000
+/**
+ * A deferred shadow merge waits this long before a flush re-drives it, since the op holding its person usually
+ * completes within it, and stays in play for the identity service's execute timeout for that op.
+ */
+const SHADOW_MERGE_REDRIVE_DELAY_MS = 5_000
+const SHADOW_MERGE_REDRIVE_WINDOW_MS = 30_000
+/** Re-drives one flush runs, and deferred merges one store keeps; past them the oldest are dropped, counted. */
+const SHADOW_MERGE_REDRIVES_PER_FLUSH = 16
+const SHADOW_MERGE_DEFERRED_LIMIT = 1_000
+
+type DeferredShadowMerge = { request: MergePersonsRequest; batchId: number; notBefore: number; expiresAt: number }
+
/** Raised when a shadow verb outruns its ceiling and the batch abandons it. */
class ShadowVerbTimeoutError extends Error {
constructor(verb: string) {
@@ -271,18 +284,31 @@ export class RoutingPersonsStore implements PersonsStore {
/**
* The caller holds the Postgres row, whose numeric id means nothing
* here (independent sequences), so a shadow write re-resolves by
- * distinct id and skips, counted, when the person does not exist yet.
- * Memoized per batch.
+ * distinct id. A person that does not exist here yet is usually one
+ * another pod attached on the authoritative side while its shadow merge
+ * was still running, so a caller that can hold its ops for a resolve
+ * at flush does; the rest skip, counted. Memoized per batch.
*/
private async withShadowPerson(
verb: string,
teamId: number,
distinctId: string,
batchId: number,
- run: (person: InternalPerson) => Promise<unknown>
+ run: (person: InternalPerson) => Promise<unknown>,
+ hold?: () => void
): Promise<void> {
+ // Ops still held for this id were stated earlier, so later ops queue behind them, as the event's
+ // partition does when the authoritative store retries.
+ if (hold && this.personhog.hasHeldOps(teamId, distinctId)) {
+ hold()
+ return
+ }
const shadowPerson = await this.personhog.fetchForUpdate(teamId, distinctId, batchId)
if (shadowPerson === null) {
+ if (hold) {
+ hold()
+ return
+ }
personhogStoreShadowSkipsCounter.labels({ verb }).inc()
return
}
@@ -364,6 +390,30 @@ 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
+ ),
after: (authoritative, shadow, abandoned) =>
this.reconcileShadowCreate(
authoritative,
@@ -377,6 +427,43 @@ 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.
+ */
+ 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
+ )
+ }
+ throw error
+ }
+ }
+
/** Postgres created the person and personhog only found it: apply the creation properties set-once. */
private async reconcileShadowCreate(
authoritative: CreatePersonResult,
@@ -416,8 +503,13 @@ export class RoutingPersonsStore implements PersonsStore {
() => this.personhog.applyEventOps(person, ops, distinctId, batchId),
{
shadow: () =>
- this.withShadowPerson('applyEventOps', person.team_id, distinctId, batchId, (shadowPerson) =>
- this.personhog.applyEventOps(shadowPerson, ops, distinctId, batchId)
+ this.withShadowPerson(
+ 'applyEventOps',
+ person.team_id,
+ distinctId,
+ batchId,
+ (shadowPerson) => this.personhog.applyEventOps(shadowPerson, ops, distinctId, batchId),
+ () => this.personhog.holdEventOps(person.team_id, distinctId, ops, batchId)
),
}
)
@@ -497,11 +589,19 @@ export class RoutingPersonsStore implements PersonsStore {
)
}
- /** The merge service's retries wrap the routed call, which never throws for the shadow side. */
+ /** Shadow merges whose retries ended unsettled or without a verdict, re-driven at a flush once their delay has passed. */
+ private deferredShadowMerges: DeferredShadowMerge[] = []
+
+ /**
+ * The merge service's retries wrap the routed call, which never throws
+ * for the shadow side. A merge still unsettled or without a verdict
+ * after them is deferred to the flush, unless this is that re-drive.
+ */
private async retriedShadowMerge(
request: MergePersonsRequest,
batchId: number,
- abandoned: AbortSignal
+ abandoned: AbortSignal,
+ defer: boolean = true
): Promise<MergePersonsResult> {
let unsettled: MergePersonsResult | undefined
try {
@@ -527,12 +627,109 @@ export class RoutingPersonsStore implements PersonsStore {
)
} catch (error) {
if (error instanceof PersonMergeUnsettledError && unsettled !== undefined) {
+ if (defer) {
+ this.deferShadowMerge(request, batchId)
+ }
return unsettled
}
+ if (error instanceof PersonMergeCallFailedError && defer) {
+ this.deferShadowMerge(request, batchId)
+ }
throw error
}
}
+ private deferShadowMerge(request: MergePersonsRequest, batchId: number): void {
+ const now = Date.now()
+ this.deferredShadowMerges.push({
+ request,
+ batchId,
+ notBefore: now + SHADOW_MERGE_REDRIVE_DELAY_MS,
+ expiresAt: now + SHADOW_MERGE_REDRIVE_WINDOW_MS,
+ })
+ if (this.deferredShadowMerges.length > SHADOW_MERGE_DEFERRED_LIMIT) {
+ this.dropShadowMerge(this.deferredShadowMerges.shift()!, 'the store holds its limit')
+ }
+ }
+
+ private dropShadowMerge(entry: DeferredShadowMerge, reason: string): void {
+ personhogStoreShadowMergeRedriveCounter.labels({ outcome: 'dropped' }).inc()
+ logger.warn('shadow merge dropped unsettled', {
+ team_id: entry.request.teamId,
+ target_distinct_id: entry.request.targetDistinctId,
+ sources: entry.request.sources.map((source) => source.distinctId),
+ reason,
+ })
+ }
+
+ private requeueAbandonedShadowMerges(entries: DeferredShadowMerge[]): void {
+ personhogStoreShadowMergeRedriveCounter.labels({ outcome: 'abandoned' }).inc(entries.length)
+ this.deferredShadowMerges.push(...entries)
+ }
+
+ /** Rejects when the ceiling abandons the leg, so a loop can stop waiting on a call it cannot cancel. */
+ private abandonment(abandoned: AbortSignal): Promise<never> {
+ return new Promise((_resolve, reject) =>
+ abandoned.addEventListener('abort', () => reject(new ShadowVerbTimeoutError('mergePersons')), {
+ once: true,
+ })
+ )
+ }
+
+ /**
+ * The identity service refuses a merge as a conflict while another op
+ * holds one of its persons, and a re-drive run too soon lands inside
+ * the same hold. A deferred merge runs at the first flush past its
+ * delay and is dropped once its window closes; one the ceiling
+ * abandons is re-queued, counted, and a flush runs a bounded number of
+ * them after the lanes.
+ */
+ private async redriveDeferredShadowMerges(abandoned: AbortSignal): Promise<void> {
+ const now = Date.now()
+ for (const entry of this.deferredShadowMerges.filter((entry) => entry.expiresAt <= now)) {
+ this.dropShadowMerge(entry, 'its window closed')
+ }
+ const live = this.deferredShadowMerges.filter((entry) => entry.expiresAt > now)
+ const due = live.filter((entry) => entry.notBefore <= now).slice(0, SHADOW_MERGE_REDRIVES_PER_FLUSH)
+ this.deferredShadowMerges = live.filter((entry) => !due.includes(entry))
+ if (due.length === 0) {
+ return
+ }
+ // One abort listener for the whole loop; the catch keeps it handled if no race is waiting when it fires.
+ const legAbandoned = this.abandonment(abandoned)
+ void legAbandoned.catch(() => {})
+ for (const [index, entry] of due.entries()) {
+ if (abandoned.aborted) {
+ this.requeueAbandonedShadowMerges(due.slice(index))
+ return
+ }
+ let settled = false
+ // The call itself cannot be cancelled, so the loop stops waiting for it at the ceiling and the entry
+ // keeps its turn; a flush's re-drives never outlive its leg.
+ const attempt = this.retriedShadowMerge(entry.request, entry.batchId, abandoned, false)
+ void attempt.catch(() => {})
+ try {
+ const result = await Promise.race([attempt, legAbandoned])
+ settled = result.results.every((source) => source.settled !== false)
+ } catch (error) {
+ if (abandoned.aborted) {
+ this.requeueAbandonedShadowMerges(due.slice(index))
+ return
+ }
+ this.recordShadowFailure('mergePersons', error)
+ }
+ const notBefore = Date.now() + SHADOW_MERGE_REDRIVE_DELAY_MS
+ if (settled) {
+ personhogStoreShadowMergeRedriveCounter.labels({ outcome: 'settled' }).inc()
+ } else if (notBefore >= entry.expiresAt) {
+ this.dropShadowMerge(entry, 'its window closed')
+ } else {
+ personhogStoreShadowMergeRedriveCounter.labels({ outcome: 'deferred' }).inc()
+ this.deferredShadowMerges.push({ ...entry, notBefore })
+ }
+ }
+ }
+
/** A fold is never retried as a fold: one that throws aborts, and its pairs take the re-drive. */
private async shadowMerge(
request: MergePersonsRequest,
@@ -681,11 +878,13 @@ export class RoutingPersonsStore implements PersonsStore {
}
prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
- return this.route(
- 'prefetchPersons',
- () => this.pg.prefetchPersons(teamDistinctIds),
- () => this.personhog.prefetchPersons(teamDistinctIds)
- )
+ if (this.mode === 'personhog') {
+ return this.personhog.prefetchPersons(teamDistinctIds)
+ }
+ // Both start now: the pipeline does not await the prefetch, so a shadow prefetch started after the
+ // authoritative one finishes would lose the race with the batch's own reads.
+ const shadow = this.shadowed('prefetchPersons', () => this.personhog.prefetchPersons(teamDistinctIds))
+ return Promise.all([this.pg.prefetchPersons(teamDistinctIds), shadow]).then(() => undefined)
}
getFlushStats(): BatchWritingStoreFlushStats {
@@ -705,7 +904,15 @@ export class RoutingPersonsStore implements PersonsStore {
return this.route(
'flush',
() => this.pg.flush(),
- () => this.personhog.flush()
+ () => this.personhog.flush(),
+ {
+ shadow: async (abandoned) => {
+ // The lanes first; the re-drives take what is left of the ceiling.
+ const flushed = await this.personhog.flush()
+ await this.redriveDeferredShadowMerges(abandoned)
+ return flushed
+ },
+ }
)
}
@@ -736,6 +943,15 @@ export class RoutingPersonsStore implements PersonsStore {
// The store's unwritten-lanes rejection is the right alarm
// only when it owns the data; a shadow-only fault must not
// stop shutdown.
+ if (this.deferredShadowMerges.length > 0) {
+ personhogStoreShadowMergeRedriveCounter
+ .labels({ outcome: 'dropped' })
+ .inc(this.deferredShadowMerges.length)
+ logger.warn('shadow merges dropped unsettled at shutdown', {
+ count: this.deferredShadowMerges.length,
+ })
+ this.deferredShadowMerges = []
+ }
await this.shadowed('shutdown', () => this.personhog.shutdown())
}
}