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.

feat(personhog): route ingestion person writes by store mode (#81624)

Zach Brown19428389cc1a
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 1c5a0f49c35f..281db4378fce 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -113,6 +113,15 @@ export type CommonConfig = BaseServerConfig & {
// PersonHog gRPC
PERSONHOG_ENABLED: boolean
+ /**
+ * Which world the ingestion persons store writes: 'pg' (default),
+ * 'personhog', or 'shadow' (pg authoritative, personhog best-effort).
+ * Until the merge saga lands, merge events fail loudly in personhog
+ * mode, so it is only safe for traffic that produces none.
+ */
+ PERSONS_STORE_MODE: string
+ /** Host and port of the personhog identity server. */
+ PERSONHOG_IDENTITY_ADDR: string
PERSONHOG_ADDR: string
PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE: number
PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS: string
@@ -294,6 +303,8 @@ export function getDefaultCommonConfig(): CommonConfig {
// PersonHog gRPC
PERSONHOG_ENABLED: false,
PERSONHOG_ADDR: '',
+ PERSONS_STORE_MODE: 'pg',
+ PERSONHOG_IDENTITY_ADDR: '',
PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE: 0,
PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS: '',
PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE: 0,
diff --git a/nodejs/src/common/personhog/client.test.ts b/nodejs/src/common/personhog/client.test.ts
index 114f1fde3767..445399d8ea56 100644
--- a/nodejs/src/common/personhog/client.test.ts
+++ b/nodejs/src/common/personhog/client.test.ts
@@ -25,6 +25,7 @@ import {
PersonHogClient,
parseRolloutTeamIds,
resolveConsistencyHeader,
+ resolvePersonRoutingKey,
shouldUseGrpcForTeam,
shouldUseGrpcForTeamItems,
shouldUseGrpcForTeams,
@@ -262,6 +263,28 @@ describe('resolveConsistencyHeader', () => {
})
})
+describe('resolvePersonRoutingKey', () => {
+ const routingKey = { teamId: 7n, personId: 42n }
+
+ it.each([
+ ['UpdatePersonProperties', ConsistencyLevel.UNSPECIFIED],
+ ['FencePerson', ConsistencyLevel.UNSPECIFIED],
+ ['ReleaseFence', ConsistencyLevel.UNSPECIFIED],
+ ['FoldPersonDocument', ConsistencyLevel.UNSPECIFIED],
+ ['GetPerson', ConsistencyLevel.STRONG],
+ ])('returns the key for leader-bound %s', (method, consistency) => {
+ expect(resolvePersonRoutingKey(method, { ...routingKey, readOptions: { consistency } })).toEqual(routingKey)
+ })
+
+ it.each([
+ ['GetPerson', ConsistencyLevel.EVENTUAL],
+ ['GetPersons', ConsistencyLevel.STRONG],
+ ['GetPersonsByDistinctIds', ConsistencyLevel.UNSPECIFIED],
+ ])('returns null for replica-bound %s', (method, consistency) => {
+ expect(resolvePersonRoutingKey(method, { ...routingKey, readOptions: { consistency } })).toBeNull()
+ })
+})
+
describe('PersonHogClient', () => {
describe('groups', () => {
describe('fetchGroup', () => {
diff --git a/nodejs/src/common/personhog/client.ts b/nodejs/src/common/personhog/client.ts
index a255a8a090c3..a616e3390786 100644
--- a/nodejs/src/common/personhog/client.ts
+++ b/nodejs/src/common/personhog/client.ts
@@ -116,6 +116,31 @@ export function resolveConsistencyHeader(message: unknown): 'strong' | 'eventual
return readOptions?.consistency === ConsistencyLevel.STRONG ? 'strong' : 'eventual'
}
+/** Methods the router always forwards to the owning partition's leader. */
+const LEADER_ROUTED_METHODS = new Set(['UpdatePersonProperties', 'FencePerson', 'ReleaseFence', 'FoldPersonDocument'])
+
+/**
+ * The person routing key for a leader-bound call, or null when the call is
+ * replica-bound. The router hashes this key out of the request headers and
+ * never decodes the body, so a leader-bound call that omits it is rejected
+ * with InvalidArgument rather than routed. Replica-bound reads must travel
+ * without the key, which is why `GetPerson` carries it only under strong
+ * consistency, the one case the router sends to a leader.
+ */
+export function resolvePersonRoutingKey(
+ methodName: string,
+ message: unknown
+): { teamId: bigint; personId: bigint } | null {
+ const leaderBound =
+ LEADER_ROUTED_METHODS.has(methodName) ||
+ (methodName === 'GetPerson' && resolveConsistencyHeader(message) === 'strong')
+ if (!leaderBound) {
+ return null
+ }
+ const { teamId, personId } = message as { teamId: bigint; personId: bigint }
+ return { teamId, personId }
+}
+
export interface PersonHogClientConfig {
/** Host and port of the personhog gRPC server, e.g. "localhost:50051". */
addr: string
@@ -194,6 +219,27 @@ export class PersonHogClient {
}
static fromConfig(config: PersonHogClientConfig): PersonHogClient {
+ const { transport, stateMonitor } = createPersonhogTransport(config)
+ return new PersonHogClient(transport, stateMonitor)
+ }
+
+ close(): void {
+ this.stateMonitor?.close()
+ }
+}
+
+/**
+ * The transport every personhog gRPC client shares: caller headers,
+ * consistency and routing-key stamping, and an HTTP/2 session kept alive
+ * and monitored.
+ * The identity server's clients build on it too, so the wire behavior
+ * cannot drift between endpoints.
+ */
+export function createPersonhogTransport(config: PersonHogClientConfig): {
+ transport: Transport
+ stateMonitor: SessionStateMonitor
+} {
+ {
const scheme = config.useTls ? 'https' : 'http'
const interceptors: Interceptor[] = []
if (config.clientName) {
@@ -216,6 +262,14 @@ export class PersonHogClient {
req.header.set('x-read-consistency', resolveConsistencyHeader(req.message))
return await next(req)
})
+ interceptors.push((next) => async (req) => {
+ const routingKey = resolvePersonRoutingKey(req.method.name, req.message)
+ if (routingKey) {
+ req.header.set('x-team-id', routingKey.teamId.toString())
+ req.header.set('x-person-id', routingKey.personId.toString())
+ }
+ return await next(req)
+ })
const sessionManager = new Http2SessionManager(`${scheme}://${config.addr}`, {
pingIntervalMs: config.pingIntervalMs ?? 30_000,
@@ -238,10 +292,6 @@ export class PersonHogClient {
sessionManager: stateMonitor,
interceptors,
})
- return new PersonHogClient(transport, stateMonitor)
- }
-
- close(): void {
- this.stateMonitor?.close()
+ return { transport, stateMonitor }
}
}
diff --git a/nodejs/src/common/personhog/identity-clients.ts b/nodejs/src/common/personhog/identity-clients.ts
new file mode 100644
index 000000000000..afeaa26578a7
--- /dev/null
+++ b/nodejs/src/common/personhog/identity-clients.ts
@@ -0,0 +1,22 @@
+import { createClient } from '@connectrpc/connect'
+
+import { PersonHogIdentity } from '~/common/generated/personhog/personhog/identity/v1/identity_pb'
+
+import { PersonHogClientConfig, createPersonhogTransport } from './client'
+import { PersonhogIdentityOperations } from './identity'
+
+/**
+ * Client for the identity server; a separate factory from
+ * PersonHogClient because it answers on a different address than the
+ * router.
+ */
+export function createIdentityClients(config: PersonHogClientConfig): {
+ identity: PersonhogIdentityOperations
+ close: () => void
+} {
+ const { transport, stateMonitor } = createPersonhogTransport(config)
+ return {
+ identity: new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport)),
+ close: () => stateMonitor.close(),
+ }
+}
diff --git a/nodejs/src/common/personhog/index.ts b/nodejs/src/common/personhog/index.ts
index 3c7e69849f92..9ce5fd3f3db0 100644
--- a/nodejs/src/common/personhog/index.ts
+++ b/nodejs/src/common/personhog/index.ts
@@ -17,6 +17,8 @@ export type PersonHogConfig = Pick<
CommonConfig,
| 'PERSONHOG_ENABLED'
| 'PERSONHOG_ADDR'
+ | 'PERSONHOG_IDENTITY_ADDR'
+ | 'PERSONS_STORE_MODE'
| 'PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE'
| 'PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS'
| 'PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE'
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index f6d4b11aa622..bb115e911864 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -160,6 +160,18 @@ export function observeLatencyByVersion(person: InternalPerson | undefined, star
personOperationLatencyByVersionSummary.labels(operation, versionBucket).observe(performance.now() - start)
}
+export const personhogStoreShadowSkipsCounter = new Counter({
+ name: 'personhog_store_shadow_skips_total',
+ help: 'Shadowed writes skipped because the person does not exist in the personhog world yet',
+ labelNames: ['verb'],
+})
+
+export const personhogStoreShadowErrorsCounter = new Counter({
+ name: 'personhog_store_shadow_errors_total',
+ help: 'Personhog shadow-side store verb failures by verb; shadow errors never fail the batch',
+ labelNames: ['verb'],
+})
+
export const personProfileUpdateOutcomeCounter = new Counter({
name: 'person_profile_update_outcome_total',
help: 'Outcome of person profile update operations at event level',
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 1e0261e65cba..a39ee01ae907 100644
--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
@@ -226,9 +226,9 @@ describe('PersonhogPersonsStore', () => {
expect(fetched?.id).toBe('7')
})
- it('deletes have no personhog path and fail loudly', () => {
+ it('deletes have no personhog path and fail loudly', async () => {
const bound = store.forBatch(0)
- expect(() => bound.deletePerson(person, 'd1')).toThrow('no personhog RPC')
+ await expect(bound.deletePerson(person, 'd1')).rejects.toThrow('no personhog RPC')
})
it('creation resolves through identity and memoizes every distinct id it mapped', async () => {
@@ -280,6 +280,79 @@ describe('PersonhogPersonsStore', () => {
await expect(bound.flush()).rejects.toThrow('leader unreachable')
})
+ describe('concurrent batches share one flush', () => {
+ const personB: () => InternalPerson = () => ({ ...person, id: '8', uuid: 'person-uuid-8' })
+
+ it("a sibling entry's failure leaves it in its lane for the next pass", async () => {
+ const bound0 = store.forBatch(0)
+ const bound1 = store.forBatch(1)
+ await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')
+ await bound1.applyEventOps(personB(), ops({ $set: { b: '2' } }), 'd2')
+
+ repository.updatePersonProperties.mockImplementation((request) =>
+ request.personId === '8'
+ ? Promise.reject(new Error('leader unreachable'))
+ : Promise.resolve({ person: { ...person, version: 2 }, updated: true })
+ )
+ await expect(store.flush()).rejects.toThrow('leader unreachable')
+
+ repository.updatePersonProperties.mockClear()
+ repository.updatePersonProperties.mockResolvedValue({ person: { ...person, version: 2 }, updated: true })
+ await store.flush()
+ // Only the failed entry survives to re-ship; the succeeded
+ // one was consumed by the first pass.
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ expect(repository.updatePersonProperties.mock.calls[0][0].personId).toBe('8')
+ })
+
+ it('flush passes serialize, so ops folded mid-pass ship strictly after it', async () => {
+ let releaseFirst!: () => void
+ const firstGate = new Promise<void>((resolve) => {
+ releaseFirst = resolve
+ })
+ const callOrder: string[] = []
+ repository.updatePersonProperties
+ .mockImplementationOnce(async () => {
+ callOrder.push('first:start')
+ await firstGate
+ callOrder.push('first:end')
+ return { person: { ...person, version: 2 }, updated: true }
+ })
+ .mockImplementation(() => {
+ callOrder.push('second')
+ return Promise.resolve({ person: { ...person, version: 3 }, updated: true })
+ })
+
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')
+ const firstFlush = store.flush()
+ // Spin microtasks until the first pass is mid-ship, blocked
+ // on the gate, so the next fold genuinely lands mid-pass.
+ for (let i = 0; i < 100 && !callOrder.includes('first:start'); i++) {
+ await Promise.resolve()
+ }
+ await bound.applyEventOps(person, ops({ $set: { a: '2' } }), 'd1')
+ const secondFlush = store.flush()
+ releaseFirst()
+ await Promise.all([firstFlush, secondFlush])
+
+ expect(callOrder).toEqual(['first:start', 'first:end', 'second'])
+ })
+
+ it('a no-change lane ships anyway when a sibling batch holds ops for the person', async () => {
+ person.properties = { $browser: 'Firefox' }
+ const bound0 = store.forBatch(0)
+ const bound1 = store.forBatch(1)
+ // Batch 0 folds a filtered-only no-change; batch 1 holds real
+ // ops for the same person, so batch 0's verdict may be stale
+ // and the leader judges it instead.
+ await bound0.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, 'pageview'), 'd1')
+ await bound1.applyEventOps(person, ops({ $set: { plan: 'pro' } }, 'pageview'), 'd1')
+ await store.flush()
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(2)
+ })
+ })
+
it('publishes nothing when the leader reports no change', async () => {
repository.updatePersonProperties.mockResolvedValue({ person, updated: false })
const bound = store.forBatch(0)
@@ -361,13 +434,9 @@ describe('PersonhogPersonsStore', () => {
expect(results).toEqual([])
})
- it('runs transactions as a passthrough over the store itself', async () => {
+ it('has no transactions of its own; the routing store owns them', async () => {
const bound = store.forBatch(0)
- const result = await bound.inTransaction('test', (tx) => {
- expect(tx).toBe(bound)
- return Promise.resolve('done')
- })
- expect(result).toBe('done')
+ await expect(bound.inTransaction('test', () => Promise.resolve('done'))).rejects.toThrow('no personhog RPC')
})
it.each([
@@ -390,9 +459,9 @@ describe('PersonhogPersonsStore', () => {
(b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>
b.moveDistinctIdsFromPersons([p], p, 'd1', undefined as any),
],
- ])('%s fails loudly while the leader RPC is pending', (_method, call) => {
+ ])('%s fails loudly while the leader RPC is pending', async (_method, call) => {
const bound = store.forBatch(0)
- expect(() => call(bound, person)).toThrow(PersonhogPendingRpcError)
+ await expect(call(bound, person)).rejects.toThrow(PersonhogPendingRpcError)
})
it('maps a direct diff update onto the folded RPC', async () => {
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
index bd48697e3a95..d09b3be7a370 100644
--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
@@ -10,12 +10,14 @@ import { PersonRepositoryTransaction } from '~/common/persons/repositories/perso
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { logger } from '~/common/utils/logger'
import { NoRowsUpdatedError } from '~/common/utils/utils'
+import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
import { EventOps, applyEventPropertyUpdates, computeOpsScalarUpdates, foldOps, refineEventOps } from './person-update'
-import { FlushResult } from './persons-store'
-import { PersonsStoreForBatch, PersonsStoreTransactionForBatch } from './persons-store-for-batch'
+import { FlushResult, PersonsStore } from './persons-store'
+import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'
+import { PersonsStoreTransaction } from './persons-store-transaction'
export const personhogStoreFlushCounter = new Counter({
name: 'personhog_store_flush_ops_total',
@@ -103,7 +105,7 @@ interface OpsLaneEntry {
* identity service; the uuid argument to createPerson is advisory and
* the returned person carries the authoritative one.
*/
-export class PersonhogPersonsStore {
+export class PersonhogPersonsStore implements PersonsStore {
private options: PersonhogPersonsStoreOptions
/** Folded ops per batch, keyed by `${teamId}:${personId}`. */
private lanes: Map<number, Map<string, OpsLaneEntry>> = new Map()
@@ -121,6 +123,8 @@ export class PersonhogPersonsStore {
* service state.
*/
private personState: Map<number, Map<string, InternalPerson>> = new Map()
+ /** Serializes flush passes; see flush(). */
+ private flushChain: Promise<void> = Promise.resolve()
constructor(
private repository: PersonHogPersonWriteRepository,
@@ -130,7 +134,7 @@ export class PersonhogPersonsStore {
}
forBatch(batchId: number): PersonsStoreForBatch {
- return new BatchBoundPersonhogStore(this, batchId)
+ return new BatchBoundPersonsStore(this, batchId)
}
/**
@@ -258,6 +262,7 @@ export class PersonhogPersonsStore {
_uuid: string,
primaryDistinctId: { distinctId: string; version?: number },
extraDistinctIds: { distinctId: string; version?: number }[] | undefined,
+ _tx: PersonRepositoryTransaction | undefined,
batchId: number
): Promise<CreatePersonResult> {
const { person, created } = await this.repository.getOrCreatePersonByDistinctId(
@@ -348,12 +353,137 @@ export class PersonhogPersonsStore {
// the shadow gates merge events off this store; once merges move to
// personhog, the merge saga owns those deletions end to end, so no
// store-level delete path will ever be needed here.
- deletePersons(_persons: InternalPerson[], _distinctId: string, _batchId?: number): Promise<PersonMessage[]> {
- throw new PersonhogPendingRpcError('deletePersons', 'merge saga')
+ /**
+ * The personhog world has no Postgres transactions; transaction
+ * semantics for routed deployments live in the routing store, which
+ * never delegates this member. Reaching it is a wiring bug.
+ */
+ inTransaction<T>(_description: string, _transaction: (tx: PersonsStoreTransaction) => Promise<T>): Promise<T> {
+ return Promise.reject(new PersonhogPendingRpcError('inTransaction', 'merge saga'))
+ }
+
+ // Merge execution is the merge saga's once it lands; until then every
+ // mutation in the family is a loud placeholder.
+
+ updatePersonForMerge(
+ _person: InternalPerson,
+ _update: Partial<InternalPerson>,
+ _distinctId: string,
+ _batchId: number,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ return Promise.reject(new PersonhogPendingRpcError('updatePersonForMerge', 'merge saga'))
+ }
+
+ claimLifecycleMarks(
+ _opId: string,
+ _teamId: number,
+ _persons: LifecycleMarkPerson[],
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return Promise.reject(new PersonhogPendingRpcError('claimLifecycleMarks', 'merge saga'))
+ }
+
+ releaseLifecycleMarks(
+ _opId: string,
+ _teamId: number,
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return Promise.reject(new PersonhogPendingRpcError('releaseLifecycleMarks', 'merge saga'))
+ }
+
+ isPersonLive(_person: InternalPerson, _distinctId: string, _tx?: PersonRepositoryTransaction): Promise<boolean> {
+ return Promise.reject(new PersonhogPendingRpcError('isPersonLive', 'merge saga'))
+ }
+
+ addDistinctId(
+ _person: InternalPerson,
+ _distinctId: string,
+ _version: number,
+ _tx: PersonRepositoryTransaction | undefined,
+ _batchId: number
+ ): Promise<PersonMessage[]> {
+ return Promise.reject(new PersonhogPendingRpcError('addDistinctId', 'merge saga'))
}
- deletePerson(_person: InternalPerson, _distinctId: string, _batchId?: number): Promise<PersonMessage[]> {
- throw new PersonhogPendingRpcError('deletePerson', 'merge saga')
+ moveDistinctIds(
+ _source: InternalPerson,
+ _target: InternalPerson,
+ _distinctId: string,
+ _limit: number | undefined,
+ _tx: PersonRepositoryTransaction,
+ _batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ return Promise.reject(new PersonhogPendingRpcError('moveDistinctIds', 'merge saga'))
+ }
+
+ moveDistinctIdsFromPersons(
+ _sources: InternalPerson[],
+ _target: InternalPerson,
+ _distinctId: string,
+ _tx: PersonRepositoryTransaction,
+ _batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ return Promise.reject(new PersonhogPendingRpcError('moveDistinctIdsFromPersons', 'merge saga'))
+ }
+
+ // Postgres bookkeeping with nothing to answer in this world: shadow
+ // teams are fresh, so no cohort rows or hash-key overrides exist to
+ // fix up.
+
+ updateCohortsAndFeatureFlagsForMerge(
+ _teamID: Team['id'],
+ _sourcePersonID: InternalPerson['id'],
+ _targetPersonID: InternalPerson['id'],
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return Promise.resolve()
+ }
+
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ _teamID: Team['id'],
+ _sourcePersonIDs: InternalPerson['id'][],
+ _targetPersonID: InternalPerson['id'],
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return Promise.resolve()
+ }
+
+ /** The leader enforces the size ceiling at admission; there is nothing to measure here. */
+ personPropertiesSize(_personId: string, _teamId: number): Promise<number> {
+ return Promise.resolve(0)
+ }
+
+ getFlushStats(): BatchWritingStoreFlushStats {
+ let dirtyEntryCount = 0
+ for (const lane of this.lanes.values()) {
+ dirtyEntryCount += lane.size
+ }
+ let cacheEntryCount = 0
+ for (const memo of this.personState.values()) {
+ cacheEntryCount += memo.size
+ }
+ return { dirtyEntryCount, referencedBatchCount: this.lanes.size, cacheEntryCount }
+ }
+
+ deletePersons(
+ _persons: InternalPerson[],
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ return Promise.reject(new PersonhogPendingRpcError('deletePersons', 'merge saga'))
+ }
+
+ deletePerson(
+ _person: InternalPerson,
+ _distinctId: string,
+ _tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ return Promise.reject(new PersonhogPendingRpcError('deletePerson', 'merge saga'))
}
/**
@@ -369,7 +499,9 @@ export class PersonhogPersonsStore {
propertiesToUnset: string[],
otherUpdates: Partial<InternalPerson>,
_distinctId: string,
- _forceUpdate?: boolean
+ _batchId: number,
+ _forceUpdate?: boolean,
+ _tx?: PersonRepositoryTransaction
): Promise<[InternalPerson, PersonMessage[], boolean]> {
const unsupported = Object.keys(otherUpdates).filter((key) => key !== 'is_identified' && key !== 'last_seen_at')
if (unsupported.length > 0) {
@@ -407,13 +539,20 @@ export class PersonhogPersonsStore {
*/
async countDistinctIdsForPersons(
teamId: Team['id'],
- personIds: InternalPerson['id'][]
+ personIds: InternalPerson['id'][],
+ _distinctId: string,
+ _tx: PersonRepositoryTransaction
): Promise<Map<string, number>> {
const byPerson = await this.repository.getDistinctIdsForPersons(teamId, personIds, undefined, CALLER_TAG)
return new Map(personIds.map((id) => [id, byPerson[id]?.length ?? 0]))
}
- async fetchPersonDistinctIds(person: InternalPerson, limit?: number): Promise<string[]> {
+ async fetchPersonDistinctIds(
+ person: InternalPerson,
+ _distinctId: string,
+ limit: number | undefined,
+ _tx: PersonRepositoryTransaction
+ ): Promise<string[]> {
const byPerson = await this.repository.getDistinctIdsForPersons(person.team_id, [person.id], limit, CALLER_TAG)
return byPerson[person.id] ?? []
}
@@ -473,7 +612,7 @@ export class PersonhogPersonsStore {
}
/**
- * Ships the batch's folded lanes to the leader, one entry per
+ * Ships every batch's folded lanes to the leader, one entry per
* person, segments in order. There is deliberately no Postgres
* fallback. A missing person (deleted or merged mid-batch) and the
* leader's size rejection are counted and skipped, since neither can
@@ -482,82 +621,142 @@ export class PersonhogPersonsStore {
* response's no-change flag: a retried call whose lost first attempt
* landed replays into the leader's no-change fast path, and the
* version still tells the truth. Any other failure fails the flush
- * so the batch retries whole; lanes are batch-scoped, so one batch's
- * failure never discards a sibling's shipped results.
+ * so the batch retries whole.
+ *
+ * Passes serialize, one at a time, with later calls queueing behind
+ * the running one. A pass claims a synchronous snapshot of every
+ * lane before shipping, so ops folded mid-pass land in fresh entries
+ * and ship on the next pass, never into an entry already in flight.
+ * A failed ship restores its entry, ahead of anything folded since:
+ * the failing flush call fails its own batch, but the entry may
+ * belong to a sibling batch that never acked its events, and folds
+ * are idempotent, so re-shipping on a later pass is safe.
*
- * A lane with no update-worthy change — every refined change
+ * A lane entry with no update-worthy change — every refined change
* filtered, nothing forced, no scalar movement — is suppressed here
* rather than shipped, the same no-op classification the Postgres
- * store applies at its flush. The leader never sees the noise.
+ * store applies at its flush. The exception is a person a sibling
+ * batch also holds ops for: the no-change verdict was judged against
+ * this batch's own baseline, so the entry ships instead and the
+ * leader's refinement no-ops it if it truly is one.
*/
- async flush(batchId: number): Promise<FlushResult[]> {
- const lane = this.lanes.get(batchId)
- if (!lane) {
- return []
+ async flush(): Promise<FlushResult[]> {
+ const run = this.flushChain.then(() => this.flushPass())
+ this.flushChain = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ private async flushPass(): Promise<FlushResult[]> {
+ const captured: { batchId: number; personKey: string; entry: OpsLaneEntry }[] = []
+ for (const [batchId, lane] of this.lanes) {
+ for (const [personKey, entry] of lane) {
+ captured.push({ batchId, personKey, entry })
+ }
+ }
+ // One entry per person per lane, so the number of captured
+ // entries for a person is the number of batches holding it.
+ const entriesPerPerson = new Map<string, number>()
+ for (const { personKey } of captured) {
+ entriesPerPerson.set(personKey, (entriesPerPerson.get(personKey) ?? 0) + 1)
+ }
+ for (const { batchId, personKey } of captured) {
+ this.lanes.get(batchId)?.delete(personKey)
}
- this.lanes.delete(batchId)
const limit = pLimit(this.options.maxConcurrentUpdates)
- const entries = [...lane.values()]
-
- const results = await Promise.all(
- entries.map((entry) =>
- limit(async (): Promise<FlushResult[]> => {
- if (!entry.triggersUpdate) {
- personhogStoreFlushCounter.inc({ outcome: 'filtered' })
- return []
- }
- let finalPerson: InternalPerson | null = null
- try {
- for (const ops of entry.segments) {
- const { person } = await this.repository.updatePersonProperties(
- {
- teamId: entry.teamId,
- personId: entry.personId,
- eventName: ops.eventName,
- setProperties: ops.set,
- setOnceProperties: ops.setOnce,
- unsetProperties: ops.unset,
- isIdentified: ops.isIdentified,
- lastSeenAtMs: ops.lastSeenAtMs,
- },
- CALLER_TAG
- )
- finalPerson = person ?? finalPerson
- }
- personhogStoreFlushCounter.inc({ outcome: 'success' })
- } catch (error) {
- if (error instanceof NoRowsUpdatedError) {
- // The person was merged or deleted since
- // the fold. In-batch that is fine: the
- // merge carried the pending projection to
- // its target. Merge events are gated off
- // this store, so this counter firing means
- // a bug, not a cross-batch race.
- personhogStoreFlushCounter.inc({ outcome: 'not_found' })
- } else if (error instanceof PersonhogPropertiesSizeError) {
- // Counted only: the store holds no outputs
- // handle, so the size-violation ingestion
- // warning the Postgres store emits has no
- // path from here.
- personhogStoreFlushCounter.inc({ outcome: 'size_violation' })
- } else {
- personhogStoreFlushCounter.inc({ outcome: 'error' })
- logger.error('Failed to flush folded update to personhog', {
- teamId: entry.teamId,
- personId: entry.personId,
- error,
- })
- throw error
- }
- }
- // No FlushResult: the leader's changelog is the
- // ClickHouse person feed, so a flush publishes
- // nothing — shipping the segments is the whole job.
- return []
- })
+ const outcomes = await Promise.allSettled(
+ captured.map(({ batchId, personKey, entry }) =>
+ limit(() => this.shipEntry(batchId, personKey, entry, (entriesPerPerson.get(personKey) ?? 0) > 1))
)
)
- return results.flat()
+ for (const [batchId, lane] of this.lanes) {
+ if (lane.size === 0) {
+ this.lanes.delete(batchId)
+ }
+ }
+ const failed = outcomes.find((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
+ if (failed) {
+ throw failed.reason
+ }
+ // No FlushResults: the leader's changelog is the ClickHouse
+ // person feed, so a flush publishes nothing — shipping the
+ // segments is the whole job.
+ return []
+ }
+
+ private async shipEntry(
+ batchId: number,
+ personKey: string,
+ entry: OpsLaneEntry,
+ siblingPending: boolean
+ ): Promise<void> {
+ if (!entry.triggersUpdate && !siblingPending) {
+ personhogStoreFlushCounter.inc({ outcome: 'filtered' })
+ return
+ }
+ try {
+ for (const ops of entry.segments) {
+ await this.repository.updatePersonProperties(
+ {
+ teamId: entry.teamId,
+ personId: entry.personId,
+ eventName: ops.eventName,
+ setProperties: ops.set,
+ setOnceProperties: ops.setOnce,
+ unsetProperties: ops.unset,
+ isIdentified: ops.isIdentified,
+ lastSeenAtMs: ops.lastSeenAtMs,
+ },
+ CALLER_TAG
+ )
+ }
+ personhogStoreFlushCounter.inc({ outcome: 'success' })
+ } catch (error) {
+ if (error instanceof NoRowsUpdatedError) {
+ // The person was merged or deleted since the fold.
+ // In-batch that is fine: the merge carried the pending
+ // projection to its target. Merge events are gated off
+ // this store, so this counter firing means a bug, not a
+ // cross-batch race.
+ personhogStoreFlushCounter.inc({ outcome: 'not_found' })
+ } else if (error instanceof PersonhogPropertiesSizeError) {
+ // Counted only: the store holds no outputs handle, so
+ // the size-violation ingestion warning the Postgres
+ // store emits has no path from here.
+ personhogStoreFlushCounter.inc({ outcome: 'size_violation' })
+ } else {
+ personhogStoreFlushCounter.inc({ outcome: 'error' })
+ logger.error('Failed to flush folded update to personhog', {
+ teamId: entry.teamId,
+ personId: entry.personId,
+ error,
+ })
+ this.restoreEntry(batchId, personKey, entry)
+ throw error
+ }
+ }
+ }
+
+ /**
+ * Puts a failed entry back in its lane, its segments ahead of any
+ * folded since the pass claimed it, preserving order for the next
+ * pass. A released batch stays released: its redelivery re-folds
+ * these ops.
+ */
+ private restoreEntry(batchId: number, personKey: string, entry: OpsLaneEntry): void {
+ const lane = this.lanes.get(batchId)
+ if (!lane) {
+ return
+ }
+ const newer = lane.get(personKey)
+ if (!newer) {
+ lane.set(personKey, entry)
+ return
+ }
+ newer.segments = [...entry.segments, ...newer.segments]
+ newer.triggersUpdate = newer.triggersUpdate || entry.triggersUpdate
}
/**
@@ -603,236 +802,3 @@ export class PersonhogPersonsStore {
return memo
}
}
-
-/**
- * The batch-bound view: batchId curried. It doubles as its own
- * transaction view: `inTransaction` is a passthrough, because there are
- * no client-side transactions here. Merge safety comes from the merge
- * flow's own progress tracking over idempotent leader verbs, and the
- * merge-execution verbs throw, so the passthrough cannot silently
- * half-merge.
- */
-class BatchBoundPersonhogStore implements PersonsStoreForBatch, PersonsStoreTransactionForBatch {
- constructor(
- private readonly store: PersonhogPersonsStore,
- public readonly batchId: number
- ) {}
-
- fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null> {
- return this.store.fetchForChecking(teamId, distinctId, this.batchId)
- }
-
- fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null> {
- return this.store.fetchForUpdate(teamId, distinctId, this.batchId)
- }
-
- fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]> {
- return this.store.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, this.batchId)
- }
-
- applyEventOps(
- person: InternalPerson,
- ops: EventOps,
- distinctId: string
- ): Promise<[InternalPerson, PersonMessage[]]> {
- return this.store.applyEventOps(person, ops, distinctId, this.batchId)
- }
-
- createPerson(
- createdAt: DateTime,
- properties: Properties,
- propertiesLastUpdatedAt: PropertiesLastUpdatedAt,
- propertiesLastOperation: PropertiesLastOperation,
- teamId: number,
- isUserId: number | null,
- isIdentified: boolean,
- uuid: string,
- primaryDistinctId: { distinctId: string; version?: number },
- extraDistinctIds?: { distinctId: string; version?: number }[]
- ): Promise<CreatePersonResult> {
- return this.store.createPerson(
- createdAt,
- properties,
- propertiesLastUpdatedAt,
- propertiesLastOperation,
- teamId,
- isUserId,
- isIdentified,
- uuid,
- primaryDistinctId,
- extraDistinctIds,
- this.batchId
- )
- }
-
- deletePersons(persons: InternalPerson[], distinctId: string): Promise<PersonMessage[]> {
- return this.store.deletePersons(persons, distinctId, this.batchId)
- }
-
- deletePerson(
- person: InternalPerson,
- distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<PersonMessage[]> {
- return this.store.deletePerson(person, distinctId, this.batchId)
- }
-
- // Lifecycle marks exist to serialize merges against lifecycle
- // operations, and merge events are gated off this store.
-
- claimLifecycleMarks(
- _opId: string,
- _teamId: number,
- _persons: LifecycleMarkPerson[],
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<void> {
- throw new PersonhogPendingRpcError('claimLifecycleMarks', 'merge saga')
- }
-
- releaseLifecycleMarks(
- _opId: string,
- _teamId: number,
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<void> {
- throw new PersonhogPendingRpcError('releaseLifecycleMarks', 'merge saga')
- }
-
- isPersonLive(_person: InternalPerson, _distinctId: string, _tx?: PersonRepositoryTransaction): Promise<boolean> {
- throw new PersonhogPendingRpcError('isPersonLive', 'merge saga')
- }
-
- inTransaction<T>(
- _description: string,
- transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>
- ): Promise<T> {
- return transaction(this)
- }
-
- updatePersonWithPropertiesDiffForUpdate(
- person: InternalPerson,
- propertiesToSet: Properties,
- propertiesToUnset: string[],
- otherUpdates: Partial<InternalPerson>,
- distinctId: string,
- forceUpdate?: boolean,
- _tx?: PersonRepositoryTransaction
- ): Promise<[InternalPerson, PersonMessage[], boolean]> {
- return this.store.updatePersonWithPropertiesDiffForUpdate(
- person,
- propertiesToSet,
- propertiesToUnset,
- otherUpdates,
- distinctId,
- forceUpdate
- )
- }
-
- countDistinctIdsForPersons(
- teamId: Team['id'],
- personIds: InternalPerson['id'][],
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<Map<string, number>> {
- return this.store.countDistinctIdsForPersons(teamId, personIds)
- }
-
- fetchPersonDistinctIds(
- person: InternalPerson,
- _distinctId: string,
- limit?: number,
- _tx?: PersonRepositoryTransaction
- ): Promise<string[]> {
- return this.store.fetchPersonDistinctIds(person, limit)
- }
-
- // Merge execution is unsupported: each verb throws, naming the RPC
- // it lacks, and shadow processing gates merge events off this store.
- //
- // An implementation must clear the source persons' fold lanes as its
- // last step: the lanes' pending content already traveled to the
- // merge target through the memo projection, so flushing them after
- // the merge would manufacture not_found outcomes and drown the
- // cross-batch race signal that counter exists to carry.
-
- updatePersonForMerge(
- _person: InternalPerson,
- _update: Partial<InternalPerson>,
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<[InternalPerson, PersonMessage[], boolean]> {
- throw new PersonhogPendingRpcError(
- 'updatePersonForMerge',
- 'created_at min-merge and merge version semantics on UpdatePersonProperties'
- )
- }
-
- addDistinctId(_person: InternalPerson, _distinctId: string, _version: number): Promise<PersonMessage[]> {
- throw new PersonhogPendingRpcError('addDistinctId', 'an idempotent AddDistinctId RPC')
- }
-
- moveDistinctIds(
- _source: InternalPerson,
- _target: InternalPerson,
- _distinctId: string,
- _limit?: number,
- _tx?: PersonRepositoryTransaction
- ): Promise<MoveDistinctIdsResult> {
- throw new PersonhogPendingRpcError('moveDistinctIds', 'an idempotent MoveDistinctIds RPC')
- }
-
- moveDistinctIdsFromPersons(
- _sources: InternalPerson[],
- _target: InternalPerson,
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<MoveDistinctIdsResult> {
- throw new PersonhogPendingRpcError('moveDistinctIdsFromPersons', 'an idempotent MoveDistinctIds RPC')
- }
-
- // Postgres bookkeeping with nothing to answer in this world: shadow
- // teams are fresh, so no cohort rows or hash-key overrides exist to
- // fix up.
-
- updateCohortsAndFeatureFlagsForMerge(
- _teamID: Team['id'],
- _sourcePersonID: InternalPerson['id'],
- _targetPersonID: InternalPerson['id'],
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<void> {
- return Promise.resolve()
- }
-
- updateCohortsAndFeatureFlagsForMergeBatch(
- _teamID: Team['id'],
- _sourcePersonIDs: InternalPerson['id'][],
- _targetPersonID: InternalPerson['id'],
- _distinctId: string,
- _tx?: PersonRepositoryTransaction
- ): Promise<void> {
- return Promise.resolve()
- }
-
- /** The leader enforces the properties-size ceiling at admission. */
- personPropertiesSize(_personId: string, _teamId: number): Promise<number> {
- return Promise.resolve(0)
- }
-
- removeDistinctIdFromCache(teamId: number, distinctId: string): void {
- this.store.removeDistinctIdFromCache(teamId, distinctId)
- }
-
- prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
- return this.store.prefetchPersons(teamDistinctIds)
- }
-
- flush(): Promise<FlushResult[]> {
- return this.store.flush(this.batchId)
- }
-
- shutdown(): Promise<void> {
- return this.store.shutdown()
- }
-}
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
new file mode 100644
index 000000000000..407b83b8d597
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
@@ -0,0 +1,297 @@
+import { personhogStoreShadowErrorsCounter, personhogStoreShadowSkipsCounter } from '~/common/persons/metrics'
+import { InternalPerson } from '~/types'
+
+import { EventOps } from './person-update'
+import { PersonhogPersonsStore } from './personhog-persons-store'
+import { PersonsStore } from './persons-store'
+import { RoutingPersonsStore, assertPersonsStoreModeConfig, parsePersonsStoreMode } from './routing-persons-store'
+
+jest.mock('~/common/persons/metrics', () => ({
+ personhogStoreShadowErrorsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personhogStoreShadowSkipsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+}))
+
+/**
+ * A complete, compile-checked PersonsStore mock: the annotation forces
+ * every interface member to exist, so an interface change breaks this
+ * factory at compile time instead of leaving stale mocks that only fail
+ * when a newly routed method runs.
+ */
+function mockStore(): jest.Mocked<PersonsStore> {
+ return {
+ inTransaction: jest.fn(),
+ fetchForChecking: jest.fn().mockResolvedValue(null),
+ fetchForUpdate: jest.fn().mockResolvedValue(null),
+ fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),
+ createPerson: jest.fn().mockResolvedValue({ success: true }),
+ updatePersonForMerge: jest.fn(),
+ applyEventOps: jest.fn(),
+ updatePersonWithPropertiesDiffForUpdate: jest.fn(),
+ deletePerson: jest.fn().mockResolvedValue([]),
+ claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ isPersonLive: jest.fn().mockResolvedValue(true),
+ addDistinctId: jest.fn().mockResolvedValue([]),
+ moveDistinctIds: jest.fn().mockResolvedValue({ success: true }),
+ moveDistinctIdsFromPersons: jest.fn().mockResolvedValue({ success: true }),
+ deletePersons: jest.fn().mockResolvedValue([]),
+ countDistinctIdsForPersons: jest.fn().mockResolvedValue(new Map()),
+ updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),
+ updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
+ personPropertiesSize: jest.fn().mockResolvedValue(0),
+ fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),
+ shutdown: jest.fn().mockResolvedValue(undefined),
+ removeDistinctIdFromCache: jest.fn(),
+ prefetchPersons: jest.fn().mockResolvedValue(undefined),
+ flush: jest.fn().mockResolvedValue([]),
+ releaseBatch: jest.fn(),
+ getFlushStats: jest.fn().mockReturnValue({ dirtyEntryCount: 0, referencedBatchCount: 0, cacheEntryCount: 0 }),
+ }
+}
+
+describe('RoutingPersonsStore', () => {
+ const person = (teamId: number, id = '1'): InternalPerson =>
+ ({ id, team_id: teamId, properties: {}, is_identified: false }) as unknown as InternalPerson
+
+ const ops: EventOps = {
+ set: {},
+ setOnce: {},
+ unset: [],
+ denied: false,
+ shouldForceUpdate: false,
+ eventName: '$set',
+ } as unknown as EventOps
+
+ const makeStores = () => {
+ const pg = mockStore()
+ // 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 = mockStore()
+ const personhog = personhogMock as unknown as PersonhogPersonsStore
+ return { pg, personhogMock, personhog }
+ }
+
+ const makeStore = (stores: ReturnType<typeof makeStores>, mode: 'personhog' | 'shadow') =>
+ new RoutingPersonsStore(stores.pg, stores.personhog, mode)
+
+ it('rejects an unknown mode at parse time', () => {
+ expect(() => parsePersonsStoreMode('both')).toThrow('PERSONS_STORE_MODE')
+ expect(parsePersonsStoreMode('shadow')).toBe('shadow')
+ })
+
+ it.each([
+ ['shadow', '', 'id:1', 'PERSONHOG_ADDR'],
+ ['personhog', 'router:1', '', 'PERSONHOG_IDENTITY_ADDR'],
+ ['shadow', '', '', 'PERSONHOG_ADDR and PERSONHOG_IDENTITY_ADDR'],
+ ] as const)('%s mode without endpoints fails at boot naming the knob', (mode, routerAddr, identityAddr, named) => {
+ expect(() => assertPersonsStoreModeConfig(mode, { routerAddr, identityAddr })).toThrow(named)
+ })
+
+ it('pg mode needs no endpoints', () => {
+ expect(() => assertPersonsStoreModeConfig('pg', { routerAddr: '', identityAddr: '' })).not.toThrow()
+ })
+
+ describe('personhog mode', () => {
+ it('routes every verb to personhog, never touching pg', async () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'personhog')
+
+ await store.fetchForUpdate(1, 'a', 0)
+ await store.fetchForUpdate(2, 'b', 0)
+ expect(stores.personhogMock.fetchForUpdate).toHaveBeenCalledTimes(2)
+ expect(stores.pg.fetchForUpdate).not.toHaveBeenCalled()
+ })
+
+ it('a personhog flush failure propagates, because the store is authoritative', async () => {
+ const stores = makeStores()
+ stores.personhogMock.flush.mockRejectedValue(new Error('leader down'))
+ const store = makeStore(stores, 'personhog')
+ await expect(store.flush()).rejects.toThrow('leader down')
+ })
+
+ it('flush never runs the pg side, and returns the personhog results', async () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'personhog')
+ await expect(store.flush()).resolves.toEqual([])
+ expect(stores.personhogMock.flush).toHaveBeenCalled()
+ expect(stores.pg.flush).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('shadow mode', () => {
+ it('pg is authoritative and the personhog verb runs shadowed', async () => {
+ const stores = makeStores()
+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '7'))
+ stores.personhogMock.fetchForUpdate.mockResolvedValue(person(1, '99'))
+ const store = makeStore(stores, 'shadow')
+
+ const result = await store.fetchForUpdate(1, 'a', 0)
+
+ expect(result?.id).toBe('7')
+ expect(stores.personhogMock.fetchForUpdate).toHaveBeenCalled()
+ })
+
+ it('a shadow failure is swallowed and counted, never failing the batch', async () => {
+ const stores = makeStores()
+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '7'))
+ stores.personhogMock.fetchForUpdate.mockRejectedValue(new Error('identity down'))
+ const store = makeStore(stores, 'shadow')
+
+ const result = await store.fetchForUpdate(1, 'a', 0)
+
+ expect(result?.id).toBe('7')
+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'fetchForUpdate' })
+ })
+
+ it('a shadow flush failure is swallowed', async () => {
+ const stores = makeStores()
+ stores.personhogMock.flush.mockRejectedValue(new Error('leader down'))
+ const store = makeStore(stores, 'shadow')
+ await expect(store.flush()).resolves.toEqual([])
+ })
+
+ it('prefetch warms both worlds', async () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'shadow')
+ await store.prefetchPersons([{ teamId: 1, distinctId: 'd', batchId: 0 }])
+ expect(stores.pg.prefetchPersons).toHaveBeenCalled()
+ expect(stores.personhogMock.prefetchPersons).toHaveBeenCalled()
+ })
+
+ it('getFlushStats counts a batch once when both worlds reference it', () => {
+ const stores = makeStores()
+ stores.pg.getFlushStats.mockReturnValue({ dirtyEntryCount: 2, referencedBatchCount: 1, cacheEntryCount: 3 })
+ stores.personhogMock.getFlushStats.mockReturnValue({
+ dirtyEntryCount: 1,
+ referencedBatchCount: 1,
+ cacheEntryCount: 2,
+ })
+ const store = makeStore(stores, 'shadow')
+ expect(store.getFlushStats()).toEqual({ dirtyEntryCount: 3, referencedBatchCount: 1, cacheEntryCount: 5 })
+ })
+ })
+
+ describe('shadow writes resolve the personhog world person', () => {
+ it.each([
+ [
+ 'applyEventOps',
+ (store: RoutingPersonsStore) => store.applyEventOps(person(1, '7'), ops, 'd1', 0),
+ (m: jest.Mocked<PersonsStore>) => m.applyEventOps,
+ ],
+ [
+ 'updatePersonWithPropertiesDiffForUpdate',
+ (store: RoutingPersonsStore) =>
+ store.updatePersonWithPropertiesDiffForUpdate(person(1, '7'), { a: '1' }, [], {}, 'd1', 0),
+ (m: jest.Mocked<PersonsStore>) => m.updatePersonWithPropertiesDiffForUpdate,
+ ],
+ ] as const)('%s ships the shadow world id, not the pg id', async (_verb, call, member) => {
+ const stores = makeStores()
+ stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])
+ stores.pg.updatePersonWithPropertiesDiffForUpdate.mockResolvedValue([person(1, '7'), [], true])
+ stores.personhogMock.fetchForUpdate.mockResolvedValue(person(1, '99'))
+ stores.personhogMock.applyEventOps.mockResolvedValue([person(1, '99'), []])
+ stores.personhogMock.updatePersonWithPropertiesDiffForUpdate.mockResolvedValue([person(1, '99'), [], true])
+ const store = makeStore(stores, 'shadow')
+
+ await call(store)
+
+ const shadowArgs = member(stores.personhogMock).mock.calls[0]
+ expect((shadowArgs[0] as InternalPerson).id).toBe('99')
+ })
+
+ it('skips the shadow write, counted, when the person does not exist in the personhog world', async () => {
+ const stores = makeStores()
+ stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])
+ stores.personhogMock.fetchForUpdate.mockResolvedValue(null)
+ const store = makeStore(stores, 'shadow')
+
+ const [result] = await store.applyEventOps(person(1, '7'), ops, 'd1', 0)
+
+ expect(result.id).toBe('7')
+ expect(stores.personhogMock.applyEventOps).not.toHaveBeenCalled()
+ expect(personhogStoreShadowSkipsCounter.labels).toHaveBeenCalledWith({ verb: 'applyEventOps' })
+ })
+ })
+
+ describe('merge execution routes to the team world, never across it', () => {
+ it.each([
+ ['deletePersons', (s: RoutingPersonsStore) => s.deletePersons([person(1)], 'd'), 'deletePersons'],
+ [
+ 'addDistinctId',
+ (s: RoutingPersonsStore) => s.addDistinctId(person(1), 'd', 0, undefined, 0),
+ 'addDistinctId',
+ ],
+ [
+ 'updatePersonForMerge',
+ (s: RoutingPersonsStore) => s.updatePersonForMerge(person(1), {}, 'd', 0),
+ 'updatePersonForMerge',
+ ],
+ [
+ 'claimLifecycleMarks',
+ (s: RoutingPersonsStore) => s.claimLifecycleMarks('op', 1, [], 'd'),
+ 'claimLifecycleMarks',
+ ],
+ ] as const)('%s reaches the personhog store for a routed team', async (_name, call, member) => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'personhog')
+
+ await call(store)
+
+ expect(stores.personhogMock[member as keyof PersonsStore]).toHaveBeenCalled()
+ expect(stores.pg[member as keyof PersonsStore]).not.toHaveBeenCalled()
+ })
+
+ it('shadow mode runs merges on pg and swallows the personhog placeholder', async () => {
+ const stores = makeStores()
+ stores.personhogMock.deletePersons.mockRejectedValue(new Error('no personhog RPC: merge saga'))
+ const store = makeStore(stores, 'shadow')
+
+ await store.deletePersons([person(1)], 'd')
+
+ expect(stores.pg.deletePersons).toHaveBeenCalled()
+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'deletePersons' })
+ })
+ })
+
+ describe('inTransaction routes by mode', () => {
+ it('personhog mode reaches the personhog store, whose placeholder answers', () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'personhog')
+ const cb = () => Promise.resolve('x')
+
+ void store.inTransaction('merge', cb)
+
+ expect(stores.personhogMock.inTransaction).toHaveBeenCalledWith('merge', cb)
+ expect(stores.pg.inTransaction).not.toHaveBeenCalled()
+ })
+
+ it('shadow mode runs the transaction on pg exactly once, unshadowed', () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'shadow')
+ const cb = () => Promise.resolve('x')
+
+ void store.inTransaction('merge', cb)
+
+ expect(stores.pg.inTransaction).toHaveBeenCalledWith('merge', cb)
+ expect(stores.personhogMock.inTransaction).not.toHaveBeenCalled()
+ })
+ })
+
+ it('shutdown closes the personhog side even when pg shutdown fails', async () => {
+ const stores = makeStores()
+ stores.pg.shutdown.mockRejectedValue(new Error('pg teardown failed'))
+ const store = makeStore(stores, 'shadow')
+
+ await expect(store.shutdown()).rejects.toThrow('pg teardown failed')
+ expect(stores.personhogMock.shutdown).toHaveBeenCalled()
+ })
+
+ it('releaseBatch releases both worlds', () => {
+ const stores = makeStores()
+ const store = makeStore(stores, 'shadow')
+ store.releaseBatch(4)
+ expect(stores.pg.releaseBatch).toHaveBeenCalledWith(4)
+ expect(stores.personhogMock.releaseBatch).toHaveBeenCalledWith(4)
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
new file mode 100644
index 000000000000..22bdd39567f7
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
@@ -0,0 +1,538 @@
+import { DateTime } from 'luxon'
+
+import { personhogStoreShadowErrorsCounter, personhogStoreShadowSkipsCounter } from '~/common/persons/metrics'
+import { PersonMessage } from '~/common/persons/person-message'
+import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
+import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
+import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
+import { logger } from '~/common/utils/logger'
+import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
+import { Properties } from '~/plugin-scaffold'
+import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
+
+import { EventOps } from './person-update'
+import { PersonhogPersonsStore } from './personhog-persons-store'
+import { FlushResult, PersonsStore } from './persons-store'
+import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'
+import { PersonsStoreTransaction } from './persons-store-transaction'
+
+export type PersonsStoreMode = 'pg' | 'personhog' | 'shadow'
+
+export function parsePersonsStoreMode(raw: string): PersonsStoreMode {
+ if (raw === 'pg' || raw === 'personhog' || raw === 'shadow') {
+ return raw
+ }
+ throw new Error(`PERSONS_STORE_MODE must be pg, personhog, or shadow; got ${JSON.stringify(raw)}`)
+}
+
+/**
+ * Fails startup when a non-pg mode is missing the endpoints it dials,
+ * so a misconfiguration is one loud boot error instead of every write
+ * failing at its first RPC.
+ */
+export function assertPersonsStoreModeConfig(
+ mode: PersonsStoreMode,
+ addrs: { routerAddr: string; identityAddr: string }
+): void {
+ if (mode === 'pg') {
+ return
+ }
+ const missing = [
+ ...(addrs.routerAddr ? [] : ['PERSONHOG_ADDR']),
+ ...(addrs.identityAddr ? [] : ['PERSONHOG_IDENTITY_ADDR']),
+ ]
+ if (missing.length > 0) {
+ throw new Error(`PERSONS_STORE_MODE=${mode} requires ${missing.join(' and ')} to be set`)
+ }
+}
+
+/**
+ * Routes person-store verbs between the Postgres world and the personhog
+ * world. The mode applies to the whole deployment: personhog sends every
+ * verb to the personhog store, and shadow runs the Postgres call as the
+ * authoritative result with the personhog call after it, its failures
+ * counted and logged but never failing the batch. Verbs the personhog
+ * store cannot serve yet answer with its pending-saga placeholders, so
+ * unsupported paths fail loudly in personhog mode and surface as counted
+ * shadow errors in shadow mode.
+ */
+export class RoutingPersonsStore implements PersonsStore {
+ constructor(
+ private pg: PersonsStore,
+ private personhog: PersonhogPersonsStore,
+ private mode: 'personhog' | 'shadow'
+ ) {}
+
+ /**
+ * Run the personhog side of a shadowed verb: sequential, awaited, and
+ * never allowed to fail the batch.
+ */
+ private async shadowed(verb: string, run: () => Promise<unknown>): Promise<void> {
+ try {
+ await run()
+ } catch (error) {
+ personhogStoreShadowErrorsCounter.labels({ verb }).inc()
+ logger.warn('personhog shadow verb failed', { verb, error: String(error) })
+ }
+ }
+
+ /**
+ * The whole mode semantics, once: personhog mode runs the personhog
+ * call, shadow runs pg as the authoritative result and the personhog
+ * call after it, swallowed. Verbs carrying a live Postgres
+ * transaction never arrive here, because the transaction wrapper
+ * pg's inTransaction hands out pins every tx-scoped call to the
+ * store that opened it.
+ */
+ private async route<T>(
+ verb: string,
+ pg: () => Promise<T>,
+ personhog: () => Promise<T>,
+ opts?: { shadow?: () => Promise<unknown> }
+ ): Promise<T> {
+ if (this.mode === 'personhog') {
+ return personhog()
+ }
+ const result = await pg()
+ await this.shadowed(verb, opts?.shadow ?? personhog)
+ return result
+ }
+
+ /**
+ * Resolve the personhog world's own person for a shadowed write. The
+ * caller holds the Postgres row, whose numeric id means nothing in
+ * the personhog world — the two id sequences are independent — so a
+ * shadow write must re-resolve by distinct id and skip, counted,
+ * when the person does not exist there yet. The fetch memoizes per
+ * batch, so repeated writes to one person cost one resolution.
+ */
+ private async withShadowPerson(
+ verb: string,
+ teamId: number,
+ distinctId: string,
+ batchId: number,
+ run: (person: InternalPerson) => Promise<unknown>
+ ): Promise<void> {
+ const shadowPerson = await this.personhog.fetchForUpdate(teamId, distinctId, batchId)
+ if (shadowPerson === null) {
+ personhogStoreShadowSkipsCounter.labels({ verb }).inc()
+ return
+ }
+ await run(shadowPerson)
+ }
+
+ forBatch(batchId: number): PersonsStoreForBatch {
+ return new BatchBoundPersonsStore(this, batchId)
+ }
+
+ /**
+ * Routes by mode like every other verb; the callback runs exactly
+ * once, so shadow mode delegates to Postgres alone rather than
+ * executing it a second time against the personhog store. In
+ * personhog mode the store's own placeholder answers until the
+ * merge saga lands.
+ */
+ inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransaction) => Promise<T>): Promise<T> {
+ return this.mode === 'personhog'
+ ? this.personhog.inTransaction(description, transaction)
+ : this.pg.inTransaction(description, transaction)
+ }
+
+ fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {
+ return this.route(
+ 'fetchForChecking',
+ () => this.pg.fetchForChecking(teamId, distinctId, batchId),
+ () => this.personhog.fetchForChecking(teamId, distinctId, batchId)
+ )
+ }
+
+ fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {
+ return this.route(
+ 'fetchForUpdate',
+ () => this.pg.fetchForUpdate(teamId, distinctId, batchId),
+ () => this.personhog.fetchForUpdate(teamId, distinctId, batchId)
+ )
+ }
+
+ fetchPersonsForUpdateByDistinctIds(
+ teamId: number,
+ distinctIds: string[],
+ batchId: number
+ ): Promise<InternalPersonWithDistinctId[]> {
+ return this.route(
+ 'fetchPersonsForUpdateByDistinctIds',
+ () => this.pg.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, batchId),
+ () => this.personhog.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, batchId)
+ )
+ }
+
+ createPerson(
+ createdAt: DateTime,
+ properties: Properties,
+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,
+ propertiesLastOperation: PropertiesLastOperation,
+ teamId: number,
+ isUserId: number | null,
+ isIdentified: boolean,
+ uuid: string,
+ primaryDistinctId: { distinctId: string; version?: number },
+ extraDistinctIds: { distinctId: string; version?: number }[] | undefined,
+ tx: PersonRepositoryTransaction | undefined,
+ batchId: number
+ ): Promise<CreatePersonResult> {
+ return this.route(
+ 'createPerson',
+ () =>
+ this.pg.createPerson(
+ createdAt,
+ properties,
+ propertiesLastUpdatedAt,
+ propertiesLastOperation,
+ teamId,
+ isUserId,
+ isIdentified,
+ uuid,
+ primaryDistinctId,
+ extraDistinctIds,
+ tx,
+ batchId
+ ),
+ () =>
+ this.personhog.createPerson(
+ createdAt,
+ properties,
+ propertiesLastUpdatedAt,
+ propertiesLastOperation,
+ teamId,
+ isUserId,
+ isIdentified,
+ uuid,
+ primaryDistinctId,
+ extraDistinctIds,
+ tx,
+ batchId
+ )
+ )
+ }
+
+ applyEventOps(
+ person: InternalPerson,
+ ops: EventOps,
+ distinctId: string,
+ batchId: number
+ ): Promise<[InternalPerson, PersonMessage[]]> {
+ return this.route(
+ 'applyEventOps',
+ () => this.pg.applyEventOps(person, ops, distinctId, batchId),
+ () => this.personhog.applyEventOps(person, ops, distinctId, batchId),
+ {
+ shadow: () =>
+ this.withShadowPerson('applyEventOps', person.team_id, distinctId, batchId, (shadowPerson) =>
+ this.personhog.applyEventOps(shadowPerson, ops, distinctId, batchId)
+ ),
+ }
+ )
+ }
+
+ updatePersonWithPropertiesDiffForUpdate(
+ person: InternalPerson,
+ propertiesToSet: Properties,
+ propertiesToUnset: string[],
+ otherUpdates: Partial<InternalPerson>,
+ distinctId: string,
+ batchId: number,
+ forceUpdate?: boolean,
+ tx?: PersonRepositoryTransaction
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ return this.route(
+ 'updatePersonWithPropertiesDiffForUpdate',
+ () =>
+ this.pg.updatePersonWithPropertiesDiffForUpdate(
+ person,
+ propertiesToSet,
+ propertiesToUnset,
+ otherUpdates,
+ distinctId,
+ batchId,
+ forceUpdate,
+ tx
+ ),
+ () =>
+ this.personhog.updatePersonWithPropertiesDiffForUpdate(
+ person,
+ propertiesToSet,
+ propertiesToUnset,
+ otherUpdates,
+ distinctId,
+ batchId,
+ forceUpdate,
+ tx
+ ),
+ {
+ shadow: () =>
+ this.withShadowPerson(
+ 'updatePersonWithPropertiesDiffForUpdate',
+ person.team_id,
+ distinctId,
+ batchId,
+ (shadowPerson) =>
+ this.personhog.updatePersonWithPropertiesDiffForUpdate(
+ shadowPerson,
+ propertiesToSet,
+ propertiesToUnset,
+ otherUpdates,
+ distinctId,
+ batchId,
+ forceUpdate
+ )
+ ),
+ }
+ )
+ }
+
+ deletePerson(
+ person: InternalPerson,
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ return this.route(
+ 'deletePerson',
+ () => this.pg.deletePerson(person, distinctId, tx),
+ () => this.personhog.deletePerson(person, distinctId, tx)
+ )
+ }
+
+ claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.route(
+ 'claimLifecycleMarks',
+ () => this.pg.claimLifecycleMarks(opId, teamId, persons, distinctId, tx),
+ () => this.personhog.claimLifecycleMarks(opId, teamId, persons, distinctId, tx)
+ )
+ }
+
+ releaseLifecycleMarks(
+ opId: string,
+ teamId: number,
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.route(
+ 'releaseLifecycleMarks',
+ () => this.pg.releaseLifecycleMarks(opId, teamId, distinctId, tx),
+ () => this.personhog.releaseLifecycleMarks(opId, teamId, distinctId, tx)
+ )
+ }
+
+ isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean> {
+ return this.route(
+ 'isPersonLive',
+ () => this.pg.isPersonLive(person, distinctId, tx),
+ () => this.personhog.isPersonLive(person, distinctId, tx)
+ )
+ }
+
+ updatePersonForMerge(
+ person: InternalPerson,
+ update: Partial<InternalPerson>,
+ distinctId: string,
+ batchId: number,
+ tx?: PersonRepositoryTransaction
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ return this.route(
+ 'updatePersonForMerge',
+ () => this.pg.updatePersonForMerge(person, update, distinctId, batchId, tx),
+ () => this.personhog.updatePersonForMerge(person, update, distinctId, batchId, tx)
+ )
+ }
+
+ addDistinctId(
+ person: InternalPerson,
+ distinctId: string,
+ version: number,
+ tx: PersonRepositoryTransaction | undefined,
+ batchId: number
+ ): Promise<PersonMessage[]> {
+ return this.route(
+ 'addDistinctId',
+ () => this.pg.addDistinctId(person, distinctId, version, tx, batchId),
+ () => this.personhog.addDistinctId(person, distinctId, version, tx, batchId)
+ )
+ }
+
+ moveDistinctIds(
+ source: InternalPerson,
+ target: InternalPerson,
+ distinctId: string,
+ limit: number | undefined,
+ tx: PersonRepositoryTransaction,
+ batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ return this.route(
+ 'moveDistinctIds',
+ () => this.pg.moveDistinctIds(source, target, distinctId, limit, tx, batchId),
+ () => this.personhog.moveDistinctIds(source, target, distinctId, limit, tx, batchId)
+ )
+ }
+
+ moveDistinctIdsFromPersons(
+ sources: InternalPerson[],
+ target: InternalPerson,
+ distinctId: string,
+ tx: PersonRepositoryTransaction,
+ batchId: number
+ ): Promise<MoveDistinctIdsResult> {
+ return this.route(
+ 'moveDistinctIdsFromPersons',
+ () => this.pg.moveDistinctIdsFromPersons(sources, target, distinctId, tx, batchId),
+ () => this.personhog.moveDistinctIdsFromPersons(sources, target, distinctId, tx, batchId)
+ )
+ }
+
+ deletePersons(
+ persons: InternalPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<PersonMessage[]> {
+ return this.route(
+ 'deletePersons',
+ () => this.pg.deletePersons(persons, distinctId, tx),
+ () => this.personhog.deletePersons(persons, distinctId, tx)
+ )
+ }
+
+ countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][],
+ distinctId: string,
+ tx: PersonRepositoryTransaction
+ ): Promise<Map<string, number>> {
+ return this.route(
+ 'countDistinctIdsForPersons',
+ () => this.pg.countDistinctIdsForPersons(teamId, personIds, distinctId, tx),
+ () => this.personhog.countDistinctIdsForPersons(teamId, personIds, distinctId, tx)
+ )
+ }
+
+ updateCohortsAndFeatureFlagsForMerge(
+ teamID: Team['id'],
+ sourcePersonID: InternalPerson['id'],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.route(
+ 'updateCohortsAndFeatureFlagsForMerge',
+ () => this.pg.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId, tx),
+ () =>
+ this.personhog.updateCohortsAndFeatureFlagsForMerge(
+ teamID,
+ sourcePersonID,
+ targetPersonID,
+ distinctId,
+ tx
+ )
+ )
+ }
+
+ updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID: Team['id'],
+ sourcePersonIDs: InternalPerson['id'][],
+ targetPersonID: InternalPerson['id'],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.route(
+ 'updateCohortsAndFeatureFlagsForMergeBatch',
+ () =>
+ this.pg.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ distinctId,
+ tx
+ ),
+ () =>
+ this.personhog.updateCohortsAndFeatureFlagsForMergeBatch(
+ teamID,
+ sourcePersonIDs,
+ targetPersonID,
+ distinctId,
+ tx
+ )
+ )
+ }
+
+ fetchPersonDistinctIds(
+ person: InternalPerson,
+ distinctId: string,
+ limit: number | undefined,
+ tx: PersonRepositoryTransaction
+ ): Promise<string[]> {
+ return this.route(
+ 'fetchPersonDistinctIds',
+ () => this.pg.fetchPersonDistinctIds(person, distinctId, limit, tx),
+ () => this.personhog.fetchPersonDistinctIds(person, distinctId, limit, tx)
+ )
+ }
+
+ personPropertiesSize(personId: string, teamId: number): Promise<number> {
+ return this.route(
+ 'personPropertiesSize',
+ () => this.pg.personPropertiesSize(personId, teamId),
+ () => this.personhog.personPropertiesSize(personId, teamId)
+ )
+ }
+
+ removeDistinctIdFromCache(teamId: number, distinctId: string): void {
+ this.pg.removeDistinctIdFromCache(teamId, distinctId)
+ this.personhog.removeDistinctIdFromCache(teamId, distinctId)
+ }
+
+ prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {
+ return this.route(
+ 'prefetchPersons',
+ () => this.pg.prefetchPersons(teamDistinctIds),
+ () => this.personhog.prefetchPersons(teamDistinctIds)
+ )
+ }
+
+ getFlushStats(): BatchWritingStoreFlushStats {
+ const pg = this.pg.getFlushStats()
+ const personhog = this.personhog.getFlushStats()
+ return {
+ dirtyEntryCount: pg.dirtyEntryCount + personhog.dirtyEntryCount,
+ // Both stores see the same batches in shadow mode, so batch
+ // references overlap rather than add; entries and cache
+ // slots are per-store and sum.
+ referencedBatchCount: Math.max(pg.referencedBatchCount, personhog.referencedBatchCount),
+ cacheEntryCount: pg.cacheEntryCount + personhog.cacheEntryCount,
+ }
+ }
+
+ flush(): Promise<FlushResult[]> {
+ return this.route(
+ 'flush',
+ () => this.pg.flush(),
+ () => this.personhog.flush()
+ )
+ }
+
+ releaseBatch(batchId: number): void {
+ this.pg.releaseBatch(batchId)
+ this.personhog.releaseBatch(batchId)
+ }
+
+ async shutdown(): Promise<void> {
+ try {
+ await this.pg.shutdown()
+ } finally {
+ await this.personhog.shutdown()
+ }
+ }
+}
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index aec421758883..d2c13872495f 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -14,6 +14,9 @@ import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhou
import { PostgresGroupRepository } from '~/common/groups/repositories/postgres-group-repository'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { PersonHogConfig, buildGroupRepository, buildPersonRepository, createPersonHogClient } from '~/common/personhog'
+import { PersonHogClient } from '~/common/personhog/client'
+import { createIdentityClients } from '~/common/personhog/identity-clients'
+import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
@@ -37,7 +40,13 @@ import {
} from '~/ingestion/common/outputs/producers'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { effectivePersonMergeEventsEnabled } from '~/ingestion/common/persons/person-merge-event'
+import { PersonhogPersonsStore } from '~/ingestion/common/persons/personhog-persons-store'
import { PersonsStore } from '~/ingestion/common/persons/persons-store'
+import {
+ RoutingPersonsStore,
+ assertPersonsStoreModeConfig,
+ parsePersonsStoreMode,
+} from '~/ingestion/common/persons/routing-persons-store'
import {
FlushBatchStoresOutputs,
createGroupProducePromises,
@@ -181,6 +190,8 @@ export class IngestionApiServer implements NodeServer {
private cookielessManager?: CookielessManager
private pubsub?: PubSub
private personsStore?: BatchWritingPersonsStore
+ private personhogStore?: PersonhogPersonsStore
+ private personhogClientClosers: Array<() => void> = []
private groupStore?: BatchWritingGroupStore
// Held so shutdown cleanup can produce ClickHouse messages returned by a
// bare groupStore.flush() — the store itself no longer holds outputs
@@ -373,7 +384,42 @@ export class IngestionApiServer implements NodeServer {
optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
})
- const personsStore: PersonsStore = this.personsStore
+ // Which world person writes land in, deployment-wide: pg (the
+ // default) builds nothing new; the other modes construct the
+ // personhog store, shadow keeping pg authoritative.
+ const personsStoreMode = parsePersonsStoreMode(this.config.PERSONS_STORE_MODE)
+ assertPersonsStoreModeConfig(personsStoreMode, {
+ routerAddr: this.config.PERSONHOG_ADDR,
+ identityAddr: this.config.PERSONHOG_IDENTITY_ADDR,
+ })
+ let personsStore: PersonsStore = this.personsStore
+ if (personsStoreMode !== 'pg') {
+ const routerClient = PersonHogClient.fromConfig({
+ addr: this.config.PERSONHOG_ADDR,
+ useTls: this.config.PERSONHOG_TLS,
+ timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,
+ readMaxBytes: this.config.PERSONHOG_READ_MAX_BYTES,
+ writeMaxBytes: this.config.PERSONHOG_WRITE_MAX_BYTES,
+ clientName: 'ingestion-persons-store',
+ })
+ const identityClients = createIdentityClients({
+ addr: this.config.PERSONHOG_IDENTITY_ADDR,
+ useTls: this.config.PERSONHOG_TLS,
+ timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,
+ clientName: 'ingestion-persons-store',
+ })
+ this.personhogClientClosers = [() => routerClient.close(), identityClients.close]
+ const writeRepository = new PersonHogPersonWriteRepository(
+ routerClient,
+ identityClients.identity,
+ 'ingestion-persons-store'
+ )
+ this.personhogStore = new PersonhogPersonsStore(writeRepository, {
+ maxConcurrentUpdates: this.config.PERSONHOG_STORE_MAX_CONCURRENT_UPDATES,
+ updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
+ })
+ personsStore = new RoutingPersonsStore(this.personsStore, this.personhogStore, personsStoreMode)
+ }
this.groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {
useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,
@@ -597,6 +643,10 @@ export class IngestionApiServer implements NodeServer {
await this.personsStore.flushAndProduceMessages()
await this.personsStore.shutdown()
}
+ if (this.personhogStore) {
+ await this.personhogStore.shutdown()
+ }
+ this.personhogClientClosers.forEach((close) => close())
if (this.groupStore) {
const groupFlushResults = await this.groupStore.flush()
// flush() returns messages for the caller to produce (it no