:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(personhog): treat identity answers as identity only in the Node client (#99569)
Nick Best879b207d5b68
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.tsindex 1528d1fe3c2c..3e6817c52f36 100644--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts@@ -116,7 +116,10 @@ export const GetOrCreatePersonByDistinctIdRequestSchema: GenMessage<GetOrCreateP/*** created = true means the stub row is committed in Postgres AND the initial- * properties (when provided) are durable in the leader's changelog.+ * properties (when provided) are durable in the leader's changelog. Only a+ * created person carries properties (the leader's document, or the fresh+ * stub's empty set). A found person carries identity fields only: the leader+ * owns its properties, and a primary copy would lag it.** @generated from message personhog.identity.v1.GetOrCreatePersonByDistinctIdResponse*/@@ -180,7 +183,8 @@ export type GetOrCreatePersonResult = Message<'personhog.identity.v1.GetOrCreatedistinctId: string/**- * Absent when this key failed (see error).+ * Absent when this key failed (see error). Carries properties only when+ * created; a found person is identity fields only.** @generated from field: optional personhog.types.v1.Person person = 3;*/@@ -294,7 +298,8 @@ export type GetPersonByDistinctIdResult = Message<'personhog.identity.v1.GetPers/*** Absent when the distinct id resolves to no live person — unknown,- * tombstoned, or its person deleted.+ * tombstoned, or its person deleted. Identity fields only: properties are+ * never populated here, fetch the person by id from its leader for state.** @generated from field: optional personhog.types.v1.Person person = 3;*/diff --git a/nodejs/src/common/personhog/identity.ts b/nodejs/src/common/personhog/identity.tsindex f41771550137..7f1c42edc2a0 100644--- a/nodejs/src/common/personhog/identity.ts+++ b/nodejs/src/common/personhog/identity.ts@@ -14,7 +14,7 @@ import { PersonPropertiesSizeViolationError } from '~/common/persons/repositorieimport { Properties } from '~/plugin-scaffold'import { InternalPerson } from '~/types'-import { encodeJsonBytes, protoPersonToDomain } from './persons'+import { PersonIdentity, encodeJsonBytes, protoPersonToDomain, protoPersonToIdentity } from './persons'/*** A single get-or-create key: resolve distinct_id within team_id,@@ -84,6 +84,11 @@ export const SEMANTIC_REFUSAL_METADATA_KEY = 'x-semantic-refusal'/** The op id belongs to a different recorded merge; refused before any durable work. */export const SEMANTIC_REFUSAL_OP_ID_REUSED = 'op_id_reused'+/** Only a created person carries a document; a found one is identity only, the leader owns its properties. */+export type GetOrCreatePersonOutcome =+ | { created: true; person: InternalPerson }+ | { created: false; person: PersonIdentity }+export type MergeSagaSourceOutcome =| 'merged'| 'noop_same_person'@@ -166,15 +171,16 @@ export class PersonhogIdentityOperations {* 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.+ * Answers carry identity only; state comes from the leader.*/async getPersonsByDistinctIds(keys: DistinctIdKey[],callerTag?: string- ): Promise<{ teamId: number; distinctId: string; person: InternalPerson | null }[]> {+ ): Promise<{ teamId: number; distinctId: string; person: PersonIdentity | null }[]> {if (keys.length === 0) {return []}- const out: { teamId: number; distinctId: string; person: InternalPerson | null }[] = []+ const out: { teamId: number; distinctId: string; person: PersonIdentity | 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(@@ -190,7 +196,7 @@ export class PersonhogIdentityOperations {out.push({teamId: Number(result.teamId),distinctId: result.distinctId,- person: result.person ? protoPersonToDomain(result.person) : null,+ person: result.person ? protoPersonToIdentity(result.person) : null,})}}@@ -237,7 +243,7 @@ export class PersonhogIdentityOperations {async getOrCreatePersonByDistinctId(entry: GetOrCreatePersonEntry,callerTag?: string- ): Promise<{ person: InternalPerson; created: boolean }> {+ ): Promise<GetOrCreatePersonOutcome> {try {const response = await this.client.getOrCreatePersonByDistinctId(create(GetOrCreatePersonByDistinctIdRequestSchema, {@@ -259,7 +265,9 @@ export class PersonhogIdentityOperations {`identity get-or-create returned no person for team ${entry.teamId} distinct_id ${entry.distinctId}`)}- return { person: protoPersonToDomain(response.person), created: response.created }+ return response.created+ ? { created: true, person: protoPersonToDomain(response.person) }+ : { created: false, person: protoPersonToIdentity(response.person) }} catch (error) {// Surfaced as the domain error the create service handles;// untranslated, the raw gRPC error matches no non-retriablediff --git a/nodejs/src/common/personhog/personhog-person-write-repository.ts b/nodejs/src/common/personhog/personhog-person-write-repository.tsindex f7d82b48c615..9e9640b646a1 100644--- a/nodejs/src/common/personhog/personhog-person-write-repository.ts+++ b/nodejs/src/common/personhog/personhog-person-write-repository.ts@@ -5,12 +5,13 @@ import { withRetry } from './grpc-retry'import {DistinctIdKey,GetOrCreatePersonEntry,+ GetOrCreatePersonOutcome,MergeSagaRequest,MergeSagaResult,PersonhogIdentityOperations,} from './identity'import { timedGrpc } from './metrics'-import { FoldedPersonUpdate } from './persons'+import { FoldedPersonUpdate, PersonIdentity } from './persons'/*** Write-side person repository backed by personhog gRPC, the@@ -36,14 +37,13 @@ export class PersonHogPersonWriteRepository {/*** 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.+ * request order, null person for an unresolved key. Identity only:+ * callers that need state fetch the person by id from its leader.*/resolvePersonsByDistinctIds(keys: DistinctIdKey[],callerTag?: string- ): Promise<{ teamId: number; distinctId: string; person: InternalPerson | null }[]> {+ ): Promise<{ teamId: number; distinctId: string; person: PersonIdentity | null }[]> {const method = 'resolvePersonsByDistinctIds'return withRetry(() => timedGrpc(this.clientLabel, method, () => this.identity.getPersonsByDistinctIds(keys, callerTag)),@@ -105,7 +105,7 @@ export class PersonHogPersonWriteRepository {getOrCreatePersonByDistinctId(entry: GetOrCreatePersonEntry,callerTag?: string- ): Promise<{ person: InternalPerson; created: boolean }> {+ ): Promise<GetOrCreatePersonOutcome> {const method = 'getOrCreatePersonByDistinctId'return withRetry(() =>diff --git a/nodejs/src/common/personhog/persons.ts b/nodejs/src/common/personhog/persons.tsindex 262ef076cb5e..5b21f029d186 100644--- a/nodejs/src/common/personhog/persons.ts+++ b/nodejs/src/common/personhog/persons.ts@@ -93,6 +93,25 @@ export function protoPersonToDomain(proto: ProtoPerson): InternalPerson {}}+/** An identity answer: no properties, because the partition leader owns them. */+export type PersonIdentity = Omit<+ InternalPerson,+ 'properties' | 'properties_last_updated_at' | 'properties_last_operation'+>++export function protoPersonToIdentity(proto: ProtoPerson): PersonIdentity {+ return {+ id: String(proto.id),+ uuid: proto.uuid,+ team_id: Number(proto.teamId),+ created_at: epochMsToDateTime(proto.createdAt),+ version: Number(proto.version),+ is_identified: proto.isIdentified,+ is_user_id: proto.isUserId != null ? (proto.isUserId ? 1 : 0) : null,+ last_seen_at: proto.lastSeenAt != null ? epochMsToDateTime(proto.lastSeenAt) : null,+ }+}+const PERSONHOG_BATCH_SIZE = 250export class PersonHogPersonOperations {diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.tsindex fc09113325dc..ea722b72488e 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts@@ -281,10 +281,8 @@ describe('PersonhogPersonsStore', () => {})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' } } },+ { teamId: 1, distinctId: 'd1', person: { ...person, version: 3 } },])repository.fetchPersonById.mockResolvedValue({ ...person, properties: { plan: 'fresh' }, version: 9 })const bound = store.forBatch(0)@@ -304,18 +302,19 @@ describe('PersonhogPersonsStore', () => {it('an update read does not trust a checking-read document', async () => {repository.resolvePersonsByDistinctIds.mockResolvedValue([- { teamId: 1, distinctId: 'd1', person: { ...person, version: 3, properties: { plan: 'lagged' } } },+ { teamId: 1, distinctId: 'd1', person: { ...person, version: 3 } },] as never)repository.fetchPersonById.mockResolvedValue({ ...person, version: 5, properties: { plan: 'fresh' } } as never)const bound = store.forBatch(0)const checked = await bound.fetchForChecking(1, 'd1')- expect(checked?.properties).toEqual({ plan: 'lagged' })+ expect(checked?.version).toBe(3)+ expect(checked?.properties).toEqual({})expect(repository.fetchPersonById).not.toHaveBeenCalled()- // The checking read installed identity's writer-lagged document; the- // update path pays the leader read it skipped, the way the Postgres- // store keeps its check cache out of the update path.+ // The checking read installed identity's document; the update path+ // pays the leader read it skipped, the way the Postgres store keeps+ // its check cache out of the update path.const updated = await bound.fetchForUpdate(1, 'd1')expect(updated?.properties).toEqual({ plan: 'fresh' })expect(repository.fetchPersonById).toHaveBeenCalledTimes(1)diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex e9aa81d80376..52948a447282 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -7,7 +7,7 @@ import { TRANSPORT_MAX_RETRIES } from '~/common/personhog/grpc-retry'import { SEMANTIC_REFUSAL_METADATA_KEY, SEMANTIC_REFUSAL_OP_ID_REUSED } from '~/common/personhog/identity'import { errorClassLabel } from '~/common/personhog/metrics'import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'-import { PersonhogFencedError, PersonhogPropertiesSizeError } from '~/common/personhog/persons'+import { PersonIdentity, PersonhogFencedError, PersonhogPropertiesSizeError } from '~/common/personhog/persons'import { PersonMessage } from '~/common/persons/person-message'import { PersonClaimedByLifecycleOpError } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'@@ -432,7 +432,12 @@ export class PersonhogPersonsStore implements PersonsStore {}}- /** Resolves through identity and uses that person directly, saving the leader hop. */+ /** Check grade only: the personless step discards properties there, and the update grade reads the leader. */+ private identityDocument(identity: PersonIdentity): InternalPerson {+ return { ...identity, properties: {}, properties_last_updated_at: {}, properties_last_operation: null }+ }++ /** Resolves through identity and serves its answer directly, saving the leader hop. */async fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {const cached = this.getCachedPerson(teamId, distinctId, 'check')if (cached !== undefined) {@@ -440,7 +445,8 @@ export class PersonhogPersonsStore implements PersonsStore {}const generation = this.generationOf(teamId)const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)- return this.cacheFetchedPerson(teamId, distinctId, resolved?.person ?? null, batchId, {+ const document = resolved?.person ? this.identityDocument(resolved.person) : null+ return this.cacheFetchedPerson(teamId, distinctId, document, batchId, {grade: 'check',generation,})@@ -498,15 +504,17 @@ export class PersonhogPersonsStore implements PersonsStore {CALLER_TAG)const { created } = createResult- let { person } = createResult- if (!created) {- // Identity's found-branch document lags the leader, so pay a- // leader read; a null means the person died mid-call, and the- // redirect heals any ops folded onto identity's answer.- const leaderDoc = await this.repository.fetchPersonById(teamId, person.id, CALLER_TAG)+ let person: InternalPerson+ if (createResult.created) {+ person = createResult.person+ } else {+ // A null means the person died mid-call, and the redirect heals+ // any ops folded onto identity's answer.+ const identity = createResult.person+ const leaderDoc = await this.repository.fetchPersonById(teamId, identity.id, CALLER_TAG)if (leaderDoc === null) {- this.clearPersonCacheForPersonId(`${teamId}:${person.id}`, 'stale_write_answer')- return { success: true, person: this.snapshot(person), messages: [], created }+ this.clearPersonCacheForPersonId(`${teamId}:${identity.id}`, 'stale_write_answer')+ return { success: true, person: this.identityDocument(identity), messages: [], created }}person = leaderDoc}diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.protoindex 0589532548f1..786248fbbac3 100644--- a/proto/personhog/identity/v1/identity.proto+++ b/proto/personhog/identity/v1/identity.proto@@ -37,7 +37,10 @@ message GetOrCreatePersonByDistinctIdRequest {}// created = true means the stub row is committed in Postgres AND the initial-// properties (when provided) are durable in the leader's changelog.+// properties (when provided) are durable in the leader's changelog. Only a+// created person carries properties (the leader's document, or the fresh+// stub's empty set). A found person carries identity fields only: the leader+// owns its properties, and a primary copy would lag it.message GetOrCreatePersonByDistinctIdResponse {personhog.types.v1.Person person = 1;bool created = 2;@@ -53,7 +56,8 @@ message GetOrCreatePersonsByDistinctIdsRequest {message GetOrCreatePersonResult {int64 team_id = 1;string distinct_id = 2;- // Absent when this key failed (see error).+ // Absent when this key failed (see error). Carries properties only when+ // created; a found person is identity fields only.optional personhog.types.v1.Person person = 3;bool created = 4;// Set when this key failed; the caller should retry the key. A committed@@ -86,7 +90,8 @@ message GetPersonByDistinctIdResult {int64 team_id = 1;string distinct_id = 2;// Absent when the distinct id resolves to no live person — unknown,- // tombstoned, or its person deleted.+ // tombstoned, or its person deleted. Identity fields only: properties are+ // never populated here, fetch the person by id from its leader for state.optional personhog.types.v1.Person person = 3;}