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): personhog persons store (#79960)

Zach Brown25d00807d085
diff --git a/nodejs/package.json b/nodejs/package.json
index 260e113f1b76..66706b789ee3 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -50,7 +50,7 @@
"build:hogvm-node:dev": "pnpm --filter=@posthog/hogvm-node run build:dev",
"build:replay-anonymizer": "pnpm --filter=@posthog/replay-anonymizer package",
"build:replay-anonymizer:dev": "pnpm --filter=@posthog/replay-anonymizer run build:dev",
- "generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/types . && cd ../nodejs && eslint --fix src/common/generated/personhog && prettier --write src/common/generated/personhog",
+ "generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/identity --path personhog/lifecycle --path personhog/types . && cd ../nodejs && eslint --fix src/common/generated/personhog && prettier --write src/common/generated/personhog",
"update-ai-costs": "ts-node src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts",
"gen:ingestion-warning-types": "ts-node src/ingestion/common/scripts/generate-ingestion-warning-types.ts",
"sync-segment-icons": "DATABASE_URL=something ts-node src/cdp/segment/sync-segment-icons.ts",
diff --git a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts
new file mode 100644
index 000000000000..8bc3f851c288
--- /dev/null
+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts
@@ -0,0 +1,444 @@
+// @generated by protoc-gen-es v2.11.0 with parameter "target=ts"
+// @generated from file personhog/identity/v1/identity.proto (package personhog.identity.v1, syntax proto3)
+import type { Message } from '@bufbuild/protobuf'
+import type { GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2'
+import { fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2'
+
+import type { Person, PersonDistinctIds } from '../../types/v1/person_pb'
+import { file_personhog_types_v1_person } from '../../types/v1/person_pb'
+
+/**
+ * Describes the file personhog/identity/v1/identity.proto.
+ */
+export const file_personhog_identity_v1_identity: GenFile =
+ /*@__PURE__*/
+ fileDesc(
+ 'CiRwZXJzb25ob2cvaWRlbnRpdHkvdjEvaWRlbnRpdHkucHJvdG8SFXBlcnNvbmhvZy5pZGVudGl0eS52MSLOAQoWR2V0T3JDcmVhdGVQZXJzb25FbnRyeRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEhoKEmV4dHJhX2Rpc3RpbmN0X2lkcxgDIAMoCRISCgpldmVudF9uYW1lGAQgASgJEhYKDnNldF9wcm9wZXJ0aWVzGAUgASgMEhsKE3NldF9vbmNlX3Byb3BlcnRpZXMYBiABKAwSEgoKY3JlYXRlZF9hdBgHIAEoAxIVCg1pc19pZGVudGlmaWVkGAggASgIImQKJEdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBI8CgVlbnRyeRgBIAEoCzItLnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbkVudHJ5ImQKJUdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVzcG9uc2USKgoGcGVyc29uGAEgASgLMhoucGVyc29uaG9nLnR5cGVzLnYxLlBlcnNvbhIPCgdjcmVhdGVkGAIgASgIImgKJkdldE9yQ3JlYXRlUGVyc29uc0J5RGlzdGluY3RJZHNSZXF1ZXN0Ej4KB2VudHJpZXMYASADKAsyLS5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0T3JDcmVhdGVQZXJzb25FbnRyeSKqAQoXR2V0T3JDcmVhdGVQZXJzb25SZXN1bHQSDwoHdGVhbV9pZBgBIAEoAxITCgtkaXN0aW5jdF9pZBgCIAEoCRIvCgZwZXJzb24YAyABKAsyGi5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uSACIAQESDwoHY3JlYXRlZBgEIAEoCBISCgVlcnJvchgFIAEoCUgBiAEBQgkKB19wZXJzb25CCAoGX2Vycm9yImoKJ0dldE9yQ3JlYXRlUGVyc29uc0J5RGlzdGluY3RJZHNSZXNwb25zZRI/CgdyZXN1bHRzGAEgAygLMi4ucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldE9yQ3JlYXRlUGVyc29uUmVzdWx0IjEKCVBlcnNvbktleRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJIlAKHkdldFBlcnNvbnNCeURpc3RpbmN0SWRzUmVxdWVzdBIuCgRrZXlzGAEgAygLMiAucGVyc29uaG9nLmlkZW50aXR5LnYxLlBlcnNvbktleSJ/ChtHZXRQZXJzb25CeURpc3RpbmN0SWRSZXN1bHQSDwoHdGVhbV9pZBgBIAEoAxITCgtkaXN0aW5jdF9pZBgCIAEoCRIvCgZwZXJzb24YAyABKAsyGi5wZXJzb25ob2cudHlwZXMudjEuUGVyc29uSACIAQFCCQoHX3BlcnNvbiJmCh9HZXRQZXJzb25zQnlEaXN0aW5jdElkc1Jlc3BvbnNlEkMKB3Jlc3VsdHMYASADKAsyMi5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0UGVyc29uQnlEaXN0aW5jdElkUmVzdWx0InoKH0dldERpc3RpbmN0SWRzRm9yUGVyc29uc1JlcXVlc3QSDwoHdGVhbV9pZBgBIAEoAxISCgpwZXJzb25faWRzGAIgAygDEh0KEGxpbWl0X3Blcl9wZXJzb24YAyABKANIAIgBAUITChFfbGltaXRfcGVyX3BlcnNvbiJmCiBHZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXNwb25zZRJCChNwZXJzb25fZGlzdGluY3RfaWRzGAEgAygLMiUucGVyc29uaG9nLnR5cGVzLnYxLlBlcnNvbkRpc3RpbmN0SWRzMuwEChFQZXJzb25Ib2dJZGVudGl0eRKaAQodR2V0T3JDcmVhdGVQZXJzb25CeURpc3RpbmN0SWQSOy5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0T3JDcmVhdGVQZXJzb25CeURpc3RpbmN0SWRSZXF1ZXN0GjwucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVzcG9uc2USoAEKH0dldE9yQ3JlYXRlUGVyc29uc0J5RGlzdGluY3RJZHMSPS5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0T3JDcmVhdGVQZXJzb25zQnlEaXN0aW5jdElkc1JlcXVlc3QaPi5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0T3JDcmVhdGVQZXJzb25zQnlEaXN0aW5jdElkc1Jlc3BvbnNlEogBChdHZXRQZXJzb25zQnlEaXN0aW5jdElkcxI1LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRQZXJzb25zQnlEaXN0aW5jdElkc1JlcXVlc3QaNi5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0UGVyc29uc0J5RGlzdGluY3RJZHNSZXNwb25zZRKLAQoYR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zEjYucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldERpc3RpbmN0SWRzRm9yUGVyc29uc1JlcXVlc3QaNy5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zUmVzcG9uc2ViBnByb3RvMw',
+ [file_personhog_types_v1_person]
+ )
+
+/**
+ * GetOrCreatePersonEntry is a single get-or-create key: resolve distinct_id
+ * within team_id, creating a person stub when absent. The properties and
+ * scalars are used on the creation branch only — when the person already
+ * exists the caller applies $set/$set_once through UpdatePersonProperties.
+ *
+ * @generated from message personhog.identity.v1.GetOrCreatePersonEntry
+ */
+export type GetOrCreatePersonEntry = Message<'personhog.identity.v1.GetOrCreatePersonEntry'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * The primary distinct id. The person UUID derives deterministically from
+ * team_id:distinct_id, so its distinct id row is always version 0.
+ *
+ * @generated from field: string distinct_id = 2;
+ */
+ distinctId: string
+
+ /**
+ * Additional distinct ids mapped to the person on the creation branch.
+ * Their rows get version 1 when the distinct id has personless history
+ * (a posthog_personlessdistinctid row already existed), else version 0.
+ * An extra already mapped to a different person keeps its existing
+ * mapping: get-or-create never re-points or merges, so the conflict is
+ * not an error and is not reported — re-pointing distinct ids is the
+ * merge path's job.
+ *
+ * @generated from field: repeated string extra_distinct_ids = 3;
+ */
+ extraDistinctIds: string[]
+
+ /**
+ * The event name that triggered this call (e.g. "$identify", "$pageview").
+ * Forwarded to the leader's property update on the creation branch.
+ *
+ * @generated from field: string event_name = 4;
+ */
+ eventName: string
+
+ /**
+ * JSON-encoded $set map, applied via the leader on the creation branch.
+ *
+ * @generated from field: bytes set_properties = 5;
+ */
+ setProperties: Uint8Array
+
+ /**
+ * JSON-encoded $set_once map, applied via the leader on the creation branch.
+ *
+ * @generated from field: bytes set_once_properties = 6;
+ */
+ setOnceProperties: Uint8Array
+
+ /**
+ * Person created_at, epoch millis. Used on the creation branch.
+ *
+ * @generated from field: int64 created_at = 7;
+ */
+ createdAt: bigint
+
+ /**
+ * @generated from field: bool is_identified = 8;
+ */
+ isIdentified: boolean
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonEntry.
+ * Use `create(GetOrCreatePersonEntrySchema)` to create a new message.
+ */
+export const GetOrCreatePersonEntrySchema: GenMessage<GetOrCreatePersonEntry> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 0)
+
+/**
+ * @generated from message personhog.identity.v1.GetOrCreatePersonByDistinctIdRequest
+ */
+export type GetOrCreatePersonByDistinctIdRequest =
+ Message<'personhog.identity.v1.GetOrCreatePersonByDistinctIdRequest'> & {
+ /**
+ * @generated from field: personhog.identity.v1.GetOrCreatePersonEntry entry = 1;
+ */
+ entry?: GetOrCreatePersonEntry
+ }
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonByDistinctIdRequest.
+ * Use `create(GetOrCreatePersonByDistinctIdRequestSchema)` to create a new message.
+ */
+export const GetOrCreatePersonByDistinctIdRequestSchema: GenMessage<GetOrCreatePersonByDistinctIdRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 1)
+
+/**
+ * created = true means the stub row is committed in Postgres AND the initial
+ * properties (when provided) are durable in the leader's changelog.
+ *
+ * @generated from message personhog.identity.v1.GetOrCreatePersonByDistinctIdResponse
+ */
+export type GetOrCreatePersonByDistinctIdResponse =
+ Message<'personhog.identity.v1.GetOrCreatePersonByDistinctIdResponse'> & {
+ /**
+ * @generated from field: personhog.types.v1.Person person = 1;
+ */
+ person?: Person
+
+ /**
+ * @generated from field: bool created = 2;
+ */
+ created: boolean
+ }
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonByDistinctIdResponse.
+ * Use `create(GetOrCreatePersonByDistinctIdResponseSchema)` to create a new message.
+ */
+export const GetOrCreatePersonByDistinctIdResponseSchema: GenMessage<GetOrCreatePersonByDistinctIdResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 2)
+
+/**
+ * @generated from message personhog.identity.v1.GetOrCreatePersonsByDistinctIdsRequest
+ */
+export type GetOrCreatePersonsByDistinctIdsRequest =
+ Message<'personhog.identity.v1.GetOrCreatePersonsByDistinctIdsRequest'> & {
+ /**
+ * Max 250 per request. Keys may span teams; each entry is independent and
+ * individually retryable.
+ *
+ * @generated from field: repeated personhog.identity.v1.GetOrCreatePersonEntry entries = 1;
+ */
+ entries: GetOrCreatePersonEntry[]
+ }
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonsByDistinctIdsRequest.
+ * Use `create(GetOrCreatePersonsByDistinctIdsRequestSchema)` to create a new message.
+ */
+export const GetOrCreatePersonsByDistinctIdsRequestSchema: GenMessage<GetOrCreatePersonsByDistinctIdsRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 3)
+
+/**
+ * GetOrCreatePersonResult is the per-key outcome of a batch get-or-create.
+ *
+ * @generated from message personhog.identity.v1.GetOrCreatePersonResult
+ */
+export type GetOrCreatePersonResult = Message<'personhog.identity.v1.GetOrCreatePersonResult'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * @generated from field: string distinct_id = 2;
+ */
+ distinctId: string
+
+ /**
+ * Absent when this key failed (see error).
+ *
+ * @generated from field: optional personhog.types.v1.Person person = 3;
+ */
+ person?: Person
+
+ /**
+ * @generated from field: bool created = 4;
+ */
+ created: boolean
+
+ /**
+ * Set when this key failed; the caller should retry the key. A committed
+ * stub whose initial-properties write failed surfaces here — the retried
+ * key resolves to the stub (created = false) and applies properties through
+ * the normal update path.
+ *
+ * @generated from field: optional string error = 5;
+ */
+ error?: string
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonResult.
+ * Use `create(GetOrCreatePersonResultSchema)` to create a new message.
+ */
+export const GetOrCreatePersonResultSchema: GenMessage<GetOrCreatePersonResult> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 4)
+
+/**
+ * @generated from message personhog.identity.v1.GetOrCreatePersonsByDistinctIdsResponse
+ */
+export type GetOrCreatePersonsByDistinctIdsResponse =
+ Message<'personhog.identity.v1.GetOrCreatePersonsByDistinctIdsResponse'> & {
+ /**
+ * Same order as the request entries.
+ *
+ * @generated from field: repeated personhog.identity.v1.GetOrCreatePersonResult results = 1;
+ */
+ results: GetOrCreatePersonResult[]
+ }
+
+/**
+ * Describes the message personhog.identity.v1.GetOrCreatePersonsByDistinctIdsResponse.
+ * Use `create(GetOrCreatePersonsByDistinctIdsResponseSchema)` to create a new message.
+ */
+export const GetOrCreatePersonsByDistinctIdsResponseSchema: GenMessage<GetOrCreatePersonsByDistinctIdsResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 5)
+
+/**
+ * A single resolution key: distinct_id within team_id.
+ *
+ * @generated from message personhog.identity.v1.PersonKey
+ */
+export type PersonKey = Message<'personhog.identity.v1.PersonKey'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * @generated from field: string distinct_id = 2;
+ */
+ distinctId: string
+}
+
+/**
+ * Describes the message personhog.identity.v1.PersonKey.
+ * Use `create(PersonKeySchema)` to create a new message.
+ */
+export const PersonKeySchema: GenMessage<PersonKey> = /*@__PURE__*/ messageDesc(file_personhog_identity_v1_identity, 6)
+
+/**
+ * @generated from message personhog.identity.v1.GetPersonsByDistinctIdsRequest
+ */
+export type GetPersonsByDistinctIdsRequest = Message<'personhog.identity.v1.GetPersonsByDistinctIdsRequest'> & {
+ /**
+ * Max 250 per request. Keys may span teams.
+ *
+ * @generated from field: repeated personhog.identity.v1.PersonKey keys = 1;
+ */
+ keys: PersonKey[]
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetPersonsByDistinctIdsRequest.
+ * Use `create(GetPersonsByDistinctIdsRequestSchema)` to create a new message.
+ */
+export const GetPersonsByDistinctIdsRequestSchema: GenMessage<GetPersonsByDistinctIdsRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 7)
+
+/**
+ * The per-key outcome of a batch resolve. Mirrors GetOrCreatePersonResult
+ * minus the creation fields: resolution never creates, so an absent key
+ * is a result, not an error.
+ *
+ * @generated from message personhog.identity.v1.GetPersonByDistinctIdResult
+ */
+export type GetPersonByDistinctIdResult = Message<'personhog.identity.v1.GetPersonByDistinctIdResult'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * @generated from field: string distinct_id = 2;
+ */
+ distinctId: string
+
+ /**
+ * Absent when the distinct id resolves to no live person — unknown,
+ * tombstoned, or its person deleted.
+ *
+ * @generated from field: optional personhog.types.v1.Person person = 3;
+ */
+ person?: Person
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetPersonByDistinctIdResult.
+ * Use `create(GetPersonByDistinctIdResultSchema)` to create a new message.
+ */
+export const GetPersonByDistinctIdResultSchema: GenMessage<GetPersonByDistinctIdResult> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 8)
+
+/**
+ * @generated from message personhog.identity.v1.GetPersonsByDistinctIdsResponse
+ */
+export type GetPersonsByDistinctIdsResponse = Message<'personhog.identity.v1.GetPersonsByDistinctIdsResponse'> & {
+ /**
+ * Same order as the request keys.
+ *
+ * @generated from field: repeated personhog.identity.v1.GetPersonByDistinctIdResult results = 1;
+ */
+ results: GetPersonByDistinctIdResult[]
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetPersonsByDistinctIdsResponse.
+ * Use `create(GetPersonsByDistinctIdsResponseSchema)` to create a new message.
+ */
+export const GetPersonsByDistinctIdsResponseSchema: GenMessage<GetPersonsByDistinctIdsResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 9)
+
+/**
+ * The identity-side twin of the service RPC of the same name, minus
+ * ReadOptions: identity always reads the primary, so there is no
+ * consistency to choose.
+ *
+ * @generated from message personhog.identity.v1.GetDistinctIdsForPersonsRequest
+ */
+export type GetDistinctIdsForPersonsRequest = Message<'personhog.identity.v1.GetDistinctIdsForPersonsRequest'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * Max 250 per request.
+ *
+ * @generated from field: repeated int64 person_ids = 2;
+ */
+ personIds: bigint[]
+
+ /**
+ * Max distinct ids returned per person; identified ids survive the
+ * cut. 0 or absent = no limit.
+ *
+ * @generated from field: optional int64 limit_per_person = 3;
+ */
+ limitPerPerson?: bigint
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetDistinctIdsForPersonsRequest.
+ * Use `create(GetDistinctIdsForPersonsRequestSchema)` to create a new message.
+ */
+export const GetDistinctIdsForPersonsRequestSchema: GenMessage<GetDistinctIdsForPersonsRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 10)
+
+/**
+ * @generated from message personhog.identity.v1.GetDistinctIdsForPersonsResponse
+ */
+export type GetDistinctIdsForPersonsResponse = Message<'personhog.identity.v1.GetDistinctIdsForPersonsResponse'> & {
+ /**
+ * @generated from field: repeated personhog.types.v1.PersonDistinctIds person_distinct_ids = 1;
+ */
+ personDistinctIds: PersonDistinctIds[]
+}
+
+/**
+ * Describes the message personhog.identity.v1.GetDistinctIdsForPersonsResponse.
+ * Use `create(GetDistinctIdsForPersonsResponseSchema)` to create a new message.
+ */
+export const GetDistinctIdsForPersonsResponseSchema: GenMessage<GetDistinctIdsForPersonsResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_identity_v1_identity, 11)
+
+/**
+ * PersonHogIdentity owns the identity graph: distinct id resolution and
+ * get-or-create orchestration across the sync plane (Postgres primary) and
+ * the async plane (leader-owned properties). Ingestion calls this service
+ * directly; it is not fronted by the router.
+ *
+ * Get-or-create semantics: created = true means the person stub row is
+ * committed in Postgres AND the initial properties (when provided) are
+ * durable in the leader's changelog. A crash between the stub commit and the
+ * leader ack surfaces as an error; the retried key resolves to the stub
+ * (created = false) and the caller applies properties through the normal
+ * UpdatePersonProperties path — the event remains the durable source of the
+ * initial properties.
+ *
+ * @generated from service personhog.identity.v1.PersonHogIdentity
+ */
+export const PersonHogIdentity: GenService<{
+ /**
+ * @generated from rpc personhog.identity.v1.PersonHogIdentity.GetOrCreatePersonByDistinctId
+ */
+ getOrCreatePersonByDistinctId: {
+ methodKind: 'unary'
+ input: typeof GetOrCreatePersonByDistinctIdRequestSchema
+ output: typeof GetOrCreatePersonByDistinctIdResponseSchema
+ }
+ /**
+ * @generated from rpc personhog.identity.v1.PersonHogIdentity.GetOrCreatePersonsByDistinctIds
+ */
+ getOrCreatePersonsByDistinctIds: {
+ methodKind: 'unary'
+ input: typeof GetOrCreatePersonsByDistinctIdsRequestSchema
+ output: typeof GetOrCreatePersonsByDistinctIdsResponseSchema
+ }
+ /**
+ * Resolve-only counterpart of get-or-create: same primary-backed
+ * resolution, same Person payload, never creates. This is the strong
+ * resolve — the router's GetPersonsByDistinctIds reads the replica and
+ * its consistency option does not change that.
+ *
+ * @generated from rpc personhog.identity.v1.PersonHogIdentity.GetPersonsByDistinctIds
+ */
+ getPersonsByDistinctIds: {
+ methodKind: 'unary'
+ input: typeof GetPersonsByDistinctIdsRequestSchema
+ output: typeof GetPersonsByDistinctIdsResponseSchema
+ }
+ /**
+ * Person-id to distinct-ids expansion on the primary; the strong twin
+ * of the router RPC of the same name (which reads the replica).
+ *
+ * @generated from rpc personhog.identity.v1.PersonHogIdentity.GetDistinctIdsForPersons
+ */
+ getDistinctIdsForPersons: {
+ methodKind: 'unary'
+ input: typeof GetDistinctIdsForPersonsRequestSchema
+ output: typeof GetDistinctIdsForPersonsResponseSchema
+ }
+}> = /*@__PURE__*/ serviceDesc(file_personhog_identity_v1_identity, 0)
diff --git a/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts b/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts
new file mode 100644
index 000000000000..61fbebabd330
--- /dev/null
+++ b/nodejs/src/common/generated/personhog/personhog/lifecycle/v1/lifecycle_pb.ts
@@ -0,0 +1,171 @@
+// @generated by protoc-gen-es v2.11.0 with parameter "target=ts"
+// @generated from file personhog/lifecycle/v1/lifecycle.proto (package personhog.lifecycle.v1, syntax proto3)
+import type { Message } from '@bufbuild/protobuf'
+import type { GenEnum, GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2'
+import { enumDesc, fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2'
+
+/**
+ * Describes the file personhog/lifecycle/v1/lifecycle.proto.
+ */
+export const file_personhog_lifecycle_v1_lifecycle: GenFile =
+ /*@__PURE__*/
+ fileDesc(
+ 'CiZwZXJzb25ob2cvbGlmZWN5Y2xlL3YxL2xpZmVjeWNsZS5wcm90bxIWcGVyc29uaG9nLmxpZmVjeWNsZS52MSJKChREZWxldGVQZXJzb25zUmVxdWVzdBIPCgd0ZWFtX2lkGAEgASgDEhIKCnBlcnNvbl9pZHMYAiADKAMSDQoFb3BfaWQYAyABKAkiZQoSRGVsZXRlUGVyc29uUmVzdWx0EhEKCXBlcnNvbl9pZBgBIAEoAxI8CgdvdXRjb21lGAIgASgOMisucGVyc29uaG9nLmxpZmVjeWNsZS52MS5EZWxldGVQZXJzb25PdXRjb21lImMKFURlbGV0ZVBlcnNvbnNSZXNwb25zZRINCgVvcF9pZBgBIAEoCRI7CgdyZXN1bHRzGAIgAygLMioucGVyc29uaG9nLmxpZmVjeWNsZS52MS5EZWxldGVQZXJzb25SZXN1bHQqsAEKE0RlbGV0ZVBlcnNvbk91dGNvbWUSJQohREVMRVRFX1BFUlNPTl9PVVRDT01FX1VOU1BFQ0lGSUVEEAASIQodREVMRVRFX1BFUlNPTl9PVVRDT01FX0RFTEVURUQQARIqCiZERUxFVEVfUEVSU09OX09VVENPTUVfU0tJUFBFRF9DT05GTElDVBACEiMKH0RFTEVURV9QRVJTT05fT1VUQ09NRV9OT1RfRk9VTkQQAzKCAQoSUGVyc29uSG9nTGlmZWN5Y2xlEmwKDURlbGV0ZVBlcnNvbnMSLC5wZXJzb25ob2cubGlmZWN5Y2xlLnYxLkRlbGV0ZVBlcnNvbnNSZXF1ZXN0Gi0ucGVyc29uaG9nLmxpZmVjeWNsZS52MS5EZWxldGVQZXJzb25zUmVzcG9uc2ViBnByb3RvMw'
+ )
+
+/**
+ * DeletePersonsRequest identifies the persons to destroy. Arguments are
+ * already person ids — there is no identity to resolve first, so the RPC
+ * goes straight into the saga runner.
+ *
+ * @generated from message personhog.lifecycle.v1.DeletePersonsRequest
+ */
+export type DeletePersonsRequest = Message<'personhog.lifecycle.v1.DeletePersonsRequest'> & {
+ /**
+ * @generated from field: int64 team_id = 1;
+ */
+ teamId: bigint
+
+ /**
+ * posthog_person.id values to delete. Max 250 per request.
+ *
+ * @generated from field: repeated int64 person_ids = 2;
+ */
+ personIds: bigint[]
+
+ /**
+ * Caller-generated operation id (UUID string). Persisted with the
+ * operation: a retried call carrying the same op_id attaches to the
+ * existing operation and returns its recorded outcome instead of starting
+ * a new one, so callers must reuse the op_id across retries.
+ *
+ * @generated from field: string op_id = 3;
+ */
+ opId: string
+}
+
+/**
+ * Describes the message personhog.lifecycle.v1.DeletePersonsRequest.
+ * Use `create(DeletePersonsRequestSchema)` to create a new message.
+ */
+export const DeletePersonsRequestSchema: GenMessage<DeletePersonsRequest> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_lifecycle_v1_lifecycle, 0)
+
+/**
+ * @generated from message personhog.lifecycle.v1.DeletePersonResult
+ */
+export type DeletePersonResult = Message<'personhog.lifecycle.v1.DeletePersonResult'> & {
+ /**
+ * @generated from field: int64 person_id = 1;
+ */
+ personId: bigint
+
+ /**
+ * @generated from field: personhog.lifecycle.v1.DeletePersonOutcome outcome = 2;
+ */
+ outcome: DeletePersonOutcome
+}
+
+/**
+ * Describes the message personhog.lifecycle.v1.DeletePersonResult.
+ * Use `create(DeletePersonResultSchema)` to create a new message.
+ */
+export const DeletePersonResultSchema: GenMessage<DeletePersonResult> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_lifecycle_v1_lifecycle, 1)
+
+/**
+ * @generated from message personhog.lifecycle.v1.DeletePersonsResponse
+ */
+export type DeletePersonsResponse = Message<'personhog.lifecycle.v1.DeletePersonsResponse'> & {
+ /**
+ * Echo of the request op_id.
+ *
+ * @generated from field: string op_id = 1;
+ */
+ opId: string
+
+ /**
+ * One result per requested person id, same order as the request.
+ *
+ * @generated from field: repeated personhog.lifecycle.v1.DeletePersonResult results = 2;
+ */
+ results: DeletePersonResult[]
+}
+
+/**
+ * Describes the message personhog.lifecycle.v1.DeletePersonsResponse.
+ * Use `create(DeletePersonsResponseSchema)` to create a new message.
+ */
+export const DeletePersonsResponseSchema: GenMessage<DeletePersonsResponse> =
+ /*@__PURE__*/
+ messageDesc(file_personhog_lifecycle_v1_lifecycle, 2)
+
+/**
+ * @generated from enum personhog.lifecycle.v1.DeletePersonOutcome
+ */
+export enum DeletePersonOutcome {
+ /**
+ * @generated from enum value: DELETE_PERSON_OUTCOME_UNSPECIFIED = 0;
+ */
+ UNSPECIFIED = 0,
+
+ /**
+ * The person was destroyed (or the recorded outcome of a completed
+ * operation says it was).
+ *
+ * @generated from enum value: DELETE_PERSON_OUTCOME_DELETED = 1;
+ */
+ DELETED = 1,
+
+ /**
+ * Another live lifecycle operation holds this person's mark; nothing was
+ * done for this person. Retry after that operation finishes.
+ *
+ * @generated from enum value: DELETE_PERSON_OUTCOME_SKIPPED_CONFLICT = 2;
+ */
+ SKIPPED_CONFLICT = 2,
+
+ /**
+ * No live person row with this id exists in the team.
+ *
+ * @generated from enum value: DELETE_PERSON_OUTCOME_NOT_FOUND = 3;
+ */
+ NOT_FOUND = 3,
+}
+
+/**
+ * Describes the enum personhog.lifecycle.v1.DeletePersonOutcome.
+ */
+export const DeletePersonOutcomeSchema: GenEnum<DeletePersonOutcome> =
+ /*@__PURE__*/
+ enumDesc(file_personhog_lifecycle_v1_lifecycle, 0)
+
+/**
+ * PersonHogLifecycle runs person-destroying operations (delete now, merge
+ * case 3 later) as durable sagas: all saga state lives in the lifecycle_op
+ * tables on the persons primary, the service itself stays stateless.
+ *
+ * Ack semantics: the RPC drives the saga to Completed before responding —
+ * an OK response means the operation's sync-plane work is committed and the
+ * owning leaders have produced the death documents. On a crash or timeout
+ * the caller retries with the same op_id; the retry attaches to the
+ * existing operation, finishes any incomplete tail steps, and returns the
+ * recorded outcome. A background sweeper backstops abandoned operations.
+ *
+ * Co-served on the identity server, but a separate service so callers are
+ * insulated from any future split.
+ *
+ * @generated from service personhog.lifecycle.v1.PersonHogLifecycle
+ */
+export const PersonHogLifecycle: GenService<{
+ /**
+ * @generated from rpc personhog.lifecycle.v1.PersonHogLifecycle.DeletePersons
+ */
+ deletePersons: {
+ methodKind: 'unary'
+ input: typeof DeletePersonsRequestSchema
+ output: typeof DeletePersonsResponseSchema
+ }
+}> = /*@__PURE__*/ serviceDesc(file_personhog_lifecycle_v1_lifecycle, 0)
diff --git a/nodejs/src/common/personhog/client.ts b/nodejs/src/common/personhog/client.ts
index 02fd285680ff..a255a8a090c3 100644
--- a/nodejs/src/common/personhog/client.ts
+++ b/nodejs/src/common/personhog/client.ts
@@ -105,6 +105,11 @@ export function eventualReadOptions() {
return create(ReadOptionsSchema, { consistency: ConsistencyLevel.EVENTUAL })
}
+/** Routes through the partition's leader for read-your-writes consistency. */
+export function strongReadOptions() {
+ return create(ReadOptionsSchema, { consistency: ConsistencyLevel.STRONG })
+}
+
export function resolveConsistencyHeader(message: unknown): 'strong' | 'eventual' {
const msg = message as Record<string, unknown> | undefined
const readOptions = msg?.readOptions as { consistency?: ConsistencyLevel } | undefined
diff --git a/nodejs/src/common/personhog/identity.test.ts b/nodejs/src/common/personhog/identity.test.ts
new file mode 100644
index 000000000000..11c22cc3fbb6
--- /dev/null
+++ b/nodejs/src/common/personhog/identity.test.ts
@@ -0,0 +1,58 @@
+import { createClient, createRouterTransport } from '@connectrpc/connect'
+
+import {
+ GetDistinctIdsForPersonsRequest,
+ GetPersonsByDistinctIdsRequest,
+ PersonHogIdentity,
+} from '~/common/generated/personhog/personhog/identity/v1/identity_pb'
+
+import { PersonhogIdentityOperations } from './identity'
+
+describe('PersonhogIdentityOperations', () => {
+ function makeOps(handlers: { getPersonsByDistinctIds?: jest.Mock; getDistinctIdsForPersons?: jest.Mock }) {
+ const transport = createRouterTransport(({ service }) => {
+ service(PersonHogIdentity, {
+ getOrCreatePersonByDistinctId: jest.fn(() => ({ person: undefined, created: false })),
+ getOrCreatePersonsByDistinctIds: jest.fn(() => ({ results: [] })),
+ getPersonsByDistinctIds: handlers.getPersonsByDistinctIds ?? jest.fn(() => ({ results: [] })),
+ getDistinctIdsForPersons:
+ handlers.getDistinctIdsForPersons ?? jest.fn(() => ({ personDistinctIds: [] })),
+ })
+ })
+ return new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport))
+ }
+
+ // The identity service rejects batches above 250, so the wrappers must
+ // chunk — without this, a large-batch prefetch degrades to a silent
+ // no-op on exactly the batches it exists for.
+ it('chunks resolve requests to the service batch cap', async () => {
+ const handler = jest.fn((req: GetPersonsByDistinctIdsRequest) => ({
+ results: req.keys.map((key) => ({ teamId: key.teamId, distinctId: key.distinctId, person: undefined })),
+ }))
+ const ops = makeOps({ getPersonsByDistinctIds: handler })
+
+ const keys = Array.from({ length: 251 }, (_, i) => ({ teamId: 1, distinctId: `d${i}` }))
+ const results = await ops.getPersonsByDistinctIds(keys)
+
+ expect(handler).toHaveBeenCalledTimes(2)
+ expect(handler.mock.calls[0][0].keys).toHaveLength(250)
+ expect(handler.mock.calls[1][0].keys).toHaveLength(1)
+ expect(results).toHaveLength(251)
+ })
+
+ it('chunks expansion requests to the service batch cap', async () => {
+ const handler = jest.fn((req: GetDistinctIdsForPersonsRequest) => ({
+ personDistinctIds: req.personIds.map((id) => ({
+ personId: id,
+ distinctIds: [{ distinctId: `d-${id}`, version: undefined }],
+ })),
+ }))
+ const ops = makeOps({ getDistinctIdsForPersons: handler })
+
+ const ids = Array.from({ length: 251 }, (_, i) => String(i + 1))
+ const byPerson = await ops.getDistinctIdsForPersons(1, ids)
+
+ expect(handler).toHaveBeenCalledTimes(2)
+ expect(Object.keys(byPerson)).toHaveLength(251)
+ })
+})
diff --git a/nodejs/src/common/personhog/identity.ts b/nodejs/src/common/personhog/identity.ts
new file mode 100644
index 000000000000..406e065c702b
--- /dev/null
+++ b/nodejs/src/common/personhog/identity.ts
@@ -0,0 +1,172 @@
+import { create } from '@bufbuild/protobuf'
+import { Client, Code, ConnectError } from '@connectrpc/connect'
+
+import {
+ GetDistinctIdsForPersonsRequestSchema,
+ GetOrCreatePersonByDistinctIdRequestSchema,
+ GetPersonsByDistinctIdsRequestSchema,
+ PersonHogIdentity,
+} from '~/common/generated/personhog/personhog/identity/v1/identity_pb'
+import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
+import { Properties } from '~/plugin-scaffold'
+import { InternalPerson } from '~/types'
+
+import { encodeJsonBytes, protoPersonToDomain } from './persons'
+
+/**
+ * A single get-or-create key: resolve distinct_id within team_id,
+ * creating a person stub when absent. The properties and scalars apply
+ * on the creation branch only; an existing person takes its ops through
+ * the normal update path. The person UUID derives deterministically from
+ * team_id:distinct_id on the identity service's side; no id is supplied
+ * here.
+ */
+export interface GetOrCreatePersonEntry {
+ teamId: number
+ distinctId: string
+ /** Additional distinct ids mapped to the person on the creation branch. */
+ extraDistinctIds?: string[]
+ /** The event name that triggered this call, forwarded to the leader on creation. */
+ eventName: string
+ setProperties?: Properties
+ setOnceProperties?: Properties
+ /** Person created_at on the creation branch, epoch milliseconds. */
+ createdAtMs: number
+ isIdentified?: boolean
+}
+
+/** The identity service rejects batches above this; chunk client-side. */
+const IDENTITY_BATCH_SIZE = 250
+
+export interface DistinctIdKey {
+ teamId: number
+ distinctId: string
+}
+
+/**
+ * The identity service's client wrapper: proto encoding and domain
+ * decoding for distinct-id resolution, expansion, and person stub
+ * creation. Callers never see proto types or gRPC codes through this
+ * surface.
+ */
+export class PersonhogIdentityOperations {
+ constructor(private client: Client<typeof PersonHogIdentity>) {}
+
+ /**
+ * Resolve-only counterpart of get-or-create: primary-backed
+ * resolution, never creates. Results come back in request order;
+ * a null person means the distinct id resolves to no live person.
+ */
+ async getPersonsByDistinctIds(
+ keys: DistinctIdKey[],
+ callerTag?: string
+ ): Promise<{ teamId: number; distinctId: string; person: InternalPerson | null }[]> {
+ if (keys.length === 0) {
+ return []
+ }
+ const out: { teamId: number; distinctId: string; person: InternalPerson | null }[] = []
+ for (let i = 0; i < keys.length; i += IDENTITY_BATCH_SIZE) {
+ const chunk = keys.slice(i, i + IDENTITY_BATCH_SIZE)
+ const response = await this.client.getPersonsByDistinctIds(
+ create(GetPersonsByDistinctIdsRequestSchema, {
+ keys: chunk.map((key) => ({
+ teamId: BigInt(key.teamId),
+ distinctId: key.distinctId,
+ })),
+ }),
+ callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined
+ )
+ for (const result of response.results) {
+ out.push({
+ teamId: Number(result.teamId),
+ distinctId: result.distinctId,
+ person: result.person ? protoPersonToDomain(result.person) : null,
+ })
+ }
+ }
+ return out
+ }
+
+ /**
+ * Person-id to distinct-ids expansion on the primary — the strong
+ * twin of the router RPC of the same name. Grouped per person id;
+ * with a limit, identified ids survive the cut.
+ */
+ async getDistinctIdsForPersons(
+ teamId: number,
+ personIds: string[],
+ limitPerPerson?: number,
+ callerTag?: string
+ ): Promise<Record<string, string[]>> {
+ if (personIds.length === 0) {
+ return {}
+ }
+ const byPerson: Record<string, string[]> = {}
+ for (let i = 0; i < personIds.length; i += IDENTITY_BATCH_SIZE) {
+ const chunk = personIds.slice(i, i + IDENTITY_BATCH_SIZE)
+ const response = await this.client.getDistinctIdsForPersons(
+ create(GetDistinctIdsForPersonsRequestSchema, {
+ teamId: BigInt(teamId),
+ personIds: chunk.map((id) => BigInt(id)),
+ limitPerPerson: limitPerPerson != null ? BigInt(limitPerPerson) : undefined,
+ }),
+ callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined
+ )
+ for (const group of response.personDistinctIds) {
+ byPerson[String(group.personId)] = group.distinctIds.map((d) => d.distinctId)
+ }
+ }
+ return byPerson
+ }
+
+ /**
+ * Resolves the distinct id to its person, creating a stub when
+ * absent. `created` means the stub row is committed in Postgres and
+ * any initial properties are durable in the leader's changelog.
+ */
+ async getOrCreatePersonByDistinctId(
+ entry: GetOrCreatePersonEntry,
+ callerTag?: string
+ ): Promise<{ person: InternalPerson; created: boolean }> {
+ try {
+ const response = await this.client.getOrCreatePersonByDistinctId(
+ create(GetOrCreatePersonByDistinctIdRequestSchema, {
+ entry: {
+ teamId: BigInt(entry.teamId),
+ distinctId: entry.distinctId,
+ extraDistinctIds: entry.extraDistinctIds ?? [],
+ eventName: entry.eventName,
+ setProperties: encodeJsonBytes(entry.setProperties ?? {}),
+ setOnceProperties: encodeJsonBytes(entry.setOnceProperties ?? {}),
+ createdAt: BigInt(entry.createdAtMs),
+ isIdentified: entry.isIdentified ?? false,
+ },
+ }),
+ callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined
+ )
+ if (!response.person) {
+ throw new Error(
+ `identity get-or-create returned no person for team ${entry.teamId} distinct_id ${entry.distinctId}`
+ )
+ }
+ return { person: protoPersonToDomain(response.person), created: response.created }
+ } catch (error) {
+ // A size rejection must surface as the domain error the
+ // create service already handles, which emits the customer
+ // ingestion warning and stops retrying. Left untranslated,
+ // the raw gRPC error matches no non-retriable class and the
+ // batch redelivers the same oversized event forever.
+ if (error instanceof ConnectError && error.code === Code.InvalidArgument) {
+ if (error.rawMessage.includes('size limit')) {
+ throw new PersonPropertiesSizeViolationError(
+ error.rawMessage,
+ entry.teamId,
+ undefined,
+ entry.distinctId
+ )
+ }
+ }
+ throw error
+ }
+ }
+}
diff --git a/nodejs/src/common/personhog/personhog-person-write-repository.ts b/nodejs/src/common/personhog/personhog-person-write-repository.ts
new file mode 100644
index 000000000000..73331c96df58
--- /dev/null
+++ b/nodejs/src/common/personhog/personhog-person-write-repository.ts
@@ -0,0 +1,113 @@
+import { InternalPerson } from '~/types'
+
+import { PersonHogClient } from './client'
+import { withRetry } from './grpc-retry'
+import { DistinctIdKey, GetOrCreatePersonEntry, PersonhogIdentityOperations } from './identity'
+import { timedGrpc } from './metrics'
+import { FoldedPersonUpdate } from './persons'
+
+/**
+ * Write-side person repository backed by personhog gRPC, the
+ * counterpart to PersonHogPersonReadRepository speaking personhog's own
+ * vocabulary rather than the Postgres-shaped contract. No verb touches
+ * the replica: resolution goes to the identity service (primary), person
+ * state and folded updates go through the router to the partition's
+ * leader.
+ *
+ * Two endpoints sit behind it: person operations go through the router;
+ * identity resolution and get-or-create go to the identity server's own
+ * address. The router proxies neither API.
+ *
+ * Every verb is idempotent (folds, get-or-create, reads), so
+ * transient-error retries are safe.
+ */
+export class PersonHogPersonWriteRepository {
+ constructor(
+ private grpcClient: PersonHogClient,
+ private identity: PersonhogIdentityOperations,
+ private clientLabel: string = 'unknown'
+ ) {}
+
+ /**
+ * Primary-backed distinct-id resolution; never creates. Results in
+ * request order, null person for an unresolved key. State freshness
+ * is writer-applied — callers that need the leader's view fetch the
+ * person by id afterwards.
+ */
+ resolvePersonsByDistinctIds(
+ keys: DistinctIdKey[],
+ callerTag?: string
+ ): Promise<{ teamId: number; distinctId: string; person: InternalPerson | null }[]> {
+ const method = 'resolvePersonsByDistinctIds'
+ return withRetry(
+ () => timedGrpc(this.clientLabel, method, () => this.identity.getPersonsByDistinctIds(keys, callerTag)),
+ this.clientLabel,
+ method
+ )
+ }
+
+ /** Leader-routed strong person read; null when deleted or merged away. */
+ fetchPersonById(teamId: number, personId: string, callerTag?: string): Promise<InternalPerson | null> {
+ const method = 'fetchPersonById'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.fetchPersonById(teamId, personId, callerTag, {
+ consistency: 'strong',
+ })
+ ),
+ this.clientLabel,
+ method
+ )
+ }
+
+ /** Applies a folded diff under the leader's per-person lock and returns the person as written. */
+ updatePersonProperties(
+ update: FoldedPersonUpdate,
+ callerTag?: string
+ ): Promise<{ person: InternalPerson | null; updated: boolean }> {
+ const method = 'updatePersonProperties'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.updatePersonProperties(update, callerTag)
+ ),
+ this.clientLabel,
+ method
+ )
+ }
+
+ /** Primary-backed expansion via identity — the merge pre-checks read their own writes. */
+ getDistinctIdsForPersons(
+ teamId: number,
+ personIntIds: string[],
+ limitPerPerson?: number,
+ callerTag?: string
+ ): Promise<Record<string, string[]>> {
+ const method = 'getDistinctIdsForPersons'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.identity.getDistinctIdsForPersons(teamId, personIntIds, limitPerPerson, callerTag)
+ ),
+ this.clientLabel,
+ method
+ )
+ }
+
+ /** Resolution and creation in one idempotent verb; the uuid derives deterministically server-side. */
+ getOrCreatePersonByDistinctId(
+ entry: GetOrCreatePersonEntry,
+ callerTag?: string
+ ): Promise<{ person: InternalPerson; created: boolean }> {
+ const method = 'getOrCreatePersonByDistinctId'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.identity.getOrCreatePersonByDistinctId(entry, callerTag)
+ ),
+ this.clientLabel,
+ method
+ )
+ }
+}
diff --git a/nodejs/src/common/personhog/persons.test.ts b/nodejs/src/common/personhog/persons.test.ts
index 904eb6643f34..f2c0037777ab 100644
--- a/nodejs/src/common/personhog/persons.test.ts
+++ b/nodejs/src/common/personhog/persons.test.ts
@@ -1,14 +1,17 @@
import { create } from '@bufbuild/protobuf'
-import { type ServiceImpl, createClient, createRouterTransport } from '@connectrpc/connect'
+import { Code, ConnectError, type ServiceImpl, createClient, createRouterTransport } from '@connectrpc/connect'
import { PersonHogService } from '~/common/generated/personhog/personhog/service/v1/service_pb'
import { PersonSchema } from '~/common/generated/personhog/personhog/types/v1/person_pb'
import type {
GetPersonsByDistinctIdsRequest,
GetPersonsByUuidsRequest,
+ UpdatePersonPropertiesRequest,
} from '~/common/generated/personhog/personhog/types/v1/person_pb'
+import { parseJSON } from '~/common/utils/json-parse'
+import { NoRowsUpdatedError } from '~/common/utils/utils'
-import { PersonHogPersonOperations } from './persons'
+import { PersonHogPersonOperations, PersonhogPropertiesSizeError } from './persons'
const textEncoder = new TextEncoder()
@@ -182,4 +185,107 @@ describe('PersonHogPersonOperations', () => {
expect(results).toHaveLength(400)
})
})
+
+ describe('updatePersonProperties', () => {
+ it('maps each op onto its own proto field and decodes the response person', async () => {
+ const handler = jest.fn()
+ handler.mockImplementation((req: UpdatePersonPropertiesRequest) => ({
+ person: makeProtoPerson(Number(req.personId), 'uuid-42', Number(req.teamId)),
+ updated: true,
+ }))
+
+ const { ops } = createOperations({ updatePersonProperties: handler })
+ const result = await ops.updatePersonProperties({
+ teamId: 7,
+ personId: '42',
+ eventName: '$folded_person_update',
+ setProperties: { plan: 'pro' },
+ setOnceProperties: { first_seen: '2024-01-01' },
+ unsetProperties: ['stale'],
+ isIdentified: true,
+ lastSeenAtMs: 1700000000000,
+ })
+
+ const req = handler.mock.calls[0][0] as UpdatePersonPropertiesRequest
+ expect(req.teamId).toBe(7n)
+ expect(req.personId).toBe(42n)
+ expect(req.eventName).toBe('$folded_person_update')
+ expect(parseJSON(new TextDecoder().decode(req.setProperties))).toEqual({ plan: 'pro' })
+ expect(parseJSON(new TextDecoder().decode(req.setOnceProperties))).toEqual({
+ first_seen: '2024-01-01',
+ })
+ expect(req.unsetProperties).toEqual(['stale'])
+ expect(req.isIdentified).toBe(true)
+ expect(req.lastSeenAt).toBe(1700000000000n)
+
+ expect(result.updated).toBe(true)
+ expect(result.person?.id).toBe('42')
+ expect(result.person?.uuid).toBe('uuid-42')
+ })
+
+ it('sends empty ops as empty bytes and absent scalars as unset fields', async () => {
+ const handler = jest.fn((_req: UpdatePersonPropertiesRequest) => ({
+ person: makeProtoPerson(1, 'u', 1),
+ updated: false,
+ }))
+
+ const { ops } = createOperations({ updatePersonProperties: handler })
+ await ops.updatePersonProperties({
+ teamId: 1,
+ personId: '1',
+ eventName: '$folded_person_update',
+ setProperties: {},
+ setOnceProperties: {},
+ unsetProperties: [],
+ })
+
+ const req = handler.mock.calls[0][0]
+ expect(req.setProperties).toHaveLength(0)
+ expect(req.setOnceProperties).toHaveLength(0)
+ expect(req.isIdentified).toBeUndefined()
+ expect(req.lastSeenAt).toBeUndefined()
+ })
+
+ it('maps the personhog contract onto domain errors', async () => {
+ const foldedUpdate = {
+ teamId: 7,
+ personId: '42',
+ eventName: '$folded_person_update',
+ setProperties: { a: '1' },
+ setOnceProperties: {},
+ unsetProperties: [],
+ }
+
+ const { ops: notFoundOps } = createOperations({
+ updatePersonProperties: () => {
+ throw new ConnectError('person 42 not found', Code.NotFound)
+ },
+ })
+ await expect(notFoundOps.updatePersonProperties(foldedUpdate)).rejects.toBeInstanceOf(NoRowsUpdatedError)
+
+ const { ops: tooBigOps } = createOperations({
+ updatePersonProperties: () => {
+ throw new ConnectError(
+ 'person properties update would exceed the size limit: 700000 bytes',
+ Code.InvalidArgument
+ )
+ },
+ })
+ const sizeError = await tooBigOps.updatePersonProperties(foldedUpdate).catch((e) => e)
+ expect(sizeError).toBeInstanceOf(PersonhogPropertiesSizeError)
+ expect(sizeError.teamId).toBe(7)
+ expect(sizeError.personId).toBe('42')
+
+ // Codes without a domain meaning pass through untouched for the
+ // caller's generic retry handling.
+ const { ops: unavailableOps } = createOperations({
+ updatePersonProperties: () => {
+ throw new ConnectError('leader unreachable', Code.Unavailable)
+ },
+ })
+ const passthrough = await unavailableOps.updatePersonProperties(foldedUpdate).catch((e) => e)
+ expect(passthrough).toBeInstanceOf(ConnectError)
+ expect(passthrough.code).toBe(Code.Unavailable)
+ })
+ })
})
diff --git a/nodejs/src/common/personhog/persons.ts b/nodejs/src/common/personhog/persons.ts
index 0b08183831c2..7ea6b8487344 100644
--- a/nodejs/src/common/personhog/persons.ts
+++ b/nodejs/src/common/personhog/persons.ts
@@ -1,20 +1,63 @@
import { create } from '@bufbuild/protobuf'
-import { Client } from '@connectrpc/connect'
+import { Client, Code, ConnectError } from '@connectrpc/connect'
import { PersonHogService } from '~/common/generated/personhog/personhog/service/v1/service_pb'
import { TeamDistinctIdSchema } from '~/common/generated/personhog/personhog/types/v1/common_pb'
import {
GetDistinctIdsForPersonsRequestSchema,
+ GetPersonRequestSchema,
GetPersonsByDistinctIdsRequestSchema,
GetPersonsByUuidsRequestSchema,
+ UpdatePersonPropertiesRequestSchema,
} from '~/common/generated/personhog/personhog/types/v1/person_pb'
import type { Person as ProtoPerson } from '~/common/generated/personhog/personhog/types/v1/person_pb'
import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'
+import { NoRowsUpdatedError } from '~/common/utils/utils'
+import { Properties } from '~/plugin-scaffold'
import { InternalPerson } from '~/types'
-import { epochMsToDateTime, eventualReadOptions, parseJsonBytes } from './client'
+import { epochMsToDateTime, eventualReadOptions, parseJsonBytes, strongReadOptions } from './client'
-function protoPersonToDomain(proto: ProtoPerson): InternalPerson {
+const textEncoder = new TextEncoder()
+
+export function encodeJsonBytes(value: object): Uint8Array {
+ return Object.keys(value).length === 0 ? new Uint8Array(0) : textEncoder.encode(JSON.stringify(value))
+}
+
+/**
+ * The leader rejected an update at the person-properties size ceiling.
+ * Carries what the transport layer knows; callers holding the person's
+ * uuid and distinct id re-wrap it into their own error vocabulary.
+ */
+export class PersonhogPropertiesSizeError extends Error {
+ constructor(
+ message: string,
+ public readonly teamId: number,
+ public readonly personId: string
+ ) {
+ super(message)
+ this.name = 'PersonhogPropertiesSizeError'
+ }
+}
+
+/** A folded person-property update, resolved by the leader under the per-person lock. */
+export interface FoldedPersonUpdate {
+ teamId: number
+ /** InternalPerson.id — the bigint row id as a string. */
+ personId: string
+ /** Representative event name; must not be one the leader's denylist filters out. */
+ eventName: string
+ setProperties: Properties
+ /** Unresolved: the leader applies these only where the key is absent in authoritative state. */
+ setOnceProperties: Properties
+ unsetProperties: string[]
+ /** OR-merged server-side; send true only — false and absence are equivalent no-ops. */
+ isIdentified?: boolean
+ /** Epoch milliseconds; max-merged server-side. */
+ lastSeenAtMs?: number
+}
+
+export function protoPersonToDomain(proto: ProtoPerson): InternalPerson {
return {
id: String(proto.id),
uuid: proto.uuid,
@@ -102,6 +145,83 @@ export class PersonHogPersonOperations {
return result
}
+ /**
+ * Person state by id. Eventual reads go to the replica; strong reads
+ * are routed to the partition's leader, whose cache the primary lags
+ * by writer apply lag, so a caller that must observe its own writes
+ * asks for strong. Returns null for a person that does not exist
+ * (deleted, or merged away).
+ */
+ async fetchPersonById(
+ teamId: number,
+ personId: string,
+ callerTag?: string,
+ options?: { consistency?: 'strong' | 'eventual' }
+ ): Promise<InternalPerson | null> {
+ try {
+ const response = await this.client.getPerson(
+ create(GetPersonRequestSchema, {
+ teamId: BigInt(teamId),
+ personId: BigInt(personId),
+ readOptions: options?.consistency === 'strong' ? strongReadOptions() : eventualReadOptions(),
+ }),
+ callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined
+ )
+ return response.person ? protoPersonToDomain(response.person) : null
+ } catch (error) {
+ if (error instanceof ConnectError && error.code === Code.NotFound) {
+ return null
+ }
+ throw error
+ }
+ }
+
+ /**
+ * Apply a folded property update to one person. The leader merges the
+ * diffs into authoritative state under the per-person lock and returns
+ * the person as written, so the caller can publish it downstream.
+ * Returns null person when the response carries none.
+ */
+ async updatePersonProperties(
+ update: FoldedPersonUpdate,
+ callerTag?: string
+ ): Promise<{ person: InternalPerson | null; updated: boolean }> {
+ try {
+ const response = await this.client.updatePersonProperties(
+ create(UpdatePersonPropertiesRequestSchema, {
+ teamId: BigInt(update.teamId),
+ personId: BigInt(update.personId),
+ eventName: update.eventName,
+ setProperties: encodeJsonBytes(update.setProperties),
+ setOnceProperties: encodeJsonBytes(update.setOnceProperties),
+ unsetProperties: update.unsetProperties,
+ isIdentified: update.isIdentified,
+ lastSeenAt: update.lastSeenAtMs != null ? BigInt(update.lastSeenAtMs) : undefined,
+ }),
+ callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined
+ )
+ return {
+ person: response.person ? protoPersonToDomain(response.person) : null,
+ updated: response.updated,
+ }
+ } catch (error) {
+ // Translate the personhog contract into domain errors here so
+ // callers never handle gRPC codes: a missing person (deleted, or
+ // merged away) surfaces as NoRowsUpdatedError, and the leader's
+ // only InvalidArgument for a well-formed request is the
+ // property-size ceiling. Everything else propagates untouched.
+ if (error instanceof ConnectError) {
+ if (error.code === Code.NotFound) {
+ throw new NoRowsUpdatedError(`Person ${update.personId} not found by personhog (deleted or merged)`)
+ }
+ if (error.code === Code.InvalidArgument && error.rawMessage.includes('size limit')) {
+ throw new PersonhogPropertiesSizeError(error.rawMessage, update.teamId, update.personId)
+ }
+ }
+ throw error
+ }
+ }
+
async fetchPersonsByPersonIds(
teamPersons: { teamId: number; personId: string }[],
callerTag?: string
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index 964a64faeeea..27c4a3ad03a0 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -15,6 +15,7 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpu
import { InternalPerson, TeamId } from '~/types'
import { BatchWritingPersonsStore } from './batch-writing-person-store'
+import { EventOps } from './person-update'
import { BatchBoundPersonsStore } from './persons-store-for-batch'
// Mock the ingestion warnings module
@@ -37,6 +38,8 @@ jest.mock('~/common/persons/metrics', () => ({
personMethodCallsPerBatchHistogram: { observe: jest.fn() },
personOptimisticUpdateConflictsPerBatchCounter: { inc: jest.fn() },
personProfileBatchIgnoredPropertiesCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personProfileIgnoredPropertiesCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personProfileUpdateOutcomeCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personProfileBatchUpdateOutcomeCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personPropertyKeyUpdateCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personRetryAttemptsHistogram: { observe: jest.fn() },
@@ -1263,6 +1266,73 @@ describe('BatchWritingPersonStore', () => {
)
})
+ describe('applyEventOps', () => {
+ const ops = (overrides: Partial<EventOps>): EventOps => ({
+ set: {},
+ setOnce: {},
+ unset: [],
+ denied: false,
+ shouldForceUpdate: false,
+ eventName: '$set',
+ ...overrides,
+ })
+
+ it('short-circuits with no write when nothing changes', async () => {
+ const [updated, messages] = await personStore.applyEventOps(
+ person,
+ ops({ set: { test: 'test' } }),
+ 'test-distinct',
+ 0
+ )
+ expect(updated.properties).toEqual({ test: 'test' })
+ expect(messages).toEqual([])
+ await personStore.flush()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
+ expect(mockRepo.updatePersonAssertVersion).not.toHaveBeenCalled()
+ })
+
+ it('a scalar-only change still writes', async () => {
+ const [updated] = await personStore.applyEventOps(person, ops({ isIdentified: true }), 'test-distinct', 0)
+ expect(updated.is_identified).toBe(true)
+ await personStore.flush()
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)
+ })
+
+ it('last-seen only advances', async () => {
+ person.last_seen_at = DateTime.fromMillis(7_200_000, { zone: 'utc' })
+ const [updated, messages] = await personStore.applyEventOps(
+ person,
+ ops({ lastSeenAtMs: 3_600_000 }),
+ 'test-distinct',
+ 0
+ )
+ expect(updated.last_seen_at?.toMillis()).toBe(7_200_000)
+ expect(messages).toEqual([])
+ await personStore.flush()
+ expect(mockRepo.updatePersonsBatch).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [false, 0],
+ [true, 1],
+ ])(
+ 'a filtered-only change writes exactly when the ops carry force (force=%s)',
+ async (force, expectedWrites) => {
+ // The suppression applies only to changes of existing
+ // filtered keys — a new key always writes — so the person
+ // must already carry the property.
+ person.properties.$browser = 'Firefox'
+ const filtered = ops({
+ set: { $browser: 'Chrome' },
+ shouldForceUpdate: force,
+ })
+ await personStore.applyEventOps(person, filtered, 'test-distinct', 0)
+ await personStore.flush()
+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(expectedWrites)
+ }
+ )
+ })
+
describe('moveDistinctIds', () => {
it('should preserve cached merged properties when moving distinct IDs', async () => {
const mockRepo = createMockRepository()
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index 38d666ed4f76..a39d7bbf6363 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -40,7 +40,13 @@ import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
import { PersonOutputs } from './person-context'
-import { getMetricKey } from './person-update'
+import {
+ EventOps,
+ applyEventPropertyUpdates,
+ computeOpsScalarUpdates,
+ getMetricKey,
+ refineEventOps,
+} from './person-update'
import { FlushResult, PersonsStore } from './persons-store'
import { PersonsStoreTransaction } from './persons-store-transaction'
@@ -1317,6 +1323,39 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return Promise.resolve(this.addPersonUpdateToBatch(person, update, distinctId, batchId))
}
+ async applyEventOps(
+ person: InternalPerson,
+ ops: EventOps,
+ distinctId: string,
+ batchId: number
+ ): Promise<[InternalPerson, PersonMessage[]]> {
+ person.properties ||= {}
+
+ // Snapshot refinement is this store's write-shape preparation:
+ // set_once resolves against current properties, sets are diffed,
+ // and the ignored-property rules classify the outcome. The
+ // intents refine here too — identification only transitions
+ // false→true, last-seen only advances.
+ const refined = refineEventOps(ops, person.properties, this.options.updateAllProperties)
+ const otherUpdates = computeOpsScalarUpdates(ops, person)
+
+ if (!refined.hasChanges && Object.keys(otherUpdates).length === 0) {
+ const [updatedPerson] = applyEventPropertyUpdates(refined, person)
+ return [updatedPerson, []]
+ }
+
+ const [updatedPerson, kafkaMessages] = await this.updatePersonWithPropertiesDiffForUpdate(
+ person,
+ refined.toSet,
+ refined.toUnset,
+ otherUpdates,
+ distinctId,
+ batchId,
+ refined.shouldForceUpdate
+ )
+ return [updatedPerson, kafkaMessages]
+ }
+
updatePersonWithPropertiesDiffForUpdate(
person: InternalPerson,
propertiesToSet: Properties,
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 49c7219e19b6..d4ee00680b45 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -29,7 +29,7 @@ import {
mergeError,
mergeSuccess,
} from './person-merge-types'
-import { applyEventPropertyUpdates, computeEventPropertyUpdates } from './person-update'
+import { applyEventPropertyUpdates, extractEventOps, refineEventOps } from './person-update'
import { lifecycleOpIdFromEvent } from './person-uuid'
import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'
@@ -571,8 +571,8 @@ export class PersonMergeService {
for (const source of mergeSources) {
mergedProperties = { ...source.properties, ...mergedProperties }
}
- const propertyUpdates = computeEventPropertyUpdates(
- this.context.event,
+ const propertyUpdates = refineEventOps(
+ extractEventOps(this.context.event, this.context.updateAllProperties),
mergedProperties,
this.context.updateAllProperties
)
@@ -735,8 +735,8 @@ export class PersonMergeService {
// we're calling aliasDeprecated as we need to refresh the persons info completely first
const mergedProperties: Properties = { ...otherPerson.properties, ...mergeInto.properties }
- const propertyUpdates = computeEventPropertyUpdates(
- this.context.event,
+ const propertyUpdates = refineEventOps(
+ extractEventOps(this.context.event, this.context.updateAllProperties),
mergedProperties,
this.context.updateAllProperties
)
diff --git a/nodejs/src/ingestion/common/persons/person-property-service.ts b/nodejs/src/ingestion/common/persons/person-property-service.ts
index 3b669dd1bb3b..862078ec010f 100644
--- a/nodejs/src/ingestion/common/persons/person-property-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-property-service.ts
@@ -4,7 +4,7 @@ import { InternalPerson } from '~/types'
import { PersonContext } from './person-context'
import { PersonCreateService } from './person-create-service'
-import { applyEventPropertyUpdates, computeEventPropertyUpdates } from './person-update'
+import { extractEventOps } from './person-update'
/**
* Service responsible for handling person property updates and person creation.
@@ -71,42 +71,25 @@ export class PersonPropertyService {
async updatePersonProperties(person: InternalPerson): Promise<[InternalPerson, Promise<void>]> {
person.properties ||= {}
- // Compute property changes
- const propertyUpdates = computeEventPropertyUpdates(
- this.context.event,
- person.properties,
- this.context.updateAllProperties
- )
-
- const otherUpdates: Partial<InternalPerson> = {}
- if (this.context.updateIsIdentified && !person.is_identified) {
- otherUpdates.is_identified = true
+ // The service states the event's intent; what the intent means
+ // given current state — diffing, identity OR-merge, last-seen
+ // advance, whether anything is worth writing — is the store's
+ // concern, resolved against its own world.
+ const ops = extractEventOps(this.context.event, this.context.updateAllProperties)
+ if (this.context.updateIsIdentified) {
+ ops.isIdentified = true
}
-
if (
this.context.shouldUpdateLastSeenAt &&
this.context.eventProperties['$update_person_last_seen_at'] !== false
) {
- const roundedTimestamp = this.context.timestamp.startOf('hour')
- if (!person.last_seen_at || roundedTimestamp > person.last_seen_at) {
- otherUpdates.last_seen_at = roundedTimestamp
- }
- }
-
- // Check if we have any changes to make
- const hasChanges = propertyUpdates.hasChanges || Object.keys(otherUpdates).length > 0
- if (!hasChanges) {
- const [updatedPerson, _] = applyEventPropertyUpdates(propertyUpdates, person)
- return [updatedPerson, Promise.resolve()]
+ ops.lastSeenAtMs = this.context.timestamp.startOf('hour').toMillis()
}
- const [updatedPerson, kafkaMessages] = await this.context.personStore.updatePersonWithPropertiesDiffForUpdate(
+ const [updatedPerson, kafkaMessages] = await this.context.personStore.applyEventOps(
person,
- propertyUpdates.toSet,
- propertyUpdates.toUnset,
- otherUpdates,
- this.context.distinctId,
- propertyUpdates.shouldForceUpdate
+ ops,
+ this.context.distinctId
)
const kafkaAck = this.context.produceMessages(kafkaMessages)
return [updatedPerson, kafkaAck]
diff --git a/nodejs/src/ingestion/common/persons/person-update.test.ts b/nodejs/src/ingestion/common/persons/person-update.test.ts
index 32d4914981b2..8d9c2291753c 100644
--- a/nodejs/src/ingestion/common/persons/person-update.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-update.test.ts
@@ -1,8 +1,24 @@
+import { DateTime } from 'luxon'
+
import { personProfileIgnoredPropertiesCounter, personProfileUpdateOutcomeCounter } from '~/common/persons/metrics'
import { FILTERED_PERSON_UPDATE_PROPERTIES } from '~/common/persons/person-property-utils'
import { PluginEvent } from '~/plugin-scaffold'
-
-import { applyEventPropertyUpdates, computeEventPropertyUpdates } from './person-update'
+import { Properties } from '~/plugin-scaffold'
+import { InternalPerson } from '~/types'
+
+import {
+ EventOps,
+ applyEventPropertyUpdates,
+ computeOpsScalarUpdates,
+ extractEventOps,
+ foldOps,
+ refineEventOps,
+} from './person-update'
+
+// The scenarios below exercise the extract → refine pair end to end, the
+// same composition the Postgres store runs per event.
+const computeEventPropertyUpdates = (event: PluginEvent, personProperties: Properties, updateAllProperties = false) =>
+ refineEventOps(extractEventOps(event, updateAllProperties), personProperties, updateAllProperties)
jest.mock('~/common/persons/metrics', () => ({
personProfileUpdateOutcomeCounter: {
@@ -153,6 +169,21 @@ describe('person-update', () => {
}
)
+ it('surfaces the filtered-only verdict for store-side suppression', () => {
+ const filteredOnly = computeEventPropertyUpdates(
+ { event: 'pageview', properties: { $set: { $browser: 'Chrome' } } } as any,
+ { $browser: 'Firefox' }
+ )
+ expect(filteredOnly.hasChanges).toBe(true)
+ expect(filteredOnly.hasNonFilteredChanges).toBe(false)
+
+ const newKey = computeEventPropertyUpdates(
+ { event: 'pageview', properties: { $set: { $browser: 'Chrome' } } } as any,
+ {}
+ )
+ expect(newKey.hasNonFilteredChanges).toBe(true)
+ })
+
it('should accept blocked $geoip_* property updates at event level (filtering happens at batch level)', () => {
const event: PluginEvent = {
event: 'pageview',
@@ -634,6 +665,7 @@ describe('person-update', () => {
toSet: { name: 'John', email: '[email protected]' },
toUnset: ['old_prop'],
shouldForceUpdate: false,
+ hasNonFilteredChanges: true,
}
const person = {
@@ -659,6 +691,7 @@ describe('person-update', () => {
toSet: { name: 'John' },
toUnset: [],
shouldForceUpdate: false,
+ hasNonFilteredChanges: true,
}
const person = {
@@ -684,6 +717,7 @@ describe('person-update', () => {
toSet: { name: 'John' },
toUnset: [],
shouldForceUpdate: false,
+ hasNonFilteredChanges: false,
}
const person = {
@@ -701,4 +735,319 @@ describe('person-update', () => {
expect(wasUpdated).toBe(false)
})
})
+
+ describe('computeOpsScalarUpdates', () => {
+ const personState = (overrides: Partial<InternalPerson>): InternalPerson =>
+ ({ properties: {}, is_identified: false, last_seen_at: null, ...overrides }) as unknown as InternalPerson
+
+ const ops = (overrides: Partial<EventOps>): EventOps => ({
+ set: {},
+ setOnce: {},
+ unset: [],
+ denied: false,
+ shouldForceUpdate: false,
+ eventName: '$set',
+ ...overrides,
+ })
+
+ it.each([
+ ['identifies an unidentified person', { isIdentified: true }, {}, { is_identified: true }],
+ ['does not re-identify an identified person', { isIdentified: true }, { is_identified: true }, {}],
+ ['never reverts identification', {}, { is_identified: true }, {}],
+ ] as [string, Partial<EventOps>, Partial<InternalPerson>, Partial<InternalPerson>][])(
+ '%s',
+ (_label, opOverrides, personOverrides, expected) => {
+ expect(computeOpsScalarUpdates(ops(opOverrides), personState(personOverrides))).toEqual(expected)
+ }
+ )
+
+ it('advances last_seen_at only forward', () => {
+ const older = DateTime.fromMillis(3_600_000, { zone: 'utc' })
+ const newer = DateTime.fromMillis(7_200_000, { zone: 'utc' })
+ const seenAt = personState({ last_seen_at: older } as unknown as Partial<InternalPerson>)
+
+ expect(computeOpsScalarUpdates(ops({ lastSeenAtMs: 7_200_000 }), seenAt)).toEqual({
+ last_seen_at: newer,
+ })
+ const current = personState({ last_seen_at: newer } as unknown as Partial<InternalPerson>)
+ expect(computeOpsScalarUpdates(ops({ lastSeenAtMs: 3_600_000 }), current)).toEqual({})
+ })
+
+ it('denied ops still contribute their scalars', () => {
+ // The denylist gates property writes only; both stores and
+ // the leader advance identity and last-seen regardless.
+ const updates = computeOpsScalarUpdates(
+ ops({ denied: true, isIdentified: true, lastSeenAtMs: 3_600_000 }),
+ personState({})
+ )
+ expect(updates.is_identified).toBe(true)
+ expect(updates.last_seen_at?.toMillis()).toBe(3_600_000)
+ })
+ })
+
+ describe('fold equivalence', () => {
+ // Deterministic PRNG (mulberry32): the sweep must reproduce
+ // identically on every run.
+ const mulberry32 = (seed: number) => (): number => {
+ seed = (seed + 0x6d2b79f5) | 0
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+
+ const KEYS = ['k1', 'k2', 'k3']
+
+ const randomProps = (rand: () => number): Record<string, string> =>
+ Object.fromEntries(KEYS.filter(() => rand() < 0.4).map((k) => [k, `v${Math.floor(rand() * 4)}`]))
+
+ const randomOps = (rand: () => number): EventOps => {
+ const set = randomProps(rand)
+ const setOnce = Object.fromEntries(Object.entries(randomProps(rand)).filter(([k]) => !(k in set)))
+ return {
+ set,
+ // extractEventOps guarantees an event's set_once keys are
+ // not among its set keys; the generator upholds the same
+ // invariant so the sweep covers reachable shapes only.
+ setOnce,
+ unset: KEYS.filter(() => rand() < 0.25),
+ denied: false,
+ shouldForceUpdate: false,
+ isIdentified: rand() < 0.2 ? true : undefined,
+ lastSeenAtMs: rand() < 0.3 ? 3_600_000 * (1 + Math.floor(rand() * 3)) : undefined,
+ eventName: '$set',
+ }
+ }
+
+ const personWith = (properties: Record<string, string>): InternalPerson =>
+ ({ properties, is_identified: false }) as unknown as InternalPerson
+
+ // This is the algebra the personhog store stakes its correctness
+ // on: folding a person's ops across a batch and refining the
+ // fold once must land on the same state as refining each event
+ // sequentially against evolving state, for every interleaving of
+ // set, set_once, and unset over shared keys.
+ it('folding into segments then refining each matches refining every op sequentially', () => {
+ const rand = mulberry32(20260807)
+ let segmentedRounds = 0
+ for (let round = 0; round < 500; round++) {
+ const baseProps = randomProps(rand)
+ const opsList = Array.from({ length: 2 + Math.floor(rand() * 4) }, () => randomOps(rand))
+
+ let sequential = personWith({ ...baseProps })
+ let seqIdentified = false
+ let seqLastSeen: number | null = null
+ for (const o of opsList) {
+ const refined = refineEventOps(o, sequential.properties, false)
+ ;[sequential] = applyEventPropertyUpdates(refined, sequential)
+ seqIdentified = seqIdentified || o.isIdentified === true
+ if (o.lastSeenAtMs !== undefined) {
+ seqLastSeen = Math.max(seqLastSeen ?? 0, o.lastSeenAtMs)
+ }
+ }
+
+ // Exactly the store's lane discipline: fold onto the last
+ // segment, cut a new one when the composition is not
+ // representable, ship segments in order.
+ const segments: EventOps[] = [opsList[0]]
+ for (const o of opsList.slice(1)) {
+ const folded = foldOps(segments[segments.length - 1], o)
+ if (folded === null) {
+ segments.push(o)
+ } else {
+ segments[segments.length - 1] = folded
+ }
+ }
+ if (segments.length > 1) {
+ segmentedRounds++
+ }
+
+ let candidate = personWith({ ...baseProps })
+ let candIdentified = false
+ let candLastSeen: number | null = null
+ for (const seg of segments) {
+ const refined = refineEventOps(seg, candidate.properties, false)
+ ;[candidate] = applyEventPropertyUpdates(refined, candidate)
+ candIdentified = candIdentified || seg.isIdentified === true
+ if (seg.lastSeenAtMs !== undefined) {
+ candLastSeen = Math.max(candLastSeen ?? 0, seg.lastSeenAtMs)
+ }
+ }
+
+ const context = { round, baseProps, opsList }
+ expect({ ...context, out: candidate.properties }).toEqual({
+ ...context,
+ out: sequential.properties,
+ })
+ expect(candIdentified).toBe(seqIdentified)
+ expect(candLastSeen).toBe(seqLastSeen)
+ }
+ // The sweep must actually exercise the segmentation path, or
+ // the null branch is dead weight it never validates.
+ expect(segmentedRounds).toBeGreaterThan(0)
+ })
+ })
+
+ describe('foldOps', () => {
+ const eventOps = (properties: Record<string, unknown>, event = '$set') =>
+ extractEventOps({ event, properties } as any)
+
+ const fold = (existing: EventOps, incoming: EventOps): EventOps => {
+ const folded = foldOps(existing, incoming)
+ expect(folded).not.toBeNull()
+ return folded!
+ }
+
+ it('preserves sequential semantics per key across folded events', () => {
+ // set shadows a pending set_once; among set_onces the first
+ // wins; an unset clears both lanes; a set_once after an unset
+ // becomes an unconditional set.
+ let acc = eventOps({ $set_once: { plan: 'first', keep: 'kept' } })
+ acc = fold(acc, eventOps({ $set: { plan: 'shadowing' }, $set_once: { keep: 'second-loses' } }))
+ acc = fold(acc, eventOps({ $unset: ['gone', 'revived'] }))
+ acc = fold(acc, eventOps({ $set_once: { revived: 'promoted' } }))
+
+ expect(acc.set).toEqual({ plan: 'shadowing', revived: 'promoted' })
+ expect(acc.setOnce).toEqual({ keep: 'kept' })
+ expect(acc.unset).toEqual(['gone'])
+ })
+
+ it('a later set supersedes a pending unset for its key', () => {
+ const acc = fold(eventOps({ $unset: ['a'] }), eventOps({ $set: { a: 'back' } }))
+ expect(acc.set).toEqual({ a: 'back' })
+ expect(acc.unset).toEqual([])
+ })
+
+ it('a same-event value and unset pair rides the fold whole', () => {
+ // The pair's outcome is snapshot-dependent (present resolves
+ // to gone, absent to the value), so both lanes must survive
+ // for refinement to decide — dropping either loses one branch.
+ const acc = fold(eventOps({ $set: { other: 'x' } }), eventOps({ $set_once: { k: 'v' }, $unset: ['k'] }))
+ expect(acc.setOnce).toEqual({ k: 'v' })
+ expect(acc.unset).toEqual(['k'])
+ })
+
+ it('a pair over pending value state resolves to a plain unset', () => {
+ // Pending state guarantees the key present at refinement, so
+ // the pair's present branch (gone) is the only reachable one.
+ const acc = fold(eventOps({ $set: { k: 'pending' } }), eventOps({ $set_once: { k: 'v' }, $unset: ['k'] }))
+ expect(acc.set).toEqual({})
+ expect(acc.setOnce).toEqual({})
+ expect(acc.unset).toEqual(['k'])
+ })
+
+ it.each([
+ ['a set_once', { $set_once: { k: 'later' } }],
+ ['another pair', { $set_once: { k: 'later' }, $unset: ['k'] }],
+ ])('%s over a pending pair cuts a segment', (_label, later) => {
+ // "Present resolves one way, absent another with a different
+ // value" has no lane representation; the caller must ship the
+ // accumulated ops and fold onward from the incoming event.
+ const pair = eventOps({ $set_once: { k: 'v' }, $unset: ['k'] })
+ expect(foldOps(pair, eventOps(later))).toBeNull()
+ })
+
+ it('identity ORs and last-seen max-merges, mirroring the leader', () => {
+ const first = eventOps({})
+ first.isIdentified = true
+ first.lastSeenAtMs = 7_200_000
+ const second = eventOps({})
+ second.lastSeenAtMs = 3_600_000
+
+ const acc = fold(first, second)
+ expect(acc.isIdentified).toBe(true)
+ expect(acc.lastSeenAtMs).toEqual(7_200_000)
+ })
+
+ it('denied events contribute nothing in either direction', () => {
+ const denied = eventOps({ $set: { a: '1' } }, '$exception')
+ const real = eventOps({ $set: { b: '2' } })
+ expect(foldOps(real, denied)).toEqual(real)
+ expect(foldOps(denied, real)).toEqual(real)
+ })
+
+ describe('exhaustive single-key transition table', () => {
+ const K = 'k'
+ type Shape = Record<string, unknown> | null
+ // Every reachable accumulated state, named by the ops that
+ // produce it, and every per-key shape one event can carry.
+ const STATES: [string, Shape][] = [
+ ['empty', null],
+ ['pending set', { $set: { [K]: 'p-set' } }],
+ ['pending set_once', { $set_once: { [K]: 'p-once' } }],
+ ['pending unset', { $unset: [K] }],
+ ['pending set pair', { $set: { [K]: 'p-pair' }, $unset: [K] }],
+ ['pending set_once pair', { $set_once: { [K]: 'p-pair' }, $unset: [K] }],
+ ]
+ const INCOMING: [string, Record<string, unknown>][] = [
+ ['set', { $set: { [K]: 'i-set' } }],
+ ['set_once', { $set_once: { [K]: 'i-once' } }],
+ ['unset', { $unset: [K] }],
+ ['set pair', { $set: { [K]: 'i-pair' }, $unset: [K] }],
+ ['set_once pair', { $set_once: { [K]: 'i-pair' }, $unset: [K] }],
+ ]
+ // The pair state is the one place composition can lose
+ // information, and only under an incoming op that is itself
+ // snapshot-dependent for the key.
+ const SEGMENTS = new Set(
+ ['pending set pair', 'pending set_once pair'].flatMap((s) =>
+ ['set_once', 'set pair', 'set_once pair'].map((i) => `${s}|${i}`)
+ )
+ )
+ const CASES = STATES.flatMap(([stateLabel, stateProps]) =>
+ INCOMING.flatMap(([inLabel, inProps]) =>
+ [
+ ['absent', {}],
+ ['present', { [K]: 'existing' }],
+ ].map(([snapLabel, snapshot]) => [stateLabel, inLabel, snapLabel, stateProps, inProps, snapshot])
+ )
+ ) as [string, string, string, Shape, Record<string, unknown>, Properties][]
+
+ const applySequentially = (events: Record<string, unknown>[], snapshot: Properties): Properties => {
+ let personState = { properties: { ...snapshot }, is_identified: false } as unknown as InternalPerson
+ for (const properties of events) {
+ const refined = refineEventOps(eventOps(properties), personState.properties, false)
+ ;[personState] = applyEventPropertyUpdates(refined, personState)
+ }
+ return personState.properties
+ }
+
+ it.each(CASES)(
+ '%s then %s over %s key: fold matches sequential refinement',
+ (stateLabel, inLabel, _snapLabel, stateProps, inProps, snapshot) => {
+ const events = stateProps === null ? [inProps] : [stateProps, inProps]
+ const sequential = applySequentially(events, snapshot)
+
+ const accumulated = eventOps(stateProps ?? {})
+ const folded = foldOps(accumulated, eventOps(inProps))
+
+ if (folded === null) {
+ expect(SEGMENTS.has(`${stateLabel}|${inLabel}`)).toBe(true)
+ // A cut segment ships each side as its own leader
+ // call, which is the sequential application above
+ // by construction — nothing further to assert.
+ return
+ }
+ expect(SEGMENTS.has(`${stateLabel}|${inLabel}`)).toBe(false)
+ let personState = { properties: { ...snapshot }, is_identified: false } as unknown as InternalPerson
+ const refined = refineEventOps(folded, personState.properties, false)
+ ;[personState] = applyEventPropertyUpdates(refined, personState)
+ expect(personState.properties).toEqual(sequential)
+ }
+ )
+ })
+
+ it('a denied event still contributes its identity and last-seen scalars', () => {
+ // The denylist gates property writes only; both stores and
+ // the leader advance the scalars regardless of event kind.
+ const denied = eventOps({ $set: { a: '1' } }, '$exception')
+ denied.lastSeenAtMs = 7_200_000
+ denied.isIdentified = true
+ const real = eventOps({ $set: { b: '2' } })
+
+ const acc = fold(real, denied)
+ expect(acc.set).toEqual(real.set)
+ expect(acc.isIdentified).toBe(true)
+ expect(acc.lastSeenAtMs).toBe(7_200_000)
+ })
+ })
})
diff --git a/nodejs/src/ingestion/common/persons/person-update.ts b/nodejs/src/ingestion/common/persons/person-update.ts
index ae48bb29c860..afc9328a2201 100644
--- a/nodejs/src/ingestion/common/persons/person-update.ts
+++ b/nodejs/src/ingestion/common/persons/person-update.ts
@@ -1,3 +1,5 @@
+import { DateTime } from 'luxon'
+
import { personProfileIgnoredPropertiesCounter, personProfileUpdateOutcomeCounter } from '~/common/persons/metrics'
import {
eventToPersonProperties,
@@ -14,6 +16,40 @@ export interface PropertyUpdates {
toUnset: string[]
hasChanges: boolean
shouldForceUpdate: boolean // True for PERSON_EVENTS ($identify, $set, etc.) to bypass batch-level filtering
+ /**
+ * Whether any surviving change is one the ignored-property rules
+ * count as update-worthy: a new key, an unset, a non-filtered value
+ * change, or anything at all under force or update-all. False with
+ * hasChanges true is the filtered-only shape a store may suppress.
+ */
+ hasNonFilteredChanges: boolean
+}
+
+/**
+ * What one event asks of a person, extracted without consulting person
+ * state: the ops as the event stated them. Interpretation of the event
+ * (denylist, force semantics) happens here; what the ops mean given
+ * current state is each store's concern. The Postgres store refines them
+ * against its snapshot; the personhog store ships them for the leader to
+ * resolve authoritatively.
+ */
+export interface EventOps {
+ /** $set values, as stated on the event. */
+ set: Properties
+ /** $set_once values for keys not shadowed by a $set on the same event. */
+ setOnce: Properties
+ /** $unset keys. */
+ unset: string[]
+ /** The event kind never writes person properties ($exception, $$heatmap). */
+ denied: boolean
+ /** PERSON_EVENTS or updateAllProperties — bypasses batch-level filtering. */
+ shouldForceUpdate: boolean
+ /** The event asserts identity; OR-merged, never reverts. Set by the caller from event-kind context. */
+ isIdentified?: boolean
+ /** Hour-truncated last-seen candidate, epoch ms; max-merged. Set by the caller from its context. */
+ lastSeenAtMs?: number
+ /** The event name, for the leader's denylist and metrics attribution. */
+ eventName: string
}
// These events are processed in a separate pipeline, so we don't allow person property updates
@@ -37,30 +73,84 @@ export function getMetricKey(key: string): string {
}
/**
- * Computes property changes from an event without modifying personProperties
- * @param event The event to extract property changes from
- * @param personProperties Current person properties (not modified)
- * @param updateAllProperties When true, all property changes trigger updates (no filtering)
- * @returns Object with properties to set, unset, and whether there are changes
+ * Extracts what an event asks of a person, without consulting person state.
+ * A $set shadows a $set_once for the same key within the event (the set
+ * would win at application anyway), and an event on the denylist yields
+ * empty ops with `denied` set.
*/
-export function computeEventPropertyUpdates(
- event: PluginEvent,
- personProperties: Properties,
- updateAllProperties: boolean = false
-): PropertyUpdates {
+export function extractEventOps(event: PluginEvent, updateAllProperties: boolean = false): EventOps {
if (NO_PERSON_UPDATE_EVENTS.has(event.event)) {
personProfileUpdateOutcomeCounter.labels({ outcome: 'unsupported' }).inc()
- return { hasChanges: false, toSet: {}, toUnset: [], shouldForceUpdate: false }
+ return {
+ set: {},
+ setOnce: {},
+ unset: [],
+ denied: true,
+ shouldForceUpdate: false,
+ eventName: event.event,
+ }
}
- // Check if this is a PERSON_EVENT that should bypass batch-level filtering
- // Also force update when updateAllProperties is enabled
- const shouldForceUpdate = PERSON_EVENTS.has(event.event) || updateAllProperties
-
- const properties: Properties = event.properties!['$set'] || {}
- const propertiesOnce: Properties = event.properties!['$set_once'] || {}
+ const set: Properties = { ...(event.properties!['$set'] || {}) }
+ const setOnce: Properties = {}
+ Object.entries((event.properties!['$set_once'] || {}) as Properties).forEach(([key, value]) => {
+ if (!(key in set)) {
+ setOnce[key] = value
+ }
+ })
const unsetProps = event.properties!['$unset']
- const unsetProperties: Array<string> = Array.isArray(unsetProps) ? unsetProps : Object.keys(unsetProps || {}) || []
+ const unset: string[] = (Array.isArray(unsetProps) ? unsetProps : Object.keys(unsetProps || {})).filter(
+ (key): key is string => typeof key === 'string'
+ )
+
+ return {
+ set,
+ setOnce,
+ unset,
+ denied: false,
+ shouldForceUpdate: PERSON_EVENTS.has(event.event) || updateAllProperties,
+ eventName: event.event,
+ }
+}
+
+/**
+ * Refines extracted ops against a person-properties snapshot into the
+ * Postgres write shape: set_once resolves locally (only absent keys
+ * survive, as sets), sets are filtered to values that differ, unsets to
+ * keys that exist, and the ignored-property rules decide whether the
+ * surviving changes deserve a write. The personhog flush path never
+ * calls this; the leader refines authoritatively on its side.
+ */
+/**
+ * The scalar half of an op against current person state: identity ORs
+ * (never reverts) and last-seen max-advances, the same merge the leader
+ * performs. Returns only the fields that change, so callers can both
+ * gate on "anything to write" and apply the delta. Deliberately
+ * indifferent to `ops.denied`: the denylist gates property writes only.
+ */
+export function computeOpsScalarUpdates(ops: EventOps, person: InternalPerson): Partial<InternalPerson> {
+ const updates: Partial<InternalPerson> = {}
+ if (ops.isIdentified && !person.is_identified) {
+ updates.is_identified = true
+ }
+ if (ops.lastSeenAtMs !== undefined) {
+ const candidate = DateTime.fromMillis(ops.lastSeenAtMs, { zone: 'utc' })
+ if (!person.last_seen_at || candidate > person.last_seen_at) {
+ updates.last_seen_at = candidate
+ }
+ }
+ return updates
+}
+
+export function refineEventOps(
+ ops: EventOps,
+ personProperties: Properties,
+ updateAllProperties: boolean = false,
+ recordOutcomes: boolean = true
+): PropertyUpdates {
+ if (ops.denied) {
+ return { hasChanges: false, toSet: {}, toUnset: [], shouldForceUpdate: false, hasNonFilteredChanges: false }
+ }
let hasChanges = false
let hasNonFilteredChanges = false
@@ -68,11 +158,11 @@ export function computeEventPropertyUpdates(
const toUnset: string[] = []
const ignoredProperties: string[] = []
- Object.entries(propertiesOnce).forEach(([key, value]) => {
+ Object.entries(ops.setOnce).forEach(([key, value]) => {
if (typeof personProperties[key] === 'undefined') {
hasChanges = true
toSet[key] = value
- if (shouldUpdatePersonIfOnlyChange(event, key, updateAllProperties)) {
+ if (shouldUpdatePersonIfOnlyChange(ops, key, updateAllProperties)) {
hasNonFilteredChanges = true
}
}
@@ -83,11 +173,11 @@ export function computeEventPropertyUpdates(
let anyPropertyTriggersUpdate = false
const changedProperties: Array<[string, unknown]> = []
- Object.entries(properties).forEach(([key, value]) => {
+ Object.entries(ops.set).forEach(([key, value]) => {
if (personProperties[key] !== value) {
changedProperties.push([key, value])
const isNewProperty = typeof personProperties[key] === 'undefined'
- if (isNewProperty || shouldUpdatePersonIfOnlyChange(event, key, updateAllProperties)) {
+ if (isNewProperty || shouldUpdatePersonIfOnlyChange(ops, key, updateAllProperties)) {
anyPropertyTriggersUpdate = true
}
}
@@ -104,18 +194,19 @@ export function computeEventPropertyUpdates(
toSet[key] = value
})
- unsetProperties.forEach((propertyKey) => {
+ ops.unset.forEach((propertyKey) => {
if (propertyKey in personProperties) {
- if (typeof propertyKey === 'string') {
- hasChanges = true
- hasNonFilteredChanges = true
- toUnset.push(propertyKey)
- }
+ hasChanges = true
+ hasNonFilteredChanges = true
+ toUnset.push(propertyKey)
}
})
- // Track person profile update outcomes at event level (skip when updateAllProperties is enabled)
- if (!updateAllProperties) {
+ // Track person profile update outcomes at event level (skip when
+ // updateAllProperties is enabled, or when the caller is projecting
+ // rather than deciding a write — a projection re-refining the same
+ // event must not double-count the outcome).
+ if (!updateAllProperties && recordOutcomes) {
const hasPropertyChanges = Object.keys(toSet).length > 0 || toUnset.length > 0
if (hasPropertyChanges) {
if (hasNonFilteredChanges) {
@@ -131,7 +222,147 @@ export function computeEventPropertyUpdates(
}
}
- return { hasChanges, toSet, toUnset, shouldForceUpdate }
+ return { hasChanges, toSet, toUnset, shouldForceUpdate: ops.shouldForceUpdate, hasNonFilteredChanges }
+}
+
+/**
+ * Folds a later event's ops onto accumulated ops for the same person,
+ * preserving sequential semantics per key: a set wins over any prior
+ * state, the first set_once wins, an unset clears prior lanes, and a
+ * value after an unset applies unconditionally (the key is definitely
+ * absent). Identity ORs and last-seen max-merges, mirroring the leader's
+ * merge rules.
+ *
+ * One event may pair an unset with a set or set_once of the same key.
+ * Refinement resolves that pair against the snapshot (present means
+ * gone, absent means the value lands), so the fold keeps both lanes as
+ * a unit. A key's accumulated state is therefore a value, an unset, or
+ * a snapshot-dependent pair.
+ *
+ * Returns null when composition would lose information: a later
+ * set_once over a key already in the pair state needs "present resolves
+ * one way, absent another with a different value", which no lane
+ * combination expresses. The caller then cuts a segment, shipping the
+ * accumulated ops as their own leader call so authoritative refinement
+ * happens between the two.
+ */
+export function foldOps(existing: EventOps, incoming: EventOps): EventOps | null {
+ if (incoming.denied || existing.denied) {
+ // The denylist gates property writes only — identity and
+ // last-seen advance regardless, matching both stores and the
+ // leader. A denied op contributes its scalars and nothing else.
+ const base = incoming.denied ? existing : incoming
+ return {
+ ...base,
+ isIdentified: existing.isIdentified || incoming.isIdentified ? true : undefined,
+ lastSeenAtMs: mergeLastSeenMs(existing.lastSeenAtMs, incoming.lastSeenAtMs),
+ }
+ }
+
+ const states = keyStates(existing)
+ for (const [key, op] of keyStates(incoming)) {
+ const next = foldKey(states.get(key), op)
+ if (next === null) {
+ return null
+ }
+ states.set(key, next)
+ }
+
+ const set: Properties = {}
+ const setOnce: Properties = {}
+ const unset: string[] = []
+ for (const [key, state] of states) {
+ if (state.kind === 'unset' || state.kind === 'pair') {
+ unset.push(key)
+ }
+ if (state.kind === 'value' || state.kind === 'pair') {
+ ;(state.lane === 'set' ? set : setOnce)[key] = state.value
+ }
+ }
+
+ return {
+ set,
+ setOnce,
+ unset,
+ denied: false,
+ shouldForceUpdate: existing.shouldForceUpdate || incoming.shouldForceUpdate,
+ isIdentified: existing.isIdentified || incoming.isIdentified ? true : undefined,
+ lastSeenAtMs: mergeLastSeenMs(existing.lastSeenAtMs, incoming.lastSeenAtMs),
+ eventName: incoming.eventName,
+ }
+}
+
+/**
+ * One key's accumulated (or incoming) state: a pending value in one of
+ * the two lanes, a pending unset, or the snapshot-dependent pair of
+ * both from a single event.
+ */
+type KeyState =
+ | { kind: 'value'; lane: 'set' | 'setOnce'; value: unknown }
+ | { kind: 'unset' }
+ | { kind: 'pair'; lane: 'set' | 'setOnce'; value: unknown }
+
+/** An EventOps decomposed per key, in set, setOnce, unset order. */
+function keyStates(ops: EventOps): Map<string, KeyState> {
+ const states = new Map<string, KeyState>()
+ const unset = new Set(ops.unset)
+ for (const [key, value] of Object.entries(ops.set)) {
+ states.set(key, { kind: unset.has(key) ? 'pair' : 'value', lane: 'set', value })
+ }
+ for (const [key, value] of Object.entries(ops.setOnce)) {
+ states.set(key, { kind: unset.has(key) ? 'pair' : 'value', lane: 'setOnce', value })
+ }
+ for (const key of ops.unset) {
+ if (!states.has(key)) {
+ states.set(key, { kind: 'unset' })
+ }
+ }
+ return states
+}
+
+/**
+ * The per-key transition table: what the accumulated state becomes when
+ * a later event's op for the same key lands on it. `null` means the
+ * composition is not representable and the caller must cut a segment.
+ *
+ * Two facts drive every row. A plain set or unset is unconditional, so
+ * it supersedes whatever is pending. A set_once and a pair are
+ * snapshot-dependent — set_once applies only where the key is absent,
+ * a pair resolves to gone where present and to its value where absent —
+ * so their outcome over pending state follows from what that state
+ * guarantees about the key: a pending value guarantees present, a
+ * pending unset guarantees absent, and a pending pair guarantees
+ * nothing, which is why a snapshot-dependent op over it must segment.
+ */
+function foldKey(state: KeyState | undefined, op: KeyState): KeyState | null {
+ if (op.kind === 'value' && op.lane === 'set') {
+ return op
+ }
+ if (op.kind === 'unset') {
+ return op
+ }
+ // op is a set_once or a pair; both resolve against the pending state.
+ switch (state?.kind) {
+ case undefined:
+ return op
+ case 'value':
+ // Present is guaranteed: a set_once loses to the first
+ // value, a pair resolves to gone.
+ return op.kind === 'value' ? state : { kind: 'unset' }
+ case 'unset':
+ // Absent is guaranteed: either op's value applies
+ // unconditionally.
+ return { kind: 'value', lane: 'set', value: op.value }
+ case 'pair':
+ return null
+ }
+}
+
+function mergeLastSeenMs(a: number | undefined, b: number | undefined): number | undefined {
+ if (a === undefined && b === undefined) {
+ return undefined
+ }
+ return Math.max(a ?? -Infinity, b ?? -Infinity)
}
/**
@@ -173,13 +404,9 @@ export function applyEventPropertyUpdates(
// Minimize useless person updates by not overriding properties if it's not a person event and we added from the event
// They will still show up for PoE as it's not removed from the event, we just don't update the person in PG anymore
-function shouldUpdatePersonIfOnlyChange(event: PluginEvent, key: string, updateAllProperties: boolean): boolean {
- if (updateAllProperties) {
- // When flag is enabled, all property changes trigger updates
- return true
- }
- if (PERSON_EVENTS.has(event.event)) {
- // for person events always update everything
+function shouldUpdatePersonIfOnlyChange(ops: EventOps, key: string, updateAllProperties: boolean): boolean {
+ if (updateAllProperties || ops.shouldForceUpdate) {
+ // Person events and the update-all flag update everything
return true
}
return !isFilteredPersonUpdateProperty(key)
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
new file mode 100644
index 000000000000..1e0261e65cba
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts
@@ -0,0 +1,423 @@
+import { DateTime } from 'luxon'
+
+import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'
+import { PersonhogPropertiesSizeError } from '~/common/personhog/persons'
+import { NoRowsUpdatedError } from '~/common/utils/utils'
+import { InternalPerson } from '~/types'
+
+import { extractEventOps } from './person-update'
+import { PersonhogPendingRpcError, PersonhogPersonsStore } from './personhog-persons-store'
+
+describe('PersonhogPersonsStore', () => {
+ let repository: jest.Mocked<PersonHogPersonWriteRepository>
+ let store: PersonhogPersonsStore
+ let person: InternalPerson
+
+ const ops = (properties: Record<string, unknown>, event = '$set') =>
+ extractEventOps({
+ event,
+ distinct_id: 'd1',
+ properties,
+ team_id: 1,
+ uuid: 'event-uuid',
+ ip: null,
+ now: '2026-08-07T00:00:00Z',
+ site_url: '',
+ } as any)
+
+ beforeEach(() => {
+ person = {
+ id: '7',
+ uuid: 'person-uuid',
+ team_id: 1,
+ properties: { plan: 'free' },
+ created_at: DateTime.fromMillis(3_600_000, { zone: 'utc' }),
+ version: 1,
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ is_user_id: null,
+ is_identified: false,
+ last_seen_at: null,
+ }
+ repository = {
+ resolvePersonsByDistinctIds: jest.fn().mockResolvedValue([]),
+ fetchPersonById: jest.fn().mockResolvedValue(null),
+ // An applied write bumps the version, as the leader does.
+ updatePersonProperties: jest.fn().mockResolvedValue({ person: { ...person, version: 2 }, updated: true }),
+ getDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
+ getOrCreatePersonByDistinctId: jest.fn().mockResolvedValue({ person, created: true }),
+ } as unknown as jest.Mocked<PersonHogPersonWriteRepository>
+ store = new PersonhogPersonsStore(repository)
+ })
+
+ it('folds a batch of ops into one leader call per person and publishes nothing', async () => {
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' }, $set_once: { first: 'x' } }), 'd1')
+ await bound.applyEventOps(person, ops({ $set: { a: '2', first: 'shadowed' } }), 'd1')
+ await bound.applyEventOps(person, ops({ $unset: ['gone'] }), 'd1')
+
+ const results = await bound.flush()
+
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ const sent = repository.updatePersonProperties.mock.calls[0][0]
+ expect(sent.personId).toEqual('7')
+ expect(sent.setProperties).toEqual({ a: '2', first: 'shadowed' })
+ expect(sent.setOnceProperties).toEqual({})
+ expect(sent.unsetProperties).toEqual(['gone'])
+ // The changelog is this world's ClickHouse feed: a flush ships
+ // segments and publishes nothing.
+ expect(results).toEqual([])
+ })
+
+ it('returns a locally projected person while the leader stays authoritative at flush', async () => {
+ const bound = store.forBatch(0)
+ const eventOps = ops({ $set: { plan: 'pro' }, $set_once: { plan: 'ignored', fresh: 'kept' } })
+ eventOps.isIdentified = true
+ eventOps.lastSeenAtMs = 7_200_000
+
+ const [projected, messages] = await bound.applyEventOps(person, eventOps, 'd1')
+
+ expect(messages).toEqual([])
+ expect(projected.properties).toEqual({ plan: 'pro', fresh: 'kept' })
+ expect(projected.is_identified).toBe(true)
+ expect(projected.last_seen_at?.toMillis()).toEqual(7_200_000)
+ expect(person.properties).toEqual({ plan: 'free' })
+ })
+
+ describe('flush suppression of filtered-only lanes', () => {
+ it('a lane of unforced filtered-only changes never reaches the leader', async () => {
+ person.properties = { $browser: 'Firefox' }
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, 'pageview'), 'd1')
+ const results = await bound.flush()
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ expect(results).toEqual([])
+ })
+
+ it.each([
+ ['a person event forces the write', { $browser: 'Firefox' }, { $set: { $browser: 'Chrome' } }, '$set'],
+ ['a new key always counts', {}, { $set: { $browser: 'Chrome' } }, 'pageview'],
+ ['an unset always counts', { $browser: 'Firefox' }, { $unset: ['$browser'] }, 'pageview'],
+ ])('%s and the lane ships', async (_label, baseline, props, event) => {
+ person.properties = { ...(baseline as Record<string, string>) }
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops(props as Record<string, unknown>, event as string), 'd1')
+ await bound.flush()
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ })
+
+ it('a scalar move ships without property changes', async () => {
+ const bound = store.forBatch(0)
+ const scalarOnly = ops({}, 'pageview')
+ scalarOnly.isIdentified = true
+ await bound.applyEventOps(person, scalarOnly, 'd1')
+ await bound.flush()
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ })
+
+ it('one update-worthy event makes the whole lane ship', async () => {
+ person.properties = { $browser: 'Firefox' }
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, 'pageview'), 'd1')
+ await bound.applyEventOps(person, ops({ $set: { plan: 'pro' } }, 'pageview'), 'd1')
+ await bound.flush()
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ it('does not fold denied events', async () => {
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }, '$exception'), 'd1')
+ const results = await bound.flush()
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ expect(results).toEqual([])
+ })
+
+ it('a denied event still ships its scalars, without its properties', async () => {
+ const bound = store.forBatch(0)
+ const denied = ops({ $set: { a: '1' } }, '$exception')
+ denied.lastSeenAtMs = 7_200_000
+ const [projected] = await bound.applyEventOps(person, denied, 'd1')
+ expect(projected.last_seen_at?.toMillis()).toBe(7_200_000)
+ expect(projected.properties).toEqual({ plan: 'free' })
+
+ await bound.flush()
+ const sent = repository.updatePersonProperties.mock.calls[0][0]
+ expect(sent.lastSeenAtMs).toBe(7_200_000)
+ expect(sent.setProperties).toEqual({})
+ })
+
+ it('memoizes update fetches per batch, resolving once and reading state once', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ const bound = store.forBatch(0)
+ await bound.fetchForUpdate(1, 'd1')
+ await bound.fetchForUpdate(1, 'd1')
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(repository.fetchPersonById).toHaveBeenCalledTimes(1)
+ })
+
+ it('update fetches take state from the leader, not the resolution', async () => {
+ // The identity resolve returns writer-applied state; the leader's
+ // is fresher and must win as the projection baseline.
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([
+ { teamId: 1, distinctId: 'd1', person: { ...person, properties: { plan: 'stale' } } },
+ ])
+ repository.fetchPersonById.mockResolvedValue({ ...person, properties: { plan: 'fresh' }, version: 9 })
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForUpdate(1, 'd1')
+ expect(fetched?.properties).toEqual({ plan: 'fresh' })
+ expect(fetched?.version).toBe(9)
+ expect(repository.fetchPersonById).toHaveBeenCalledWith(1, '7', expect.any(String))
+ })
+
+ it('checking fetches use the resolved person without a leader call', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForChecking(1, 'd1')
+ expect(fetched?.id).toBe('7')
+ expect(repository.fetchPersonById).not.toHaveBeenCalled()
+ })
+
+ it('prefetch resolves the batch once so later fetches make no calls', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ await store.prefetchPersons([{ teamId: 1, distinctId: 'd1', batchId: 0 }])
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForUpdate(1, 'd1')
+ expect(fetched?.id).toBe('7')
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(repository.fetchPersonById).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 })
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForUpdate(1, 'd1')
+ expect(fetched?.id).toBe('7')
+
+ // A late prefetch response reporting absence must not erase the
+ // resolved mapping.
+ ;(store as any).recordFetch(1, 'd1', null, 0)
+ const again = await bound.fetchForUpdate(1, 'd1')
+ expect(again?.id).toBe('7')
+ })
+
+ it('prefetch dedupes repeated distinct ids before resolving', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ await store.prefetchPersons([
+ { teamId: 1, distinctId: 'd1', batchId: 0 },
+ { teamId: 1, distinctId: 'd1', batchId: 0 },
+ { teamId: 1, distinctId: 'd1', batchId: 0 },
+ ])
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+ expect(repository.resolvePersonsByDistinctIds.mock.calls[0][0]).toEqual([{ teamId: 1, distinctId: 'd1' }])
+ })
+
+ it('a failed prefetch falls back to first-touch resolution', async () => {
+ repository.resolvePersonsByDistinctIds.mockRejectedValueOnce(new Error('identity unavailable'))
+ await store.prefetchPersons([{ teamId: 1, distinctId: 'd1', batchId: 0 }])
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForUpdate(1, 'd1')
+ expect(fetched?.id).toBe('7')
+ })
+
+ it('deletes have no personhog path and fail loudly', () => {
+ const bound = store.forBatch(0)
+ expect(() => bound.deletePerson(person, 'd1')).toThrow('no personhog RPC')
+ })
+
+ it('creation resolves through identity and memoizes every distinct id it mapped', async () => {
+ const bound = store.forBatch(0)
+ const result = await bound.createPerson(
+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),
+ { initial: 'props' },
+ {},
+ {},
+ 1,
+ null,
+ false,
+ 'advisory-uuid',
+ { distinctId: 'd1' },
+ [{ distinctId: 'd2' }]
+ )
+
+ expect(result.success).toBe(true)
+ expect(repository.getOrCreatePersonByDistinctId).toHaveBeenCalledWith(
+ expect.objectContaining({
+ teamId: 1,
+ distinctId: 'd1',
+ extraDistinctIds: ['d2'],
+ setProperties: { initial: 'props' },
+ createdAtMs: 3_600_000,
+ }),
+ expect.any(String)
+ )
+ await bound.fetchForUpdate(1, 'd1')
+ await bound.fetchForUpdate(1, 'd2')
+ expect(repository.resolvePersonsByDistinctIds).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['not_found', new NoRowsUpdatedError('gone')],
+ ['size_violation', new PersonhogPropertiesSizeError('too big', 1, '7')],
+ ])('skips %s at flush without failing the batch', async (_outcome, error) => {
+ repository.updatePersonProperties.mockRejectedValue(error)
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')
+ const results = await bound.flush()
+ expect(results).toEqual([])
+ })
+
+ it('fails the flush on unexpected errors so the batch retries whole', async () => {
+ repository.updatePersonProperties.mockRejectedValue(new Error('leader unreachable'))
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')
+ await expect(bound.flush()).rejects.toThrow('leader unreachable')
+ })
+
+ it('publishes nothing when the leader reports no change', async () => {
+ repository.updatePersonProperties.mockResolvedValue({ person, updated: false })
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { plan: 'free' } }), 'd1')
+ const results = await bound.flush()
+ expect(results).toEqual([])
+ })
+
+ it('a later segment failing on a domain error does not undo earlier segments', async () => {
+ const bound = store.forBatch(0)
+ const pair = ops({ $set_once: { k: 'v' }, $unset: ['k'] })
+ const cutter = ops({ $set_once: { k: 'later' } })
+ await bound.applyEventOps(person, pair, 'd1')
+ await bound.applyEventOps(person, cutter, 'd1')
+
+ repository.updatePersonProperties
+ .mockResolvedValueOnce({ person: { ...person, version: 2 }, updated: true })
+ .mockRejectedValueOnce(new PersonhogPropertiesSizeError('too big', 1, '7'))
+ const results = await bound.flush()
+ // Both segments shipped — the first landed before the second's
+ // domain error, and the error skips rather than fails the flush.
+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(2)
+ expect(results).toEqual([])
+ })
+
+ it('pending state is visible through every distinct id of the person', async () => {
+ const bound = store.forBatch(0)
+ await bound.createPerson(
+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),
+ {},
+ {},
+ {},
+ 1,
+ null,
+ false,
+ 'advisory-uuid',
+ { distinctId: 'd1' },
+ [{ distinctId: 'd2' }]
+ )
+ const viaD1 = await bound.fetchForUpdate(1, 'd1')
+ await bound.applyEventOps(viaD1!, ops({ $set: { a: '1' } }), 'd1')
+
+ const viaD2 = await bound.fetchForUpdate(1, 'd2')
+ expect(viaD2?.properties).toMatchObject({ a: '1' })
+ expect(repository.resolvePersonsByDistinctIds).not.toHaveBeenCalled()
+ })
+
+ it('pending ops are visible to later fetches and compose across events', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ const bound = store.forBatch(0)
+ const fetched = await bound.fetchForUpdate(1, 'd1')
+ await bound.applyEventOps(fetched!, ops({ $set: { a: '1' } }), 'd1')
+
+ const refetched = await bound.fetchForUpdate(1, 'd1')
+ expect(refetched?.properties).toEqual({ plan: 'free', a: '1' })
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)
+
+ const [afterSecond] = await bound.applyEventOps(refetched!, ops({ $set: { b: '2' } }), 'd1')
+ expect(afterSecond.properties).toEqual({ plan: 'free', a: '1', b: '2' })
+ })
+
+ it('releaseBatch frees the batch memo so later fetches hit the service again', async () => {
+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])
+ repository.fetchPersonById.mockResolvedValue({ ...person })
+ const bound = store.forBatch(0)
+ await bound.fetchForUpdate(1, 'd1')
+ store.releaseBatch(0)
+ await bound.fetchForUpdate(1, 'd1')
+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(2)
+ })
+
+ it('releaseBatch drops an unflushed lane so nothing ships for the batch', async () => {
+ const bound = store.forBatch(0)
+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')
+ store.releaseBatch(0)
+ const results = await bound.flush()
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ expect(results).toEqual([])
+ })
+
+ it('runs transactions as a passthrough over the store itself', 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')
+ })
+
+ it.each([
+ [
+ 'updatePersonForMerge',
+ (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>
+ b.updatePersonForMerge(p, {}, 'd1'),
+ ],
+ [
+ 'addDistinctId',
+ (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) => b.addDistinctId(p, 'd2', 0),
+ ],
+ [
+ 'moveDistinctIds',
+ (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>
+ b.moveDistinctIds(p, p, 'd1', undefined, undefined as any),
+ ],
+ [
+ 'moveDistinctIdsFromPersons',
+ (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) => {
+ const bound = store.forBatch(0)
+ expect(() => call(bound, person)).toThrow(PersonhogPendingRpcError)
+ })
+
+ it('maps a direct diff update onto the folded RPC', async () => {
+ const bound = store.forBatch(0)
+ const [updated, messages] = await bound.updatePersonWithPropertiesDiffForUpdate(
+ person,
+ { plan: 'pro' },
+ ['gone'],
+ { is_identified: true, last_seen_at: DateTime.fromMillis(7_200_000, { zone: 'utc' }) },
+ 'd1'
+ )
+ const sent = repository.updatePersonProperties.mock.calls[0][0]
+ expect(sent.setProperties).toEqual({ plan: 'pro' })
+ expect(sent.unsetProperties).toEqual(['gone'])
+ expect(sent.isIdentified).toBe(true)
+ expect(sent.lastSeenAtMs).toBe(7_200_000)
+ expect(updated).toEqual({ ...person, version: 2 })
+ expect(messages).toEqual([])
+ })
+
+ it('refuses a diff update carrying fields the RPC cannot express', async () => {
+ const bound = store.forBatch(0)
+ await expect(
+ bound.updatePersonWithPropertiesDiffForUpdate(person, {}, [], { created_at: person.created_at }, 'd1')
+ ).rejects.toThrow(PersonhogPendingRpcError)
+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
new file mode 100644
index 000000000000..bd48697e3a95
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts
@@ -0,0 +1,838 @@
+import { DateTime } from 'luxon'
+import pLimit from 'p-limit'
+import { Counter } from 'prom-client'
+
+import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'
+import { PersonhogPropertiesSizeError } from '~/common/personhog/persons'
+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 { NoRowsUpdatedError } from '~/common/utils/utils'
+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'
+
+export const personhogStoreFlushCounter = new Counter({
+ name: 'personhog_store_flush_ops_total',
+ help: 'Folded person updates flushed to the personhog leader, by outcome',
+ labelNames: ['outcome'],
+})
+
+export interface PersonhogPersonsStoreOptions {
+ /**
+ * Bounds concurrent RPC fan-out (batch fetches and flush). Its own
+ * knob on purpose: the Postgres store's identically named option
+ * exists to avoid connection-pool starvation, a resource this store
+ * does not hold.
+ */
+ maxConcurrentUpdates: number
+ /**
+ * When true, every property change triggers a person update in the
+ * local projection, matching the Postgres store's option of the same
+ * name. Wiring must hand both stores the same value or their
+ * projections diverge by construction.
+ */
+ updateAllProperties: boolean
+}
+
+const DEFAULT_OPTIONS: PersonhogPersonsStoreOptions = {
+ maxConcurrentUpdates: 10,
+ updateAllProperties: false,
+}
+
+const CALLER_TAG = 'ingestion/personhog-store'
+
+/** The event name stamped on creation calls; per-event names are consumed at fold time. */
+const CREATE_EVENT_NAME = '$create_person'
+
+/** The event name stamped on direct diff updates, which carry no originating event. */
+const DIRECT_UPDATE_EVENT_NAME = '$direct_update'
+
+/**
+ * A store verb with no personhog RPC behind it. The shadow gates the
+ * events that reach these verbs off this store, so hitting one is a
+ * wiring bug; it fails loudly instead of no-oping into silent
+ * divergence.
+ */
+export class PersonhogPendingRpcError extends Error {
+ constructor(method: string, needs: string) {
+ super(`PersonhogPersonsStore.${method} has no personhog RPC: ${needs}`)
+ this.name = 'PersonhogPendingRpcError'
+ }
+}
+
+interface OpsLaneEntry {
+ teamId: number
+ personId: string
+ distinctId: string
+ /**
+ * Folded ops in arrival order. Almost always one segment; a new one
+ * starts only when foldOps cannot represent the composition, and
+ * flush ships segments sequentially so the leader refines between
+ * them.
+ */
+ segments: EventOps[]
+ /**
+ * Whether any folded event triggers a person update against its
+ * projection baseline, per the ignored-property rules. A lane that
+ * never turns this on holds filtered-only noise, and flush
+ * suppresses it — the same no-op classification the Postgres store
+ * applies at its flush.
+ */
+ triggersUpdate: boolean
+}
+
+/**
+ * The personhog implementation of the person store: distinct-id
+ * resolution and person creation through the identity service's
+ * get-or-create, person state through the leader's strong reads, and
+ * property updates as raw op folds shipped to the leader, which refines
+ * them against authoritative state under the per-person lock.
+ *
+ * Where the Postgres store refines ops against a fetched snapshot before
+ * writing, this store ships them as stated, so no version-race machinery
+ * exists here. Fetches memoize per batch; folded ops accumulate per
+ * (batch, person) and flush as one call per person.
+ *
+ * Person uuids derive deterministically from team_id:distinct_id on the
+ * identity service; the uuid argument to createPerson is advisory and
+ * the returned person carries the authoritative one.
+ */
+export class PersonhogPersonsStore {
+ private options: PersonhogPersonsStoreOptions
+ /** Folded ops per batch, keyed by `${teamId}:${personId}`. */
+ private lanes: Map<number, Map<string, OpsLaneEntry>> = new Map()
+ /**
+ * Distinct-id resolution per batch: `${teamId}:${distinctId}` to the
+ * person key, or null for a known-absent id. Split from person state
+ * so every distinct id of a person reads the same pending
+ * projection, not just the one that triggered the update.
+ */
+ private resolutions: Map<number, Map<string, string | null>> = new Map()
+ /**
+ * Person state per batch, keyed by `${teamId}:${personId}`. Once ops
+ * fold for a person this holds the pending projection (the batch's
+ * read-your-write view), and fetches must not clobber it with
+ * service state.
+ */
+ private personState: Map<number, Map<string, InternalPerson>> = new Map()
+
+ constructor(
+ private repository: PersonHogPersonWriteRepository,
+ options?: Partial<PersonhogPersonsStoreOptions>
+ ) {
+ this.options = { ...DEFAULT_OPTIONS, ...options }
+ }
+
+ forBatch(batchId: number): PersonsStoreForBatch {
+ return new BatchBoundPersonhogStore(this, batchId)
+ }
+
+ /**
+ * Checking reads resolve through identity (primary-backed) and use
+ * the resolved person directly: writer-applied state is within this
+ * read class's eventual contract, and it saves the leader hop.
+ */
+ async fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {
+ const cached = this.lookupMemo(teamId, distinctId, batchId)
+ if (cached !== undefined) {
+ return cached
+ }
+ const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)
+ return this.recordFetch(teamId, distinctId, resolved?.person ?? null, batchId)
+ }
+
+ /**
+ * Update reads split resolution from state: identity resolves the
+ * distinct id on the primary, then the person's state comes from the
+ * partition leader, which the primary lags by writer apply lag. The
+ * projection this feeds enriches the batch's events, so the baseline
+ * must be the leader's.
+ */
+ async fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {
+ const cached = this.lookupMemo(teamId, distinctId, batchId)
+ if (cached !== undefined) {
+ return cached
+ }
+ const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)
+ if (!resolved?.person) {
+ return this.recordFetch(teamId, distinctId, null, batchId)
+ }
+ // A null here means the person vanished between resolve and read
+ // (merged or deleted mid-flight); record the resolution miss and
+ // let the caller's create path re-resolve authoritatively.
+ const person = await this.repository.fetchPersonById(teamId, resolved.person.id, CALLER_TAG)
+ return this.recordFetch(teamId, distinctId, person, batchId)
+ }
+
+ async fetchPersonsForUpdateByDistinctIds(
+ teamId: number,
+ distinctIds: string[],
+ batchId: number
+ ): Promise<InternalPersonWithDistinctId[]> {
+ const resolved = await this.repository.resolvePersonsByDistinctIds(
+ distinctIds.map((distinctId) => ({ teamId, distinctId })),
+ CALLER_TAG
+ )
+ const limit = pLimit(this.options.maxConcurrentUpdates)
+ const fetched = await Promise.all(
+ resolved.map((entry) =>
+ limit(async () => {
+ if (!entry.person) {
+ this.recordFetch(teamId, entry.distinctId, null, batchId)
+ return null
+ }
+ const person = await this.repository.fetchPersonById(teamId, entry.person.id, CALLER_TAG)
+ // Pending projections win over fetched state here
+ // too, so the merge planner reads the same pre-flush
+ // view the update path does.
+ const recorded = this.recordFetch(teamId, entry.distinctId, person, batchId)
+ if (!recorded) {
+ return null
+ }
+ return { ...recorded, distinct_id: entry.distinctId } as InternalPersonWithDistinctId
+ })
+ )
+ )
+ return fetched.filter((person): person is InternalPersonWithDistinctId => person !== null)
+ }
+
+ /** Resolves a distinct id through the batch memos, undefined on miss. */
+ private lookupMemo(teamId: number, distinctId: string, batchId: number): InternalPerson | null | undefined {
+ const resolution = this.resolutionMemo(batchId).get(`${teamId}:${distinctId}`)
+ if (resolution === undefined) {
+ return undefined
+ }
+ if (resolution === null) {
+ return null
+ }
+ return this.personStateMemo(batchId).get(resolution) ?? undefined
+ }
+
+ /**
+ * Records a fetch result in the batch memos and returns the state
+ * callers should see: an existing pending projection wins over the
+ * fetched snapshot, so a fetch never rolls the batch's view back to
+ * pre-update state.
+ */
+ private recordFetch(
+ teamId: number,
+ distinctId: string,
+ fetched: InternalPerson | null,
+ batchId: number
+ ): InternalPerson | null {
+ const resolutions = this.resolutionMemo(batchId)
+ if (fetched === null) {
+ // Never downgrade a live mapping: a stale prefetch response
+ // can land after the batch created or resolved this person,
+ // and absence must not overwrite presence.
+ const existing = resolutions.get(`${teamId}:${distinctId}`)
+ if (existing === undefined || existing === null) {
+ resolutions.set(`${teamId}:${distinctId}`, null)
+ }
+ return existing != null ? (this.personStateMemo(batchId).get(existing) ?? null) : null
+ }
+ const personKey = `${teamId}:${fetched.id}`
+ resolutions.set(`${teamId}:${distinctId}`, personKey)
+ const state = this.personStateMemo(batchId)
+ const hasPending = this.lanes.get(batchId)?.has(personKey) ?? false
+ if (!hasPending || !state.has(personKey)) {
+ state.set(personKey, fetched)
+ }
+ return state.get(personKey) ?? fetched
+ }
+
+ async 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,
+ batchId: number
+ ): Promise<CreatePersonResult> {
+ const { person, created } = await this.repository.getOrCreatePersonByDistinctId(
+ {
+ teamId,
+ distinctId: primaryDistinctId.distinctId,
+ extraDistinctIds: extraDistinctIds?.map(({ distinctId }) => distinctId),
+ eventName: CREATE_EVENT_NAME,
+ setProperties: properties,
+ createdAtMs: createdAt.toMillis(),
+ isIdentified,
+ },
+ CALLER_TAG
+ )
+ const personKey = `${teamId}:${person.id}`
+ const resolutions = this.resolutionMemo(batchId)
+ resolutions.set(`${teamId}:${primaryDistinctId.distinctId}`, personKey)
+ for (const extra of extraDistinctIds ?? []) {
+ resolutions.set(`${teamId}:${extra.distinctId}`, personKey)
+ }
+ this.personStateMemo(batchId).set(personKey, person)
+ // The identity service publishes its own downstream messages on
+ // the creation branch, so none are surfaced here.
+ return { success: true, person, messages: [], created }
+ }
+
+ applyEventOps(
+ person: InternalPerson,
+ ops: EventOps,
+ distinctId: string,
+ batchId: number
+ ): Promise<[InternalPerson, PersonMessage[]]> {
+ // The denylist gates property writes only: a denied op still
+ // advances identity and last-seen, matching the Postgres store
+ // and the leader's own refinement. Denied ops carrying no
+ // scalars have nothing to contribute at all.
+ if (ops.denied && ops.isIdentified === undefined && ops.lastSeenAtMs === undefined) {
+ return Promise.resolve([person, []])
+ }
+
+ // A local projection for the caller: the same application the
+ // Postgres world would perform, so the processor returns a
+ // sensible person. The leader's application at flush remains the
+ // authoritative one for this world.
+ const refined = refineEventOps(ops, person.properties ?? {}, this.options.updateAllProperties, false)
+ const [projected] = applyEventPropertyUpdates(refined, person)
+ const scalarUpdates = computeOpsScalarUpdates(ops, projected)
+ Object.assign(projected, scalarUpdates)
+ // An event triggers an update when the refinement found a
+ // non-filtered change against its baseline, or a scalar moved.
+ // Filtered-only noise leaves it false, and a lane of nothing but
+ // noise is suppressed at flush.
+ const triggersUpdate =
+ (refined.hasChanges && refined.hasNonFilteredChanges) || Object.keys(scalarUpdates).length > 0
+
+ const lane = this.opsLane(batchId)
+ const personKey = `${person.team_id}:${person.id}`
+ const existing = lane.get(personKey)
+ if (!existing) {
+ lane.set(personKey, {
+ teamId: person.team_id,
+ personId: person.id,
+ distinctId,
+ segments: [ops],
+ triggersUpdate,
+ })
+ } else {
+ existing.triggersUpdate = existing.triggersUpdate || triggersUpdate
+ const last = existing.segments.length - 1
+ const folded = foldOps(existing.segments[last], ops)
+ if (folded === null) {
+ existing.segments.push(ops)
+ } else {
+ existing.segments[last] = folded
+ }
+ }
+ // The memo now holds the pending projection: every distinct id
+ // resolving to this person sees the change pre-flush, and the
+ // next event composes on top. Merged properties are computed
+ // from the projection, so pending ops travel to the merge
+ // target through it.
+ this.personStateMemo(batchId).set(personKey, projected)
+ this.resolutionMemo(batchId).set(`${person.team_id}:${distinctId}`, personKey)
+ return Promise.resolve([projected, []])
+ }
+
+ // Deletes exist only to destroy the losing persons of a merge, and
+ // 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')
+ }
+
+ deletePerson(_person: InternalPerson, _distinctId: string, _batchId?: number): Promise<PersonMessage[]> {
+ throw new PersonhogPendingRpcError('deletePerson', 'merge saga')
+ }
+
+ /**
+ * A direct diff update, applied immediately rather than folded: the
+ * caller has already resolved the diff, so it maps one-to-one onto
+ * the leader's folded-update RPC. Only the diff-expressible fields of
+ * `otherUpdates` are supported; anything else has no RPC field, and
+ * silently dropping it would diverge, so it fails loudly instead.
+ */
+ async updatePersonWithPropertiesDiffForUpdate(
+ person: InternalPerson,
+ propertiesToSet: Properties,
+ propertiesToUnset: string[],
+ otherUpdates: Partial<InternalPerson>,
+ _distinctId: string,
+ _forceUpdate?: boolean
+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {
+ const unsupported = Object.keys(otherUpdates).filter((key) => key !== 'is_identified' && key !== 'last_seen_at')
+ if (unsupported.length > 0) {
+ throw new PersonhogPendingRpcError(
+ 'updatePersonWithPropertiesDiffForUpdate',
+ `UpdatePersonProperties fields for ${unsupported.join(', ')}`
+ )
+ }
+ const { person: updated } = await this.repository.updatePersonProperties(
+ {
+ teamId: person.team_id,
+ personId: person.id,
+ eventName: DIRECT_UPDATE_EVENT_NAME,
+ setProperties: propertiesToSet,
+ setOnceProperties: {},
+ unsetProperties: propertiesToUnset,
+ isIdentified: otherUpdates.is_identified === true ? true : undefined,
+ lastSeenAtMs: otherUpdates.last_seen_at?.toMillis(),
+ },
+ CALLER_TAG
+ )
+ if (!updated) {
+ return [person, [], false]
+ }
+ // No ClickHouse message: the leader's changelog is this world's
+ // person feed, so emitting here would double-publish.
+ return [updated, [], false]
+ }
+
+ /**
+ * Counts by fetching: the RPC surface has no dedicated count, and the
+ * merge pre-check consuming this runs at shadow-team scale, where
+ * fetching the ids to count them is acceptable. Absent persons count
+ * zero, matching the SQL count.
+ */
+ async countDistinctIdsForPersons(
+ teamId: Team['id'],
+ personIds: InternalPerson['id'][]
+ ): 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[]> {
+ const byPerson = await this.repository.getDistinctIdsForPersons(person.team_id, [person.id], limit, CALLER_TAG)
+ return byPerson[person.id] ?? []
+ }
+
+ removeDistinctIdFromCache(teamId: number, distinctId: string): void {
+ // Resolution only: the person's state may still be valid under
+ // its other distinct ids; what a merge changed is which person
+ // this id maps to, and the next fetch re-resolves it.
+ const key = `${teamId}:${distinctId}`
+ for (const memo of this.resolutions.values()) {
+ memo.delete(key)
+ }
+ }
+
+ /**
+ * One identity batch resolve for the batch's distinct ids, then
+ * leader state reads for the hits — the same two-step the update
+ * fetch does singly, done once up front so per-event processing hits
+ * the memo. Best-effort: a failed prefetch leaves resolution to
+ * first touch.
+ */
+ 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.lookupMemo(entry.teamId, entry.distinctId, entry.batchId) === undefined
+ })
+ if (unresolved.length === 0) {
+ return
+ }
+ try {
+ const resolved = await this.repository.resolvePersonsByDistinctIds(
+ unresolved.map((entry) => ({ teamId: entry.teamId, distinctId: entry.distinctId })),
+ CALLER_TAG
+ )
+ const limit = pLimit(this.options.maxConcurrentUpdates)
+ await Promise.all(
+ resolved.map((entry, i) =>
+ limit(async () => {
+ const { batchId } = unresolved[i]
+ if (!entry.person) {
+ this.recordFetch(entry.teamId, entry.distinctId, null, batchId)
+ return
+ }
+ const person = await this.repository.fetchPersonById(entry.teamId, entry.person.id, CALLER_TAG)
+ this.recordFetch(entry.teamId, entry.distinctId, person, batchId)
+ })
+ )
+ )
+ } catch (error) {
+ logger.warn('personhog prefetch failed; resolution falls back to first touch', { error })
+ }
+ }
+
+ /**
+ * Ships the 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
+ * succeed on retry, but segments already applied still publish.
+ * Publication gates on the version floor rather than the last
+ * 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.
+ *
+ * A lane 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.
+ */
+ async flush(batchId: number): Promise<FlushResult[]> {
+ const lane = this.lanes.get(batchId)
+ if (!lane) {
+ return []
+ }
+ 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 []
+ })
+ )
+ )
+ return results.flat()
+ }
+
+ /**
+ * Frees a completed batch's resolution memo and any unfetched lane,
+ * mirroring the Postgres store's post-flush release in
+ * flush-batch-stores-step. No reference counting: unlike the
+ * Postgres cache, nothing here is shared across batches.
+ */
+ releaseBatch(batchId: number): void {
+ this.resolutions.delete(batchId)
+ this.personState.delete(batchId)
+ this.lanes.delete(batchId)
+ }
+
+ shutdown(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ private opsLane(batchId: number): Map<string, OpsLaneEntry> {
+ let lane = this.lanes.get(batchId)
+ if (!lane) {
+ lane = new Map()
+ this.lanes.set(batchId, lane)
+ }
+ return lane
+ }
+
+ private resolutionMemo(batchId: number): Map<string, string | null> {
+ let memo = this.resolutions.get(batchId)
+ if (!memo) {
+ memo = new Map()
+ this.resolutions.set(batchId, memo)
+ }
+ return memo
+ }
+
+ private personStateMemo(batchId: number): Map<string, InternalPerson> {
+ let memo = this.personState.get(batchId)
+ if (!memo) {
+ memo = new Map()
+ this.personState.set(batchId, memo)
+ }
+ 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/persons-store-for-batch.ts b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
index 4f4f442535f7..c15874c64273 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
@@ -7,6 +7,7 @@ import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
+import { EventOps } from './person-update'
import { FlushResult, PersonsStore } from './persons-store'
import { PersonsStoreTransaction } from './persons-store-transaction'
@@ -106,6 +107,7 @@ export type PersonsStoreForBatch = Omit<
| 'fetchForChecking'
| 'fetchForUpdate'
| 'fetchPersonsForUpdateByDistinctIds'
+ | 'applyEventOps'
| 'createPerson'
| 'updatePersonForMerge'
| 'updatePersonWithPropertiesDiffForUpdate'
@@ -120,6 +122,7 @@ export type PersonsStoreForBatch = Omit<
fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null>
fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null>
fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]>
+ applyEventOps(person: InternalPerson, ops: EventOps, distinctId: string): Promise<[InternalPerson, PersonMessage[]]>
moveDistinctIdsFromPersons(
sources: InternalPerson[],
target: InternalPerson,
@@ -313,6 +316,14 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.fetchForChecking(teamId, distinctId, this.batchId)
}
+ applyEventOps(
+ person: InternalPerson,
+ ops: EventOps,
+ distinctId: string
+ ): Promise<[InternalPerson, PersonMessage[]]> {
+ return this.store.applyEventOps(person, ops, distinctId, this.batchId)
+ }
+
fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null> {
return this.store.fetchForUpdate(teamId, distinctId, this.batchId)
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.ts
index 1b29f648f0b0..2a59c0f731b2 100644
--- a/nodejs/src/ingestion/common/persons/persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store.ts
@@ -8,6 +8,7 @@ import { BatchWritingStore } 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 { PersonsStoreTransaction } from './persons-store-transaction'
export type FlushResult = {
@@ -76,6 +77,19 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
tx?: PersonRepositoryTransaction
): Promise<[InternalPerson, PersonMessage[], boolean]>
+ /**
+ * Applies one event's extracted ops to a person, resolving what they
+ * mean against this store's own state: snapshot refinement, the
+ * identity OR-merge, the last-seen advance, and whether anything is
+ * worth writing at all.
+ */
+ applyEventOps(
+ person: InternalPerson,
+ ops: EventOps,
+ distinctId: string,
+ batchId: number
+ ): Promise<[InternalPerson, PersonMessage[]]>
+
/**
* Updates person for regular updates with specific properties to set and unset
*/
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 1e23967ef822..7ab0f1b63177 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -137,6 +137,8 @@ export type IngestionConsumerConfig = {
PERSON_BATCH_WRITING_MAX_CONCURRENT_UPDATES: number
PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: number
PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: number
+ /** Concurrent RPC fan-out in the personhog store (batch fetches and flush). */
+ PERSONHOG_STORE_MAX_CONCURRENT_UPDATES: number
PERSONS_PREFETCH_ENABLED: boolean
// Person properties config
@@ -300,6 +302,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,
PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: 5,
PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: 50,
+ PERSONHOG_STORE_MAX_CONCURRENT_UPDATES: 10,
PERSONS_PREFETCH_ENABLED: false,
// Person properties config