: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
feat(personhog): simple merge store (#93358)
José Sequeira2379ba0acb66
diff --git a/bin/start-rust-service b/bin/start-rust-serviceindex e450bb824ebd..34ab8df56831 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -374,6 +374,9 @@ case "$RS_SVC" inexport KAFKA_HOSTS="${KAFKA_HOSTS:-localhost:9092}"export KAFKA_PERSON_STATE_TOPIC=personhog_updatesexport FALLBACK_DATABASE_URL="postgres://posthog:posthog@${PGHOST:-localhost}:${PGPORT:-5432}/posthog_persons"+ # Pair with the identity service's and the writer's default table, or+ # leader cache misses read a table the identity never wrote.+ export FALLBACK_TABLE="${FALLBACK_TABLE:-personhog_person_tmp}"export METRICS_PORT=9102;;diff --git a/docker-compose.base.yml b/docker-compose.base.ymlindex 281dbc86f9d9..c9189a1c1a9e 100644--- a/docker-compose.base.yml+++ b/docker-compose.base.yml@@ -538,6 +538,84 @@ services:RUST_LOG: 'info'METRICS_PORT: '9101'+ personhog-router-leader:+ # The same router binary in leader mode: person writes and strong+ # reads go to leader pods via etcd partition routing; the rest goes+ # to the replica.+ image: ghcr.io/posthog/posthog/personhog-router:master+ build:+ context: rust/+ args:+ BIN: personhog-router+ restart: on-failure+ environment:+ GRPC_ADDRESS: '0.0.0.0:50054'+ REPLICA_URL: 'http://personhog-replica:50051'+ ROUTER_MODE: 'leader'+ ETCD_ENDPOINTS: 'http://etcd:2379'+ ETCD_PREFIX: '/personhog/'+ BACKEND_TIMEOUT_MS: '5000'+ RUST_LOG: 'info'+ METRICS_PORT: '9104'++ personhog-leader:+ image: ghcr.io/posthog/posthog/personhog-leader:master+ build:+ context: rust/+ args:+ BIN: personhog-leader+ restart: on-failure+ # The leader binds the wildcard, so it must advertise the container's+ # own IP in etcd for routers to dial; compose cannot inject it as+ # K8s's downward API does, so the entrypoint resolves it at start.+ entrypoint: ['/bin/sh', '-c', 'POD_IP=$$(hostname -i) exec /usr/local/bin/personhog-leader']+ environment:+ GRPC_ADDRESS: '0.0.0.0:50053'+ CACHE_MEMORY_CAPACITY: '100000'+ ETCD_ENDPOINTS: 'http://etcd:2379'+ ETCD_PREFIX: '/personhog/'+ POD_NAME: 'personhog-leader'+ KAFKA_HOSTS: 'kafka:9092'+ KAFKA_PERSON_STATE_TOPIC: 'personhog_updates'+ FALLBACK_DATABASE_URL: 'postgres://posthog:posthog@db:5432/posthog_persons'+ # Must name the same table the identity service and the writer+ # target (their defaults), or leader misses read the wrong table.+ FALLBACK_TABLE: 'personhog_person_tmp'+ RUST_LOG: 'info'+ METRICS_PORT: '9102'++ personhog-writer:+ image: ghcr.io/posthog/posthog/personhog-writer:master+ build:+ context: rust/+ args:+ BIN: personhog-writer+ restart: on-failure+ environment:+ DATABASE_URL: 'postgres://posthog:posthog@db:5432/posthog_persons'+ KAFKA_HOSTS: 'kafka:9092'+ KAFKA_TOPIC: 'personhog_updates'+ KAFKA_CONSUMER_GROUP: 'personhog-writer'+ FLUSH_INTERVAL_MS: '5000'+ FLUSH_BUFFER_SIZE: '1000'+ BUFFER_CAPACITY: '50000'+ RUST_LOG: 'info'+ METRICS_PORT: '9103'++ personhog-identity:+ image: ghcr.io/posthog/posthog/personhog-identity:master+ build:+ context: rust/+ args:+ BIN: personhog-identity+ restart: on-failure+ environment:+ GRPC_ADDRESS: '0.0.0.0:50055'+ PRIMARY_DATABASE_URL: 'postgres://posthog:posthog@db:5432/posthog_persons'+ ROUTER_URL: 'http://personhog-router-leader:50054'+ RUST_LOG: 'info'+ METRICS_PORT: '9108'+hypercache-server:image: ghcr.io/posthog/posthog/hypercache-server:masterbuild:diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex f6e693e79087..be59d1f1e9da 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -676,6 +676,80 @@ services:profiles:- ingestion+ personhog-router-leader:+ extends:+ file: docker-compose.base.yml+ service: personhog-router-leader+ ports:+ - '50054:50054'+ depends_on:+ etcd:+ condition: service_healthy+ personhog-replica:+ condition: service_started+ profiles:+ - ingestion++ personhog-leader:+ extends:+ file: docker-compose.base.yml+ service: personhog-leader+ environment:+ FALLBACK_DATABASE_URL: postgres://posthog:posthog@db:5432/${POSTHOG_PERSONS_DB_NAME:-posthog}+ depends_on:+ etcd:+ condition: service_healthy+ db:+ condition: service_healthy+ kafka:+ condition: service_started+ personhog-etcd-init:+ condition: service_completed_successfully+ profiles:+ - ingestion++ personhog-writer:+ extends:+ file: docker-compose.base.yml+ service: personhog-writer+ environment:+ DATABASE_URL: postgres://posthog:posthog@db:5432/${POSTHOG_PERSONS_DB_NAME:-posthog}+ depends_on:+ db:+ condition: service_healthy+ kafka:+ condition: service_started+ profiles:+ - ingestion++ personhog-identity:+ extends:+ file: docker-compose.base.yml+ service: personhog-identity+ environment:+ PRIMARY_DATABASE_URL: postgres://posthog:posthog@db:5432/${POSTHOG_PERSONS_DB_NAME:-posthog}+ ports:+ - '50055:50055'+ depends_on:+ db:+ condition: service_healthy+ personhog-router-leader:+ condition: service_started+ profiles:+ - ingestion++ # Seeds the partition count the leaders and routers coordinate under;+ # idempotent, and the same key bin/mprocs.yaml writes for hogli runs.+ personhog-etcd-init:+ image: quay.io/coreos/etcd:v3.6.8+ restart: 'no'+ entrypoint: ['etcdctl', '--endpoints=http://etcd:2379', 'put', '/personhog/config/total_partitions', '4']+ depends_on:+ etcd:+ condition: service_healthy+ profiles:+ - ingestion+feature-flags:extends:file: docker-compose.base.ymldiff --git a/docker-compose.profiles.yml b/docker-compose.profiles.ymlindex 2581ef4be901..cda49a6112dc 100644--- a/docker-compose.profiles.yml+++ b/docker-compose.profiles.yml@@ -54,9 +54,11 @@ services:objectstorage-azure:profiles: [azure]- # Coordination - etcd for PersonHog and Kafka partition assignment+ # Coordination - etcd for PersonHog and Kafka partition assignment.+ # Also in the ingestion profile: the personhog services there depend on+ # it as service_healthy, so an ingestion-profile run must bring it up.etcd:- profiles: [etcd]+ profiles: [etcd, ingestion]# DuckDB query serverduckgres:diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 8d36b85601c9..63ac42d8e5a8 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -129,6 +129,8 @@ export type CommonConfig = BaseServerConfig & {PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS: stringPERSONHOG_TLS: booleanPERSONHOG_TIMEOUT_MS: number+ /** Deadline for the identity merge saga call; must exceed the engine's lifecycle_execute_timeout_secs. */+ PERSONHOG_MERGE_TIMEOUT_MS: numberPERSONHOG_READ_MAX_BYTES: numberPERSONHOG_WRITE_MAX_BYTES: numberPERSONHOG_PING_INTERVAL_MS: number@@ -325,6 +327,7 @@ export function getDefaultCommonConfig(): CommonConfig {PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS: '',PERSONHOG_TLS: false,PERSONHOG_TIMEOUT_MS: 3000,+ PERSONHOG_MERGE_TIMEOUT_MS: 35_000,PERSONHOG_READ_MAX_BYTES: 128 * 1024 * 1024,PERSONHOG_WRITE_MAX_BYTES: 4 * 1024 * 1024,PERSONHOG_PING_INTERVAL_MS: 30_000,diff --git a/nodejs/src/common/personhog/grpc-retry.ts b/nodejs/src/common/personhog/grpc-retry.tsindex 16c43b588f9d..28c1296c0462 100644--- a/nodejs/src/common/personhog/grpc-retry.ts+++ b/nodejs/src/common/personhog/grpc-retry.ts@@ -31,6 +31,12 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms))}+/**+ * Retries beyond the first attempt. Exported so a caller that must wait out+ * another caller's full transport budget can derive its bound from this.+ */+export const TRANSPORT_MAX_RETRIES = 2+/*** Retry a function with exponential backoff on transient gRPC errors.* Non-transient errors are thrown immediately.@@ -44,7 +50,7 @@ export async function withRetry<T>(fn: () => Promise<T>,client: string,method: string,- maxRetries: number = 2,+ maxRetries: number = TRANSPORT_MAX_RETRIES,initialDelayMs: number = 50): Promise<T> {let lastError: unknowndiff --git a/nodejs/src/common/personhog/identity-clients.ts b/nodejs/src/common/personhog/identity-clients.tsindex afeaa26578a7..2fa1e0d66599 100644--- a/nodejs/src/common/personhog/identity-clients.ts+++ b/nodejs/src/common/personhog/identity-clients.ts@@ -10,13 +10,23 @@ import { PersonhogIdentityOperations } from './identity'* PersonHogClient because it answers on a different address than the* router.*/-export function createIdentityClients(config: PersonHogClientConfig): {+export function createIdentityClients(+ config: PersonHogClientConfig,+ options: { mergeTimeoutMs?: number } = {}+): {identity: PersonhogIdentityOperationsclose: () => void} {+ // A zero or negative deadline would kill every merge client-side.+ if (+ options.mergeTimeoutMs !== undefined &&+ (!Number.isInteger(options.mergeTimeoutMs) || options.mergeTimeoutMs < 1)+ ) {+ throw new Error(`PERSONHOG_MERGE_TIMEOUT_MS must be an integer >= 1, got ${options.mergeTimeoutMs}`)+ }const { transport, stateMonitor } = createPersonhogTransport(config)return {- identity: new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport)),+ identity: new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport), options),close: () => stateMonitor.close(),}}diff --git a/nodejs/src/common/personhog/identity.test.ts b/nodejs/src/common/personhog/identity.test.tsindex 11c22cc3fbb6..f26bf0d1905c 100644--- a/nodejs/src/common/personhog/identity.test.ts+++ b/nodejs/src/common/personhog/identity.test.ts@@ -3,13 +3,23 @@ import { createClient, createRouterTransport } from '@connectrpc/connect'import {GetDistinctIdsForPersonsRequest,GetPersonsByDistinctIdsRequest,+ MergePersonsRequest,PersonHogIdentity,} from '~/common/generated/personhog/personhog/identity/v1/identity_pb'import { PersonhogIdentityOperations } from './identity'+import { createIdentityClients } from './identity-clients'describe('PersonhogIdentityOperations', () => {- function makeOps(handlers: { getPersonsByDistinctIds?: jest.Mock; getDistinctIdsForPersons?: jest.Mock }) {+ it('refuses a merge timeout that would kill every merge client-side', () => {+ expect(() => createIdentityClients({} as never, { mergeTimeoutMs: 0 })).toThrow('PERSONHOG_MERGE_TIMEOUT_MS')+ })++ function makeOps(handlers: {+ getPersonsByDistinctIds?: jest.Mock+ getDistinctIdsForPersons?: jest.Mock+ mergePersons?: jest.Mock+ }) {const transport = createRouterTransport(({ service }) => {service(PersonHogIdentity, {getOrCreatePersonByDistinctId: jest.fn(() => ({ person: undefined, created: false })),@@ -17,11 +27,106 @@ describe('PersonhogIdentityOperations', () => {getPersonsByDistinctIds: handlers.getPersonsByDistinctIds ?? jest.fn(() => ({ results: [] })),getDistinctIdsForPersons:handlers.getDistinctIdsForPersons ?? jest.fn(() => ({ personDistinctIds: [] })),+ mergePersons: handlers.mergePersons ?? jest.fn(() => ({ opId: '', results: [] })),})})return new PersonhogIdentityOperations(createClient(PersonHogIdentity, transport))}+ // Both fields are new on this RPC and nothing else exercises the wire,+ // where a dropped mapping is silent: no newborn would carry its+ // creating event, and every verdict would read as unsettled.+ it('carries the creator event uuid out and the settled bit back', async () => {+ const handler = jest.fn((req: MergePersonsRequest) => ({+ opId: req.opId,+ survivor: {+ id: 7n,+ uuid: 'survivor-uuid',+ teamId: 1n,+ properties: new TextEncoder().encode('{}'),+ createdAt: 3_600_000n,+ version: 1n,+ isIdentified: true,+ },+ results: [{ sourceDistinctId: 'anon-1', outcome: 1, settled: true }],+ }))+ const ops = makeOps({ mergePersons: handler })++ const result = await ops.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'source-event-uuid' }],+ eventSet: {},+ eventSetOnce: {},+ opId: 'op-id',+ allowIdentifiedSources: false,+ moveLimit: 0,+ createdAtMs: 3_600_000,+ creatorEventUuid: 'event-uuid',+ })++ expect(handler.mock.calls[0][0].creatorEventUuid).toBe('event-uuid')+ expect(result.results[0].settled).toBe(true)+ expect(result.survivor?.id).toBe('7')+ })++ it('a merge call carries its own deadline instead of the transport default', async () => {+ // The saga is a multi-step drive bounded server-side at+ // lifecycle_execute_timeout_secs; the transport default is sized+ // for point reads and would cancel drives mid-lease, serializing+ // progress behind lease expiry.+ const client = {+ mergePersons: jest.fn((_req: unknown, _options?: unknown) => Promise.resolve({ opId: '', results: [] })),+ }+ const ops = new PersonhogIdentityOperations(client as never, { mergeTimeoutMs: 35_000 })++ await ops.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'source-event-uuid' }],+ eventSet: {},+ eventSetOnce: {},+ opId: 'op-id',+ allowIdentifiedSources: false,+ moveLimit: 0,+ createdAtMs: 3_600_000,+ creatorEventUuid: 'event-uuid',+ })++ expect(client.mergePersons.mock.calls[0][1]).toMatchObject({ timeoutMs: 35_000 })+ })++ it.each([+ ['an outcome added by a newer service', 99],+ ['no outcome at all, which proto3 reads as zero', 0],+ ])('names %s as unknown rather than as a refusal', async (_case, wire) => {+ // 'error' is a verdict the caller acks and records as a lost merge.+ // Neither of these is a verdict, and the merge may well have+ // happened, so they must not arrive wearing that name.+ const ops = makeOps({+ mergePersons: jest.fn((req: MergePersonsRequest) => ({+ opId: req.opId,+ survivor: undefined,+ results: [{ sourceDistinctId: 'anon-1', outcome: wire }],+ })),+ })++ const result = await ops.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'source-event-uuid' }],+ eventSet: {},+ eventSetOnce: {},+ opId: 'op-id',+ allowIdentifiedSources: false,+ moveLimit: 0,+ createdAtMs: 3_600_000,+ creatorEventUuid: 'event-uuid',+ })++ expect(result.results[0].outcome).toBe('unknown')+ })+// 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.diff --git a/nodejs/src/common/personhog/identity.ts b/nodejs/src/common/personhog/identity.tsindex 406e065c702b..f41771550137 100644--- a/nodejs/src/common/personhog/identity.ts+++ b/nodejs/src/common/personhog/identity.ts@@ -1,10 +1,13 @@import { create } from '@bufbuild/protobuf'import { Client, Code, ConnectError } from '@connectrpc/connect'+import { Counter } from 'prom-client'import {GetDistinctIdsForPersonsRequestSchema,GetOrCreatePersonByDistinctIdRequestSchema,GetPersonsByDistinctIdsRequestSchema,+ MergePersonsRequestSchema,+ MergeSourceOutcome,PersonHogIdentity,} from '~/common/generated/personhog/personhog/identity/v1/identity_pb'import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'@@ -15,11 +18,9 @@ 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.+ * creating a person stub when absent. Properties and scalars apply on the+ * creation branch only; the uuid derives from team_id:distinct_id+ * server-side.*/export interface GetOrCreatePersonEntry {teamId: number@@ -43,6 +44,112 @@ export interface DistinctIdKey {distinctId: string}+/** One source pair of a merge saga call. */+export interface MergeSagaSource {+ distinctId: string+ /** The $identify/$create_alias event that contributed this pair; for warning correlation only. */+ eventUuid: string+}++export interface MergeSagaRequest {+ teamId: number+ targetDistinctId: string+ /** Ordered; earlier pairs beat later pairs on property precedence, the target beats all. */+ sources: MergeSagaSource[]+ /** The merge event's $set: overrides on conflict, applied to the survivor. */+ eventSet: Properties+ /** The merge event's $set_once: fills only still-absent keys. */+ eventSetOnce: Properties+ /** Retry key: a repeated call with the same op id returns the recorded outcome. */+ opId: string+ /** $merge_dangerously legally merges already-identified sources; $identify does not. */+ allowIdentifiedSources: boolean+ /** Per-source distinct-id count guard; sources over it come back skipped_move_limit. */+ moveLimit: number+ /** Merge event created_at, epoch millis; consulted only when an unresolved target births a fresh person. */+ createdAtMs: number+ /**+ * The executing event's uuid, stable across retries; stamped as+ * $creator_event_uuid on a person the merge births and echoed on the+ * fences the saga installs.+ */+ creatorEventUuid: string+}++/**+ * Metadata key on identity's definitive refusals; the value is a reason+ * slug, and retrying the same request meets the same answer forever.+ */+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'++export type MergeSagaSourceOutcome =+ | 'merged'+ | 'noop_same_person'+ | 'attached'+ | 'skipped_illegal'+ | 'skipped_already_identified'+ | 'skipped_conflict'+ | 'skipped_move_limit'+ | 'skipped_refused'+ | 'error'+ | 'unknown'++export interface MergeSagaResult {+ /** The surviving person; null only when the target no longer resolves. */+ survivor: InternalPerson | null+ results: {+ sourceDistinctId: string+ outcome: MergeSagaSourceOutcome+ /**+ * Set only on a merged source: a merged-away person is permanent,+ * so a caller may reconcile cached state against it. Every other+ * verdict answers null because its person is still live.+ */+ sourcePersonId: string | null+ /**+ * The server's durability statement: true means no retry can change+ * this outcome, false means a retry under the same op id may.+ */+ settled: boolean+ }[]+}++export const personhogUnknownMergeOutcomeCounter = new Counter({+ name: 'personhog_unknown_merge_outcome_total',+ help: 'Merge verdicts this build has no name for, by wire value; a newer identity service can introduce one',+ labelNames: ['wire_value'],+})++const MERGE_OUTCOME_NAMES: Record<MergeSourceOutcome, MergeSagaSourceOutcome> = {+ // Proto3 reads an omitted field as zero, so this says the server sent no+ // verdict rather than that it refused the source.+ [MergeSourceOutcome.UNSPECIFIED]: 'unknown',+ [MergeSourceOutcome.MERGED]: 'merged',+ [MergeSourceOutcome.NOOP_SAME_PERSON]: 'noop_same_person',+ [MergeSourceOutcome.ATTACHED]: 'attached',+ [MergeSourceOutcome.SKIPPED_ILLEGAL]: 'skipped_illegal',+ [MergeSourceOutcome.SKIPPED_ALREADY_IDENTIFIED]: 'skipped_already_identified',+ [MergeSourceOutcome.SKIPPED_CONFLICT]: 'skipped_conflict',+ [MergeSourceOutcome.SKIPPED_MOVE_LIMIT]: 'skipped_move_limit',+ [MergeSourceOutcome.SKIPPED_REFUSED]: 'skipped_refused',+ [MergeSourceOutcome.ERROR]: 'error',+}++/**+ * The name this build knows for a wire verdict; a newer service's unknown+ * value is not a refusal and must not be recorded as one.+ */+function namedOutcome(wire: MergeSourceOutcome): MergeSagaSourceOutcome {+ const named = MERGE_OUTCOME_NAMES[wire]+ if (named !== undefined) {+ return named+ }+ personhogUnknownMergeOutcomeCounter.labels({ wire_value: String(wire) }).inc()+ return 'unknown'+}+/*** The identity service's client wrapper: proto encoding and domain* decoding for distinct-id resolution, expansion, and person stub@@ -50,7 +157,10 @@ export interface DistinctIdKey {* surface.*/export class PersonhogIdentityOperations {- constructor(private client: Client<typeof PersonHogIdentity>) {}+ constructor(+ private client: Client<typeof PersonHogIdentity>,+ private options: { mergeTimeoutMs?: number } = {}+ ) {}/*** Resolve-only counterpart of get-or-create: primary-backed@@ -151,11 +261,9 @@ export class PersonhogIdentityOperations {}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.+ // Surfaced as the domain error the create service handles;+ // untranslated, the raw gRPC error matches no non-retriable+ // class and the batch redelivers the oversized event forever.if (error instanceof ConnectError && error.code === Code.InvalidArgument) {if (error.rawMessage.includes('size limit')) {throw new PersonPropertiesSizeViolationError(@@ -169,4 +277,45 @@ export class PersonhogIdentityOperations {throw error}}++ /**+ * Merge every source distinct id's person into the target's person via+ * the identity service's merge saga. Retries with the same op id return+ * the recorded outcome, so callers reuse the op id across retries.+ */+ async mergePersons(request: MergeSagaRequest, callerTag?: string): Promise<MergeSagaResult> {+ const response = await this.client.mergePersons(+ create(MergePersonsRequestSchema, {+ teamId: BigInt(request.teamId),+ targetDistinctId: request.targetDistinctId,+ sources: request.sources.map((source) => ({+ sourceDistinctId: source.distinctId,+ eventUuid: source.eventUuid,+ })),+ eventSet: encodeJsonBytes(request.eventSet),+ eventSetOnce: encodeJsonBytes(request.eventSetOnce),+ opId: request.opId,+ allowIdentifiedSources: request.allowIdentifiedSources,+ moveLimit: BigInt(request.moveLimit),+ createdAt: BigInt(request.createdAtMs),+ creatorEventUuid: request.creatorEventUuid,+ }),+ {+ // A saga drive, not a point read, so its own deadline; it+ // must exceed the engine's lifecycle_execute_timeout_secs+ // so the server answers first in the common case.+ timeoutMs: this.options.mergeTimeoutMs,+ ...(callerTag ? { headers: { 'x-caller-tag': callerTag } } : {}),+ }+ )+ return {+ survivor: response.survivor ? protoPersonToDomain(response.survivor) : null,+ results: response.results.map((result) => ({+ sourceDistinctId: result.sourceDistinctId,+ outcome: namedOutcome(result.outcome),+ sourcePersonId: result.sourcePersonId === undefined ? null : String(result.sourcePersonId),+ settled: result.settled,+ })),+ }+ }}diff --git a/nodejs/src/common/personhog/index.ts b/nodejs/src/common/personhog/index.tsindex 9ce5fd3f3db0..6bc51a4e120a 100644--- a/nodejs/src/common/personhog/index.ts+++ b/nodejs/src/common/personhog/index.ts@@ -25,6 +25,7 @@ export type PersonHogConfig = Pick<| 'PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS'| 'PERSONHOG_TLS'| 'PERSONHOG_TIMEOUT_MS'+ | 'PERSONHOG_MERGE_TIMEOUT_MS'| 'PERSONHOG_READ_MAX_BYTES'| 'PERSONHOG_WRITE_MAX_BYTES'| 'PERSONHOG_PING_INTERVAL_MS'diff --git a/nodejs/src/common/personhog/metrics.ts b/nodejs/src/common/personhog/metrics.tsindex 6f1f1c9b9ca1..9e6f50f27828 100644--- a/nodejs/src/common/personhog/metrics.ts+++ b/nodejs/src/common/personhog/metrics.ts@@ -70,6 +70,15 @@ export function grpcErrorType(error: unknown): string {return 'non_grpc'}+/** A bounded metric label: gRPC faults carry their status code, everything else its class name. */+export function errorClassLabel(error: unknown): string {+ if (error instanceof ConnectError) {+ return grpcErrorType(error)+ }+ const name = error instanceof Error ? error.constructor?.name : undefined+ return typeof name === 'string' && name.length > 0 && name.length <= 64 ? name : 'unknown'+}+export const personhogLatencySeconds = new Histogram({name: 'personhog_latency_seconds',help: 'PersonHog request latency in seconds',diff --git a/nodejs/src/common/personhog/personhog-person-write-repository.ts b/nodejs/src/common/personhog/personhog-person-write-repository.tsindex 73331c96df58..f7d82b48c615 100644--- a/nodejs/src/common/personhog/personhog-person-write-repository.ts+++ b/nodejs/src/common/personhog/personhog-person-write-repository.ts@@ -2,7 +2,13 @@ import { InternalPerson } from '~/types'import { PersonHogClient } from './client'import { withRetry } from './grpc-retry'-import { DistinctIdKey, GetOrCreatePersonEntry, PersonhogIdentityOperations } from './identity'+import {+ DistinctIdKey,+ GetOrCreatePersonEntry,+ MergeSagaRequest,+ MergeSagaResult,+ PersonhogIdentityOperations,+} from './identity'import { timedGrpc } from './metrics'import { FoldedPersonUpdate } from './persons'@@ -110,4 +116,14 @@ export class PersonHogPersonWriteRepository {method)}++ /**+ * Runs the identity service's merge saga to completion; the op id+ * dedupes, so a retried call returns the recorded outcome. No+ * transport retries: the merge service owns the single bounded retry+ * layer, and layering both multiplies a wedged saga's deadline.+ */+ mergePersons(request: MergeSagaRequest, callerTag?: string): Promise<MergeSagaResult> {+ return timedGrpc(this.clientLabel, 'mergePersons', () => this.identity.mergePersons(request, callerTag))+ }}diff --git a/nodejs/src/common/personhog/persons.test.ts b/nodejs/src/common/personhog/persons.test.tsindex bd65fd41ce50..49fbb681806f 100644--- a/nodejs/src/common/personhog/persons.test.ts+++ b/nodejs/src/common/personhog/persons.test.ts@@ -11,7 +11,7 @@ import type {import { parseJSON } from '~/common/utils/json-parse'import { NoRowsUpdatedError } from '~/common/utils/utils'-import { PersonHogPersonOperations, PersonhogPropertiesSizeError } from './persons'+import { PersonHogPersonOperations, PersonhogFencedError, PersonhogPropertiesSizeError } from './persons'const textEncoder = new TextEncoder()@@ -286,5 +286,38 @@ describe('PersonHogPersonOperations', () => {expect(passthrough).toBeInstanceOf(ConnectError)expect(passthrough.code).toBe(Code.Unavailable)})++ // The leader raises FAILED_PRECONDITION, but the router that+ // ingestion actually dials substitutes UNAVAILABLE after its+ // retries while forwarding the fence metadata. Keying on the status+ // code would read the routed shape as a generic outage.+ it.each([+ ['the leader answers directly', Code.FailedPrecondition],+ ['the router substitutes its own status after exhausting retries', Code.Unavailable],+ ])('reads a fence refusal as a fence when %s', async (_case, code) => {+ const { ops } = createOperations({+ updatePersonProperties: () => {+ const metadata = new Headers()+ metadata.set('x-person-fenced', 'true')+ metadata.set('x-person-fenced-op-id', 'merge:op-77')+ throw new ConnectError('person 42 is held by a lifecycle operation', code, metadata)+ },+ })++ const error = await ops+ .updatePersonProperties({+ teamId: 7,+ personId: '42',+ eventName: '$folded_person_update',+ setProperties: { a: '1' },+ setOnceProperties: {},+ unsetProperties: [],+ })+ .catch((e) => e)++ expect(error).toBeInstanceOf(PersonhogFencedError)+ expect(error.personId).toBe('42')+ expect(error.fencingOpId).toBe('merge:op-77')+ })})})diff --git a/nodejs/src/common/personhog/persons.ts b/nodejs/src/common/personhog/persons.tsindex 7ea6b8487344..262ef076cb5e 100644--- a/nodejs/src/common/personhog/persons.ts+++ b/nodejs/src/common/personhog/persons.ts@@ -24,10 +24,13 @@ export function encodeJsonBytes(value: object): Uint8Array {return Object.keys(value).length === 0 ? new Uint8Array(0) : textEncoder.encode(JSON.stringify(value))}+/** Set by the leader on any write refused because a lifecycle op holds the person. */+const FENCED_METADATA_KEY = 'x-person-fenced'+/** Carries the holding operation's id on that refusal. */+const FENCED_OP_ID_METADATA_KEY = 'x-person-fenced-op-id'/**- * 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.+ * The leader rejected an update at the person-properties size ceiling;+ * callers re-wrap it into their own error vocabulary.*/export class PersonhogPropertiesSizeError extends Error {constructor(@@ -40,6 +43,21 @@ export class PersonhogPropertiesSizeError extends Error {}}+/**+ * The leader refused a write because a lifecycle operation holds the+ * person; the holder's op id and creator travel for attribution.+ */+export class PersonhogFencedError extends Error {+ constructor(+ message: string,+ public readonly personId: string,+ public readonly fencingOpId: string | undefined+ ) {+ super(message)+ this.name = 'PersonhogFencedError'+ }+}+/** A folded person-property update, resolved by the leader under the per-person lock. */export interface FoldedPersonUpdate {teamId: number@@ -55,6 +73,8 @@ export interface FoldedPersonUpdate {isIdentified?: boolean/** Epoch milliseconds; max-merged server-side. */lastSeenAtMs?: number+ /** The event's force flag; the leader writes filtered-only changes under it. */+ forceUpdate?: boolean}export function protoPersonToDomain(proto: ProtoPerson): InternalPerson {@@ -197,6 +217,7 @@ export class PersonHogPersonOperations {unsetProperties: update.unsetProperties,isIdentified: update.isIdentified,lastSeenAt: update.lastSeenAtMs != null ? BigInt(update.lastSeenAtMs) : undefined,+ forceUpdate: update.forceUpdate ?? false,}),callerTag ? { headers: { 'x-caller-tag': callerTag } } : undefined)@@ -217,6 +238,16 @@ export class PersonHogPersonOperations {if (error.code === Code.InvalidArgument && error.rawMessage.includes('size limit')) {throw new PersonhogPropertiesSizeError(error.rawMessage, update.teamId, update.personId)}+ // Keyed on the metadata rather than the status code: the+ // leader answers FAILED_PRECONDITION while the router hands+ // back its own UNAVAILABLE with these keys carried forward.+ if (error.metadata.has(FENCED_METADATA_KEY)) {+ throw new PersonhogFencedError(+ error.rawMessage,+ update.personId,+ error.metadata.get(FENCED_OP_ID_METADATA_KEY) ?? undefined+ )+ }}throw error}diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.tsindex f1d87da4f21a..1b5c75c6b645 100644--- a/nodejs/src/common/persons/metrics.ts+++ b/nodejs/src/common/persons/metrics.ts@@ -168,7 +168,31 @@ export const personhogStoreShadowSkipsCounter = new Counter({export const personhogStoreShadowErrorsCounter = new Counter({name: 'personhog_store_shadow_errors_total',- help: 'Personhog shadow-side store verb failures by verb; shadow errors never fail the batch',+ help: 'Personhog shadow-side store verb failures by verb and error class; shadow errors never fail the batch',+ labelNames: ['verb', 'error'],+})++export const personhogStoreShadowDivergenceCounter = new Counter({+ name: 'personhog_store_shadow_divergence_total',+ help: 'Answers where the shadow backend disagreed with the authoritative one, by verb and by the field that differed',+ labelNames: ['verb', 'field'],+})++export const personhogStoreShadowComparedCounter = new Counter({+ name: 'personhog_store_shadow_compared_total',+ help: 'Shadow answers actually compared against the authoritative one, the denominator for the divergence rate',+ labelNames: ['verb'],+})++export const personhogStoreShadowFoldRedriveCounter = new Counter({+ name: 'personhog_store_shadow_fold_redrive_total',+ help: 'Per-pair shadow merges re-driven after a fold the authoritative side executed aborted on the shadow, by outcome',+ labelNames: ['outcome'],+})++export const personhogStoreShadowCompareFailedCounter = new Counter({+ name: 'personhog_store_shadow_compare_failed_total',+ help: 'Shadow comparisons that threw, which is a fault in the comparison rather than in either backend',labelNames: ['verb'],})diff --git a/nodejs/src/common/persons/person-utils.ts b/nodejs/src/common/persons/person-utils.tsindex 67818f95feba..7170614d81e9 100644--- a/nodejs/src/common/persons/person-utils.ts+++ b/nodejs/src/common/persons/person-utils.ts@@ -73,11 +73,11 @@ export const isDistinctIdIllegal = (id: string): boolean => {}/**- * Ids no merge can ever involve. Wider than the illegal list, which is ids- * that never resolve to a person anywhere: NUL cannot exist in Postgres- * text (the capture path strips it from event.distinct_id but not from- * $anon_distinct_id or alias property values), and over 400 code points- * cannot exist in the varchar(400) column.+ * Ids no merge can involve, a strict superset of isDistinctIdIllegal: NUL+ * cannot exist in Postgres text and over 400 code points cannot fit the+ * column. Every path that picks merge participants must agree, or a merge+ * admits an id that fails at the column instead of settling.*/-export const isDistinctIdUnmergeable = (id: string): boolean =>- isDistinctIdIllegal(id) || id.includes('\u0000') || [...id].length > 400+export const isDistinctIdUnmergeable = (id: string): boolean => {+ return isDistinctIdIllegal(id) || id.includes('\u0000') || [...id].length > 400+}diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.test.tsindex b657e1e4703c..9ab1e7d8dfdc 100644--- a/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts@@ -178,15 +178,18 @@ describe('createMergeFoldPlanningStep', () => {expect(planOf(items[2])).toBe(plan)})- it('excludes anon ids no backend can store, which would fail the fold transaction', async () => {- // A NUL cannot exist in Postgres text and over 400 code points- // cannot fit the column, so folding one in aborts the whole- // transaction and every pair with it.- const items = await scan([identify('anon-1'), identify('anon\u0000two'), identify('x'.repeat(401))])+ it.each([+ ['a NUL, which the column cannot hold', 'anon\u0000bad'],+ ['over 400 code points, which the column cannot fit', 'a'.repeat(401)],+ ])('excludes an anon distinct id carrying %s', async (_case, badId) => {+ // The sequential path refuses these before merging. Admitting one+ // into a fold instead runs it against the column, which aborts the+ // whole folded transaction and takes every other pair in the run+ // down with it.+ const items = await scan([identify('anon-1'), identify(badId), identify('anon-2')])- expect(planOf(items[0])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1'])+ expect(planOf(items[0])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1', 'anon-2'])expect(items[1].mergeFold.type).toBe('immediate')- expect(items[2].mergeFold.type).toBe('immediate')})it('skips planning when only illegal anon distinct ids are in the run', async () => {@@ -195,6 +198,21 @@ describe('createMergeFoldPlanningStep', () => {expect(items.every((item) => item.mergeFold.type === 'immediate')).toBe(true)})+ it('splits a run longer than the saga source cap into several plans', async () => {+ const items = await scan(Array.from({ length: 260 }, (_, i) => identify(`anon-${i}`)))++ // One request carrying 260 sources is refused outright, which spends+ // the fold and drops every pair back to its own sequential merge.+ const plans = new Set(items.map((item) => planOf(item)).filter(Boolean))+ expect(plans.size).toBe(2)+ const sizes = [...plans].map((plan) => plan!.pairs.length).sort((a, b) => b - a)+ expect(sizes).toEqual([250, 10])++ // Every pair still folds: the split loses no merge.+ const folded = [...plans].flatMap((plan) => plan!.pairs.map((pair) => pair.anonDistinctId))+ expect(new Set(folded).size).toBe(260)+ })+it('excludes self-merges from the plan', async () => {const items = await scan([identify('user-1'), identify('anon-1'), identify('anon-2')])diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.tsindex 2d07e0d99c0c..d985b1dd890a 100644--- a/nodejs/src/ingestion/common/persons/person-merge-fold.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.ts@@ -95,6 +95,13 @@ function getFoldableAnonDistinctId(item: MergeFoldScanItem): string | null {return String(anonDistinctId)}+/**+ * The most sources one folded request may carry, matching the identity+ * service's max_batch_size default; a run past a smaller server cap is+ * refused there and degrades to the sequential fallback.+ */+const MAX_FOLD_SOURCES = 250+/*** Build the group chunk step that decides, per value, whether the event folds* or processes immediately. The step is always wired; whether it plans@@ -106,9 +113,6 @@ function getFoldableAnonDistinctId(item: MergeFoldScanItem): string | null {* shared MergeFoldPlan, carried by the run's values as a `planned` decision,* with the distinct anon ids as pairs (first event wins the pair's eventUuid;* self-merges are excluded). Every other value gets the `immediate` decision.- * Fold size is naturally bounded by the batch size; pathological per-source- * distinct_id counts are handled by the merge-mode limit pre-check at- * execution time.*/export function createMergeFoldPlanningStep<T extends MergeFoldScanItem>(options: MergeFoldOptions@@ -170,14 +174,21 @@ function planRun<T extends MergeFoldScanItem>(return}- const plan: MergeFoldPlan = {- targetDistinctId,- pairs: [...pairByAnonId.values()],- status: 'planned',+ // A longer run becomes several plans: the saga refuses an oversized+ // request outright, abandoning the fold into per-pair merges.+ const planByAnonId = new Map<string, MergeFoldPlan>()+ const ordered = [...pairByAnonId.values()]+ for (let offset = 0; offset < ordered.length; offset += MAX_FOLD_SOURCES) {+ const pairs = ordered.slice(offset, offset + MAX_FOLD_SOURCES)+ const plan: MergeFoldPlan = { targetDistinctId, pairs, status: 'planned' }+ for (const pair of pairs) {+ planByAnonId.set(pair.anonDistinctId, plan)+ }}for (let index = runStart; index < runEnd; index++) {const anonDistinctId = getFoldableAnonDistinctId(values[index])- if (anonDistinctId !== null && pairByAnonId.has(anonDistinctId)) {+ const plan = anonDistinctId === null ? undefined : planByAnonId.get(anonDistinctId)+ if (plan !== undefined) {results[index] = ok({ ...values[index], mergeFold: { type: 'planned', plan } })}}diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.tsindex 0af1a5225f93..1a082ccb4d5f 100644--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts@@ -148,6 +148,12 @@ export interface PostgresMergePolicy {export class PostgresPersonMerge {private batchStore: PersonsStoreForBatchprivate createService: PersonCreateService+ /**+ * The bootstrap's produced messages, when one committed before the fold+ * ran. Held on the request rather than inside the fold, because an abort+ * unwinds past that scope while the commit it produced for stands.+ */+ private bootstrapAck?: Promise<void>constructor(private store: BatchWritingPersonsStore,@@ -476,7 +482,9 @@ export class PostgresPersonMerge {reason,error,})- return { survivor: null, results: [], foldAborted: reason }+ // A committed bootstrap's messages still have to reach the+ // event's ack; the rollback did not unmake that commit.+ return { survivor: null, results: [], foldAborted: reason, kafkaAck: this.bootstrapAck }}}@@ -528,7 +536,6 @@ export class PostgresPersonMerge {private async executeFoldInner(): Promise<MergePersonsResult> {const teamId = this.teamIdconst outcomes: MergePersonsSourceResult[] = []- let bootstrapAck: Promise<void> | undefinedlet target = await this.store.fetchForUpdate(teamId, this.targetDistinctId, this.batchId)let sourcesToFold = this.request.sources@@ -550,7 +557,7 @@ export class PostgresPersonMerge {}target = bootstrap.survivoroutcomes.push(...bootstrap.results)- bootstrapAck = bootstrap.kafkaAck+ this.bootstrapAck = bootstrap.kafkaAcksourcesToFold = this.request.sources.filter((source) => source !== bootstrapSource)}@@ -605,7 +612,7 @@ export class PostgresPersonMerge {if (mergeSources.length === 0 && missingSources.length === 0) {const { kafkaAck: reemitAck } = await this.reemitSatisfiedMappings(noopSourceDistinctIds)- const kafkaAck = bootstrapAck ? joinAcks(bootstrapAck, reemitAck) : reemitAck+ const kafkaAck = this.bootstrapAck ? joinAcks(this.bootstrapAck, reemitAck) : reemitAckreturn { survivor: target, results: outcomes, kafkaAck }}@@ -714,7 +721,9 @@ export class PostgresPersonMerge {// ack so the caller observes every message this merge produced.const foldAck = this.produceMessages(kafkaMessages)const { kafkaAck: reemitAck } = await this.reemitSatisfiedMappings(noopSourceDistinctIds)- const kafkaAck = bootstrapAck ? joinAcks(bootstrapAck, foldAck, reemitAck) : joinAcks(foldAck, reemitAck)+ const kafkaAck = this.bootstrapAck+ ? joinAcks(this.bootstrapAck, foldAck, reemitAck)+ : joinAcks(foldAck, reemitAck)for (const source of mergeSources) {// Same fire-and-forget contract as executeTransaction.void this.producePersonMergeEvent(source, mergedPerson).catch(() => {})diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts b/nodejs/src/ingestion/common/persons/person-merge-service.test.tsindex 41bc21afaf67..896c82612ed6 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.test.ts@@ -1,14 +1,24 @@+import { Code, ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import { PersonClaimedByLifecycleOpError } from '~/common/persons/repositories/person-repository'import { parseJSON } from '~/common/utils/json-parse'import { defaultRetryConfig } from '~/common/utils/retries'+import { IngestionWarningLimiter } from '~/common/utils/token-bucket'+import { ingestionWarningCounter } from '~/ingestion/common/ingestion-warnings'import { PluginEvent } from '~/plugin-scaffold'import { InternalPerson, Team } from '~/types'import { PersonContext } from './person-context'import { MergeFoldPlan } from './person-merge-fold'-import { PersonMergeService, mergeFoldFallbackCounter, mergeSettledFailureCounter } from './person-merge-service'+import {+ PersonMergeService,+ mergeClaimDroppedCounter,+ mergeFoldFallbackCounter,+ mergeResponseMismatchCounter,+ mergeSettledFailureCounter,+ mergeUnsettledCounter,+} from './person-merge-service'import {PersonMergeCallFailedError,PersonMergeLimitExceededError,@@ -21,10 +31,8 @@ import {import { MergePersonsOutcome, MergePersonsResult } from './persons-store'import { PersonsStoreForBatch } from './persons-store-for-batch'-async function counterTotal(counter: { get(): Promise<{ values: { value: number }[] }> }): Promise<number> {- const metric = await counter.get()- return metric.values.reduce((sum, v) => sum + v.value, 0)-}+const counterTotal = async (counter: { get: () => Promise<{ values: { value: number }[] }> }): Promise<number> =>+ (await counter.get()).values.reduce((sum, entry) => sum + entry.value, 0)describe('PersonMergeService store-owned merges', () => {const timestamp = DateTime.fromMillis(3_600_000, { zone: 'utc' })@@ -86,6 +94,9 @@ describe('PersonMergeService store-owned merges', () => {beforeEach(() => {defaultRetryConfig.RETRY_INTERVAL_DEFAULT = 0+ // The warning limiter is module-global; a leftover bucket would let+ // one test's emission suppress another's.+ IngestionWarningLimiter.storage.buckets.clear()store = {mergePersons: jest.fn().mockResolvedValue(result('merged')),fetchForUpdate: jest.fn().mockResolvedValue(null),@@ -143,13 +154,14 @@ describe('PersonMergeService store-owned merges', () => {expect(warned).toContain('merge_settled_failure')})- it('attributes a replayed fold verdict to its own source', async () => {- // A fold that failed after the saga recorded its op replays under the- // same op id, carrying every source of the original fold.+ it('attributes a multi-result answer to its own source', async () => {+ // A single-source call cannot legitimately receive two results.+ // Decoding is keyed by source rather than position, so an anomalous+ // answer reads this source's own verdict and stays inert.store.mergePersons.mockResolvedValue({survivor,results: [- { sourceDistinctId: 'anon-9', outcome: 'merged' },+ { sourceDistinctId: 'anon-9', outcome: 'skipped_already_identified' },{ sourceDistinctId: 'anon-1', outcome: 'merged' },],})@@ -158,6 +170,14 @@ describe('PersonMergeService store-owned merges', () => {const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)expect(mergeResult.success && mergeResult.person).toBe(survivor)+ // Our source merged; the sibling did not. Reading the first result+ // rather than this source's would warn about an identified source we+ // never asked about.+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).not.toContain('cannot_merge_already_identified')})it('$merge_dangerously legally merges identified sources', async () => {@@ -166,17 +186,45 @@ describe('PersonMergeService store-owned merges', () => {expect(store.mergePersons.mock.calls[0][0].allowIdentifiedSources).toBe(true)})- it('a merge call failure fails the batch instead of acking through the generic catch', async () => {- // The store wraps verdictless failures in the typed error; the- // backend-agnostic catch must rethrow it — an ack here loses the- // merge whenever the saga did not commit. The Postgres path never- // produces this type, so its handling is untouched.+ it('a merge call failure retries, then acks with the settled-failure warning', async () => {store.mergePersons.mockRejectedValue(new PersonMergeCallFailedError('personhog merge call failed with no verdict', new Error('transport')))const service = makeService()- await expect(service.handleIdentifyOrAlias()).rejects.toThrow(PersonMergeCallFailedError)+ const result = await service.handleIdentifyOrAlias()+ expect(result.success).toBe(true)+ expect(store.mergePersons.mock.calls.length).toBeGreaterThan(1)+ // Postgres gives this loss up silently; the warning is the one+ // deliberate step above parity, so the customer can see it.+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('merge_settled_failure')+ })++ it('a deterministic raw refusal acks once with a warning instead of wedging the batch', async () => {+ // The op_id_reused refusal is deterministic, so rethrowing or+ // retrying would spin on the same refusal until the recorded op+ // ages out. It must ack once and leave a customer-visible trace.+ const before = await counterTotal(ingestionWarningCounter)+ const settledBefore = await counterTotal(mergeSettledFailureCounter)+ store.mergePersons.mockRejectedValue(+ new ConnectError(+ 'op_id was already used for a different request',+ Code.FailedPrecondition,+ new Headers({ 'x-semantic-refusal': 'op_id_reused' })+ )+ )+ const service = makeService()++ await expect(service.handleIdentifyOrAlias()).resolves.not.toThrow()+ expect(store.mergePersons).toHaveBeenCalledTimes(1)+ expect(await counterTotal(ingestionWarningCounter)).toBe(before + 1)+ // The settled-loss series is what a rollout watches; a refusal+ // counted only under the generic failure counter is invisible there.+ expect(await counterTotal(mergeSettledFailureCounter)).toBe(settledBefore + 1)})it.each([@@ -199,16 +247,77 @@ describe('PersonMergeService store-owned merges', () => {expect(warned).toContain('cannot_merge_with_illegal_distinct_id')})- it('a returned conflict verdict surfaces as the claim error without a retry', async () => {- // Both backends surface conflicts as throws rather than returned- // verdicts, so a returned conflict is contract-breaking input the- // backstop must refuse to ack as a merge.- store.mergePersons.mockResolvedValue(result('skipped_conflict'))+ it('an unsettled verdict retries under one request and drops with the race warning', async () => {+ // A retry may change the answer, so it happens in-process under+ // the same op id; exhaustion drops the merge the way Postgres+ // drops a persistent conflict.+ // Snapshots taken per call, so a request mutated or rebuilt between+ // attempts cannot compare equal to itself.+ const seenRequests: unknown[] = []+ store.mergePersons.mockImplementation((request: unknown) => {+ seenRequests.push(structuredClone(request))+ return Promise.resolve({+ survivor: null,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' as const, settled: false }],+ })+ })+ mergeUnsettledCounter.reset()+ mergeClaimDroppedCounter.reset()const service = makeService()- await expect(service.merge('anon-1', 'd1', 1, timestamp)).rejects.toBeInstanceOf(- PersonClaimedByLifecycleOpError- )+ const result = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(result.success).toBe(true)+ expect(seenRequests.length).toBeGreaterThan(1)+ // Every attempt re-presented an identical request, which the op id+ // derives from.+ for (const seen of seenRequests) {+ expect(seen).toEqual(seenRequests[0])+ }+ // One drop, not one count per attempt, and it reads on the same+ // drop-rate series the other race drops feed.+ expect(await counterTotal(mergeUnsettledCounter)).toBe(1)+ expect(await counterTotal(mergeClaimDroppedCounter)).toBe(1)+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('merge_race_condition')+ })++ it('a settled verdict this build cannot name acks as a settled loss', async () => {+ // The settled bit is the durability contract; the outcome name only+ // picks the warning. A newer backend's verdict therefore acks+ // instead of wedging the partition or routing to the DLQ.+ store.mergePersons.mockResolvedValue(result('unknown'))+ mergeSettledFailureCounter.reset()+ const service = makeService()++ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)++ expect(mergeResult.success).toBe(true)+ // 'unknown' may in fact have merged, so it stays off the loss counter.+ expect((await mergeSettledFailureCounter.get()).values[0]?.value ?? 0).toBe(0)+ })++ it('a settled conflict drops with the race warning, as Postgres drops one', async () => {+ store.mergePersons.mockResolvedValue({+ survivor: null,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' as const, settled: true }],+ })+ mergeClaimDroppedCounter.reset()+ const service = makeService()++ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)++ expect(mergeResult.success).toBe(true)expect(store.mergePersons).toHaveBeenCalledTimes(1)+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('merge_race_condition')+ expect(warned).not.toContain('merge_settled_failure')+ // The drop counts on the same series the fold path feeds.+ expect(await counterTotal(mergeClaimDroppedCounter)).toBe(1)})it('an over-limit source returns the limit error result for the merge-mode policy', async () => {@@ -295,27 +404,6 @@ describe('PersonMergeService store-owned merges', () => {expect(mergeResult.success && mergeResult.person).toBe(survivor)})- it('warns on an over-limit source the fold skipped', async () => {- store.mergePersons.mockResolvedValue({- survivor,- results: [- { sourceDistinctId: 'anon-1', outcome: 'merged' },- { sourceDistinctId: 'anon-2', outcome: 'skipped_move_limit' },- ],- })- const service = makeService('$identify', makePlan())-- await service.handleIdentifyOrAlias()-- // The source's own event later reads the executed plan and acks, so- // without this the lost merge leaves no customer-visible trace.- const warned = outputs.queueMessages.mock.calls- .flat(3)- .filter((entry: any) => entry?.value)- .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)- expect(warned).toContain('merge_move_limit_exceeded')- })-it.each([['skipped_illegal', 'cannot_merge_with_illegal_distinct_id'],['skipped_conflict', 'merge_race_condition'],@@ -340,9 +428,11 @@ describe('PersonMergeService store-owned merges', () => {expect(warned).toContain(warningType)})- it('counts a source the fold settled as failed', async () => {- // The warning type is limiter-debounced across tests, so the- // settled-loss counter is the stable observable.+ it('a source the fold settled as failed leaves a customer-visible trace', async () => {+ // The op is terminal and the source's own event later acks, so+ // dropping this arm would make the lost merge silent. Asserted+ // on the counter because the warning is debounced per team and+ // type.const before = await counterTotal(mergeSettledFailureCounter)store.mergePersons.mockResolvedValue({survivor,@@ -358,6 +448,99 @@ describe('PersonMergeService store-owned merges', () => {expect(await counterTotal(mergeSettledFailureCounter)).toBe(before + 1)})+ it('a source dropped to a lifecycle claim counts on the rollout drop signal', async () => {+ const before = await counterTotal(mergeClaimDroppedCounter)+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ const service = makeService('$identify', makePlan())++ await service.handleIdentifyOrAlias()++ // The single-source path counts this drop. Counting only that one+ // makes the rollout's drop rate read low by whatever folds.+ expect(await counterTotal(mergeClaimDroppedCounter)).toBe(before + 1)+ })++ it('awaits a committed bootstrap’s delivery before falling back', async () => {+ const order: string[] = []+ let deliver: () => void = () => {}+ const ack = new Promise<void>((resolve) => {+ deliver = () => {+ order.push('delivered')+ resolve()+ }+ })+ store.mergePersons.mockResolvedValueOnce({+ survivor: null,+ results: [],+ foldAborted: 'conflict',+ kafkaAck: ack,+ })+ store.mergePersons.mockImplementation(() => {+ order.push('fallback')+ return Promise.resolve(result('merged'))+ })+ const service = makeService('$identify', makePlan())++ const running = service.handleIdentifyOrAlias()+ await new Promise((resolve) => setTimeout(resolve, 0))++ // The rollback did not unmake what the bootstrap committed and+ // produced. Falling back before that delivery lets the event ack+ // ahead of a person row that never reached ClickHouse.+ expect(order).toEqual([])+ deliver()+ await running+ expect(order).toEqual(['delivered', 'fallback'])+ })++ it('a rejected bootstrap ack still abandons the aborted fold', async () => {+ store.mergePersons+ .mockImplementationOnce(() =>+ Promise.resolve({+ survivor: null,+ results: [],+ foldAborted: 'conflict',+ kafkaAck: Promise.reject(new Error('produce failed')),+ })+ )+ .mockResolvedValue(result('merged'))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ // The rejection reaches the generic catch; the plan must not be+ // left re-attempting folds for every later event.+ await expect(service.handleIdentifyOrAlias()).resolves.toMatchObject({ success: true })+ expect(plan.status).toBe('abandoned')+ })++ it('a verdict this build cannot name abandons the fold rather than acking the run', async () => {+ store.mergePersons+ .mockResolvedValueOnce({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'unknown' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ .mockResolvedValue(result('merged'))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ await service.handleIdentifyOrAlias()++ // Marking the plan executed would ack every event in the run on+ // a verdict nobody can read. Abandoning sends each event down the+ // single-source path, which fails the batch and redelivers once+ // the fleet has caught up.+ expect(plan.status).toBe('abandoned')+ })+it('a later event of an executed plan short-circuits without a store call', async () => {const plan = makePlan()plan.status = 'executed'@@ -387,6 +570,39 @@ describe('PersonMergeService store-owned merges', () => {expect(mergeResult.success && mergeResult.person).toBe(survivor)})+ it('a fold response missing a verdict for a source fails the batch', async () => {+ store.mergePersons.mockResolvedValue({ survivor, results: [] })+ mergeResponseMismatchCounter.reset()+ const plan = makePlan()+ const service = makeService('$identify', plan)++ await expect(service.handleIdentifyOrAlias()).rejects.toThrow(PersonMergeResponseMismatchError)+ // The stall this causes must be attributable on the mismatch series.+ expect(await counterTotal(mergeResponseMismatchCounter)).toBe(1)+ })++ it('a fold whose call returned no verdict falls back to sequential merges', async () => {+ // A fence the saga still holds drops the sequential re-merges+ // with race warnings until the sweeper settles it.+ store.mergePersons.mockRejectedValue(new PersonMergeCallFailedError('no verdict', new Error('transport')))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ const result = await service.handleIdentifyOrAlias()+ expect(result.success).toBe(true)+ expect(plan.status).toBe('abandoned')+ })++ it('a mismatched merge response fails the batch instead of acking', async () => {+ // The merge never happened, so acking would lose it permanently:+ // the generic catch below returns success, and redelivery is the+ // only thing that could still complete it.+ store.mergePersons.mockRejectedValue(new PersonMergeResponseMismatchError('no verdict for anon-1'))+ const service = makeService('$identify', makePlan())++ await expect(service.handleIdentifyOrAlias()).rejects.toThrow(PersonMergeResponseMismatchError)+ })+it('carries the triggering source for the cold-start bootstrap', async () => {store.mergePersons.mockResolvedValue({survivor,@@ -410,9 +626,12 @@ describe('PersonMergeService store-owned merges', () => {{ sourceDistinctId: 'anon-2', outcome: 'skipped_already_identified' },],})- outputs.queueMessages.mockRejectedValue(new Error('broker down'))const plan = makePlan()const service = makeService('$identify', plan)+ // Stubbed on the service rather than through queueMessages:+ // emitIngestionWarning swallows a produce rejection and answers+ // false, so a rejecting broker never reaches the catch this pins.+ jest.spyOn(service as any, 'emitFoldWarnings').mockRejectedValue(new Error('warning emission failed'))const mergeResult = await service.handleIdentifyOrAlias()diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.tsindex a370945c5971..21ea782119a4 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts@@ -1,3 +1,4 @@+import { ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import { Counter } from 'prom-client'@@ -18,6 +19,7 @@ import {PersonMergeLimitExceededError,PersonMergeResponseMismatchError,PersonMergeResult,+ PersonMergeUnsettledError,SourcePersonHasDistinctIdsError,SourcePersonNotFoundError,TargetPersonNotFoundError,@@ -46,6 +48,17 @@ export const mergeFoldFallbackCounter = new Counter({labelNames: ['reason'],})+export const mergeResponseMismatchCounter = new Counter({+ name: 'person_merge_response_mismatch_total',+ help: 'Merge responses carrying no verdict for the source that was asked about, which stalls the partition.',+ labelNames: ['call'],+})++export const mergeUnsettledCounter = new Counter({+ name: 'person_merge_unsettled_total',+ help: 'Merges still unsettled after every in-process retry, dropped with the race warning.',+})+export const mergeSettledFailureCounter = new Counter({name: 'person_merge_settled_failure_total',help: 'Merges the merge backend settled on a verdict that merged nothing.',@@ -127,11 +140,9 @@ export class PersonMergeService {}} catch (e) {if (e instanceof PersonClaimedByLifecycleOpError) {- // Expected contention, not a failure: another lifecycle operation held one of- // the persons through every retry. Drop the merge with a warning; the event's- // property updates still apply to whatever the distinct ids resolve to next.- // The counter is the rollout's drop-rate signal; the warning is debounced by- // the standard limiter so a long-held claim cannot flood the warnings topic.+ // Expected contention: another lifecycle op held a person+ // through every retry. Drop with a warning; the counter is+ // the drop-rate signal and the warning is debounced.mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {type: 'merge_race_condition',@@ -151,20 +162,12 @@ export class PersonMergeService {})return mergeSuccess(undefined, warningAck, true)}- // Both carry no settled verdict; their class docs explain why the- // batch must fail and redeliver rather than ack.- if (e instanceof PersonMergeResponseMismatchError || e instanceof PersonMergeCallFailedError) {+ if (e instanceof PersonMergeResponseMismatchError) {+ // A malformed answer is a bug detector; fail the batch.throw e}- captureException(e, {- tags: { team_id: this.context.team.id, pipeline_step: 'processPersonsStep' },- extra: {- location: 'handleIdentifyOrAlias',- distinctId: this.context.distinctId,- anonId: String(this.context.eventProperties['$anon_distinct_id']),- alias: String(this.context.eventProperties['alias']),- },- })+ // PersonMergeCallFailedError falls through: bounded retries ran,+ // so it takes the same give-up the Postgres path has always had.mergeFinalFailuresCounter.labels({backend: this.context.personStore.backend,@@ -172,14 +175,72 @@ export class PersonMergeService {error: e instanceof Error ? e.constructor.name : 'unknown',}).inc()- logger.error('handleIdentifyOrAlias failed', {- error: e,- team_id: this.context.team.id,- distinctId: this.context.distinctId,- event_name: this.context.event.event,- anon_distinct_id: String(this.context.eventProperties['$anon_distinct_id']),- alias: String(this.context.eventProperties['alias']),- })+ if (e instanceof ConnectError) {+ // A raw refusal is a designed verdict no redelivery can+ // change: acked as a settled loss with the customer-visible+ // warning rather than filling error tracking.+ mergeSettledFailureCounter.inc()+ logger.warn('🤔', 'merge refused deterministically; settled as lost', {+ team_id: this.context.team.id,+ distinctId: this.context.distinctId,+ event_name: this.context.event.event,+ error: String(e),+ })+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_settled_failure',+ details: {+ distinctId: this.context.distinctId,+ eventUuid: this.context.event.uuid,+ sourcePersonDistinctId: String(+ this.context.eventProperties['$anon_distinct_id'] ?? this.context.eventProperties['alias']+ ),+ targetPersonDistinctId: this.context.distinctId,+ outcome: 'refused',+ },+ pipelineStep: 'person-merge',+ }).then(() => undefined)+ return mergeSuccess(undefined, warningAck, true)+ } else if (e instanceof PersonMergeCallFailedError) {+ // Bounded retries ran; give up as Postgres does, but warned.+ logger.warn('🤔', 'merge call failed through every retry; given up with a warning', {+ team_id: this.context.team.id,+ distinctId: this.context.distinctId,+ event_name: this.context.event.event,+ error: String(e),+ })+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_settled_failure',+ details: {+ distinctId: this.context.distinctId,+ eventUuid: this.context.event.uuid,+ sourcePersonDistinctId: String(+ this.context.eventProperties['$anon_distinct_id'] ?? this.context.eventProperties['alias']+ ),+ targetPersonDistinctId: this.context.distinctId,+ outcome: 'call_failed',+ },+ pipelineStep: 'person-merge',+ }).then(() => undefined)+ return mergeSuccess(undefined, warningAck, true)+ } else {+ captureException(e, {+ tags: { team_id: this.context.team.id, pipeline_step: 'processPersonsStep' },+ extra: {+ location: 'handleIdentifyOrAlias',+ distinctId: this.context.distinctId,+ anonId: String(this.context.eventProperties['$anon_distinct_id']),+ alias: String(this.context.eventProperties['alias']),+ },+ })+ logger.error('handleIdentifyOrAlias failed', {+ error: e,+ team_id: this.context.team.id,+ distinctId: this.context.distinctId,+ event_name: this.context.event.event,+ anon_distinct_id: String(this.context.eventProperties['$anon_distinct_id']),+ alias: String(this.context.eventProperties['alias']),+ })+ }} finally {clearTimeout(timeout)}@@ -221,11 +282,53 @@ export class PersonMergeService {[{ distinctId: otherPersonDistinctId, eventUuid: this.context.event.uuid }],timestamp)- // The store owns the whole merge, its own record-escape retries- // included: retryable conflicts surface here as throws, and each- // re-entry runs against fresh state.- const result = await promiseRetry(() => this.context.personStore.mergePersons(request), 'merge_distinct_ids')- return this.mapSingleSourceResult(result, otherPersonDistinctId, mergeIntoDistinctId)+ // The store owns the whole merge; retryable Postgres conflicts+ // surface as throws and each re-entry runs against fresh state. A+ // raw ConnectError is a deterministic refusal the store+ // deliberately unwrapped; retrying re-runs the same comparison.+ // Mapping inside the retry lets an unsettled verdict re-present the+ // same op id, which the saga's conflict discard was built for.+ try {+ return await promiseRetry(+ async () =>+ this.mapSingleSourceResult(+ await this.context.personStore.mergePersons(request),+ otherPersonDistinctId,+ mergeIntoDistinctId+ ),+ 'merge_distinct_ids',+ undefined,+ undefined,+ undefined,+ [ConnectError, PersonMergeResponseMismatchError]+ )+ } catch (error) {+ if (!(error instanceof PersonMergeUnsettledError)) {+ throw error+ }+ // Retries exhausted without a settled answer: dropped with the+ // race warning, as Postgres drops a persistent conflict. The+ // drop also counts on the claim-drop series, so the drop rate+ // reads whole across both backends.+ mergeUnsettledCounter.inc()+ mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()+ const warningAck = emitIngestionWarning(this.context.outputs, teamId, {+ type: 'merge_race_condition',+ details: {+ sourcePersonDistinctId: otherPersonDistinctId,+ targetPersonDistinctId: mergeIntoDistinctId,+ distinctId: mergeIntoDistinctId,+ eventUuid: this.context.event.uuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,+ }).then(() => undefined)+ logger.warn('🤔', 'merge unsettled through every retry; dropped with the race warning', {+ team_id: teamId,+ distinct_id: mergeIntoDistinctId,+ })+ return mergeSuccess(undefined, warningAck, true)+ }}/**@@ -248,10 +351,9 @@ export class PersonMergeService {eventUuid: this.context.event.uuid,allowIdentifiedSources: this.context.event.event === '$merge_dangerously',mergeMode: this.context.mergeMode,- // Passed as the event stated it, pre-epoch values included: what a- // backend can store is the backend's constraint, and clamping here- // would rewrite the created_at Postgres records for a person born- // from a merge.+ // Passed as the event stated it, pre-epoch values included:+ // clamping here would rewrite the created_at Postgres records+ // for a merge-born person.createdAtMs: timestamp.toMillis(),}}@@ -305,6 +407,9 @@ export class PersonMergeService {// batch instead of being absorbed by the fallback.throw error}+ // A no-verdict call falls back too: a fence the saga still+ // holds drops sequential merges with race warnings until the+ // sweeper settles it.// Any other failure falls back to the sequential path: the current// event re-runs its own merge (a no-op if the fold partially// landed), and later events process individually with full retries.@@ -318,10 +423,33 @@ export class PersonMergeService {return null}if (result.foldAborted) {- // The store already logged its abort with the underlying error.+ // Abandon before the await, so a rejected ack cannot leave the+ // plan re-attempting folds.this.abandonFold(plan, result.foldAborted)+ // An abort can still carry an ack (a bootstrap committed before+ // the fold); awaiting keeps the event from acking ahead of its+ // own writes.+ if (result.kafkaAck) {+ await result.kafkaAck+ }return null}+ // Every requested source must carry a verdict; a response missing+ // one is malformed, not an answer.+ for (const source of request.sources) {+ if (!result.results.some((r) => r.sourceDistinctId === source.distinctId)) {+ mergeResponseMismatchCounter.labels({ call: this.context.event.event }).inc()+ logger.error('fold response carried no verdict for a requested source; failing the batch', {+ team_id: this.context.team.id,+ event_uuid: this.context.event.uuid,+ source_distinct_id: source.distinctId,+ target_distinct_id: request.targetDistinctId,+ })+ throw new PersonMergeResponseMismatchError(+ `merge response for team ${this.context.team.id} carried no verdict for a folded source`+ )+ }+ }if (!result.survivor) {const reason = result.results[0]?.outcome === 'skipped_move_limit' ? 'limit' : 'error'this.abandonFold(plan, reason)@@ -334,6 +462,22 @@ export class PersonMergeService {return null}+ // A verdict this build cannot name comes from a backend a release+ // ahead, so whether that source merged is unknown. The fold gives up+ // rather than ack the whole run on that unknown, and each event+ // decides for itself.+ const unnamed = result.results.find((source) => source.outcome === 'unknown')+ if (unnamed !== undefined) {+ this.abandonFold(plan, 'error')+ logger.warn('🤔', 'fold settled a source on a verdict this build cannot name', {+ team_id: this.context.team.id,+ source_distinct_id: unnamed.sourceDistinctId,+ target_distinct_id: request.targetDistinctId,+ pairs: plan.pairs.length,+ })+ return null+ }+plan.status = 'executed'plan.mergedPerson = result.survivor// Warning acks ride the result's kafkaAck to the batch-end await@@ -369,12 +513,29 @@ export class PersonMergeService {// answer.const sourceResult = result.results.find((source) => source.sourceDistinctId === otherPersonDistinctId)if (sourceResult === undefined) {- // A malformed response rather than a settled answer, so it must- // not take the settled-failure path below.+ // A missing verdict says nothing about what happened, so it+ // must not ack as a settled loss; the saga replays per op id,+ // so failing here stalls the partition by design.+ mergeResponseMismatchCounter.labels({ call: this.context.event.event }).inc()+ logger.error('merge response carried no verdict for its requested source; failing the batch', {+ team_id: this.context.team.id,+ event_uuid: this.context.event.uuid,+ source_distinct_id: otherPersonDistinctId,+ target_distinct_id: mergeIntoDistinctId,+ verdicts: result.results.map((source) => source.sourceDistinctId),+ })throw new PersonMergeResponseMismatchError(`merge response for team ${this.context.team.id} carried no verdict for its requested source`)}+ if (sourceResult.settled === false) {+ // The backend states a retry under the same op id can change+ // this answer (claim contention whose record is discarded); the+ // caller retries in place and counts one drop on exhaustion.+ throw new PersonMergeUnsettledError(+ `merge verdict for team ${this.context.team.id} is unsettled; a retry under the same op id may settle it`+ )+ }const outcome = sourceResult.outcomeconst survivor = result.survivor ?? undefinedconst kafkaAck = result.kafkaAck ?? Promise.resolve()@@ -424,9 +585,11 @@ export class PersonMergeService {true)}+ case 'skipped_conflict':case 'skipped_race': {- // A concurrent merge kept winning the persons through every- // retry; the merge drops and the target stays the survivor.+ // A rival operation kept the persons through every retry;+ // the merge drops with pg's race warning.+ mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {type: 'merge_race_condition',details: {@@ -449,14 +612,6 @@ export class PersonMergeService {true)}- case 'skipped_conflict':- // Normally converted into a throw inside the retry loop;- // this backstop keeps the claim-dropped semantics for any- // path that maps the outcome directly.- throw new PersonClaimedByLifecycleOpError(- 'merge saga: a live lifecycle operation holds a person in this merge',- this.context.team.id- )case 'skipped_move_limit':// The over-limit path: the caller's merge-mode policy// (redirect, DLQ) decides what happens to the event.@@ -471,17 +626,17 @@ export class PersonMergeService {'Cannot delete source person due to concurrent distinct ID additions'))+ case 'skipped_refused':case 'error':+ case 'unknown':default: {- // A verdict, not a transient fault: the merge backend records it- // against the op id and replays it for the retention window, so- // neither this event's retry nor its redelivery can reach a- // different answer, and failing the batch would stall the- // partition instead of healing. The merge is lost; the event's- // property updates still apply, and the customer's next- // $identify carries a fresh op id that can succeed. Acked, but- // never silently.- mergeSettledFailureCounter.inc()+ // A settled verdict no retry can change: acked with the+ // warning, never silently; a fresh op id can succeed later.+ // 'unknown' may in fact have merged, so it skips the loss+ // counter.+ if (outcome !== 'unknown') {+ mergeSettledFailureCounter.inc()+ }const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {type: 'merge_settled_failure',details: {@@ -489,20 +644,25 @@ export class PersonMergeService {targetPersonDistinctId: mergeIntoDistinctId,distinctId: mergeIntoDistinctId,eventUuid: this.context.event.uuid,- // The Postgres backend names the person by uuid; the saga- // reports a row id and no uuid, so both travel and- // whichever exists identifies the person.+ // Both travel because each backend names the person+ // differently.otherPersonId: sourceResult.sourcePersonUuid,sourcePersonId: sourceResult.sourcePersonId,outcome,},pipelineStep: 'person-merge',})- logger.warn('🤔', 'merge settled without merging; the pair stays unmerged', {- team_id: this.context.team.id,- outcome,- event_uuid: this.context.event.uuid,- })+ logger.warn(+ '🤔',+ outcome === 'unknown'+ ? 'merge settled on a verdict this build cannot name; whether it merged is unknown'+ : 'merge settled without merging; the pair stays unmerged',+ {+ team_id: this.context.team.id,+ outcome,+ event_uuid: this.context.event.uuid,+ }+ )return mergeSuccess(undefined,Promise.all([kafkaAck, warningAck]).then(() => undefined),@@ -554,6 +714,9 @@ export class PersonMergeService {breakcase 'skipped_conflict':case 'skipped_race':+ // The same drop the single-source path counts; skipping+ // it here makes the drop rate read low by the folded share.+ mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()warningAcks.push(emitIngestionWarning(this.context.outputs, this.context.team.id, {type: 'merge_race_condition',@@ -569,39 +732,9 @@ export class PersonMergeService {}))break- case 'skipped_move_limit':- // Only the saga answers this inside an executed fold; the- // Postgres merge aborts the whole fold instead. The- // source's event acks without its merge (and without the- // ASYNC redirect the sequential path would give it), so- // the warning is what keeps the loss identifiable.- mergeMoveLimitDroppedCounter.labels({ path: 'fold' }).inc()- warningAcks.push(- emitIngestionWarning(this.context.outputs, this.context.team.id, {- type: 'merge_move_limit_exceeded',- details: {- sourcePersonDistinctId: sourceResult.sourceDistinctId,- targetPersonDistinctId: request.targetDistinctId,- distinctId: request.targetDistinctId,- eventUuid,- otherPersonId: sourceResult.sourcePersonUuid,- eventDropped: false,- },- pipelineStep: 'person-merge',- })- )- logger.warn('🤔', 'fold skipped an over-limit source; its merge is dropped', {- team_id: this.context.team.id,- source_distinct_id: sourceResult.sourceDistinctId,- target_distinct_id: request.targetDistinctId,- event_uuid: eventUuid,- })- breakcase 'error':- // The merge for this source did not happen and the op is- // terminal, so redelivery cannot reach a different- // answer. The single-source path treats this as a- // settled failure; a fold has to say so too, or the+ // The op is terminal, so redelivery cannot change the+ // answer; a fold must record the settled failure or the// loss is invisible.mergeSettledFailureCounter.inc()warningAcks.push(diff --git a/nodejs/src/ingestion/common/persons/person-merge-types.ts b/nodejs/src/ingestion/common/persons/person-merge-types.tsindex 3504a353fd12..739c5c369418 100644--- a/nodejs/src/ingestion/common/persons/person-merge-types.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-types.ts@@ -38,10 +38,9 @@ export class PersonMergeResponseMismatchError extends PersonMergeError {}/**- * A merge call that failed with no verdict at all, so the saga's state is- * unknowable from here. The batch must fail and redeliver: the saga replays- * recorded outcomes idempotently, so redelivery converges where an ack- * would lose the merge. Personhog-only; the Postgres merge never throws it.+ * A merge call that failed with no verdict at all. Retried in-process+ * under the same op id; exhaustion gives up the way the Postgres path+ * does. Personhog-only; the Postgres merge never throws it.*/export class PersonMergeCallFailedError extends PersonMergeError {readonly type = 'CALL_FAILED' as const@@ -54,6 +53,15 @@ export class PersonMergeCallFailedError extends PersonMergeError {}}+/**+ * The merge backend answered an unsettled verdict: a retry under the same+ * op id may change the answer. Retried in-process; exhaustion drops the+ * merge with the race warning, as Postgres drops a persistent conflict.+ */+export class PersonMergeUnsettledError extends PersonMergeError {+ readonly type = 'UNSETTLED' as const+}+/*** Error when race condition is detected during merge*/diff --git a/nodejs/src/ingestion/common/persons/person-update.test.ts b/nodejs/src/ingestion/common/persons/person-update.test.tsindex 8d9c2291753c..f68e5af5ae9c 100644--- a/nodejs/src/ingestion/common/persons/person-update.test.ts+++ b/nodejs/src/ingestion/common/persons/person-update.test.ts@@ -847,7 +847,7 @@ describe('person-update', () => {// 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.+ // representable, write segments in order.const segments: EventOps[] = [opsList[0]]for (const o of opsList.slice(1)) {const folded = foldOps(segments[segments.length - 1], o)@@ -940,7 +940,7 @@ describe('person-update', () => {['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+ // value" has no lane representation; the caller must write 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()@@ -1022,7 +1022,7 @@ describe('person-update', () => {if (folded === null) {expect(SEGMENTS.has(`${stateLabel}|${inLabel}`)).toBe(true)- // A cut segment ships each side as its own leader+ // A cut segment writes each side as its own leader// call, which is the sequential application above// by construction — nothing further to assert.returndiff --git a/nodejs/src/ingestion/common/persons/person-update.ts b/nodejs/src/ingestion/common/persons/person-update.tsindex afc9328a2201..5ca6af3d4d6c 100644--- a/nodejs/src/ingestion/common/persons/person-update.ts+++ b/nodejs/src/ingestion/common/persons/person-update.ts@@ -30,7 +30,7 @@ export interface PropertyUpdates {* 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+ * against its snapshot; the personhog store writes them for the leader to* resolve authoritatively.*/export interface EventOps {@@ -242,7 +242,7 @@ export function refineEventOps(* 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+ * combination expresses. The caller then cuts a segment, writing the* accumulated ops as their own leader call so authoritative refinement* happens between the two.*/diff --git a/nodejs/src/ingestion/common/persons/person-uuid.test.ts b/nodejs/src/ingestion/common/persons/person-uuid.test.tsindex 9bc70992567d..f5f882108d9f 100644--- a/nodejs/src/ingestion/common/persons/person-uuid.test.ts+++ b/nodejs/src/ingestion/common/persons/person-uuid.test.ts@@ -1,4 +1,8 @@-import { lifecycleOpIdFromEvent, uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'+import {+ lifecycleOpIdFromEvent,+ mergeOpIdFromRequest,+ uuidFromDistinctId,+} from '~/ingestion/common/persons/person-uuid'jest.setTimeout(5000) // 5 sec timeout@@ -17,3 +21,54 @@ describe('lifecycleOpIdFromEvent', () => {expect(lifecycleOpIdFromEvent(1, 'event-uuid')).not.toBe(lifecycleOpIdFromEvent(1, 'other-event'))})})++describe('mergeOpIdFromRequest', () => {+ it('separates a multi-source fold from the single-source merges it falls back to', () => {+ // The saga freezes the request behind this key and rejects any later+ // call presenting it with a different source list, so sharing one key+ // between the two shapes loses the fallback merge entirely. A+ // single-pair fold has the same source list as its fallback and+ // shares the key on purpose: the fallback resumes the recorded op.+ const fold = mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1', 'anon-2'], 10_000)+ const single = mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000)+ expect(fold).not.toEqual(single)+ })++ it('gives different move limits different keys', () => {+ // skipped_move_limit is a recorded verdict; the async re-attempt's+ // whole purpose is a raised limit, so it must be a fresh op rather+ // than attach to the skip. Same-limit retries keep replaying.+ expect(mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000)).not.toEqual(+ mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 50_000)+ )+ })++ it('gives differently ordered source lists different keys', () => {+ // Source order is property precedence, and the saga compares its+ // frozen request in order: one key for two orders would make the+ // second call a permanent FAILED_PRECONDITION instead of a fresh+ // op that converges as a no-op.+ expect(mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-2', 'anon-1'], 10_000)).not.toEqual(+ mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1', 'anon-2'], 10_000)+ )+ })++ it('cannot collide two source lists that join to one string', () => {+ // Distinct ids are arbitrary customer strings; without length+ // prefixes, ['a,b'] and ['a','b'] would share a key and the second+ // merge would be refused as a replay of the first.+ expect(mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['a,b'], 10_000)).not.toEqual(+ mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['a', 'b'], 10_000)+ )+ })++ it('scopes the key per team', () => {+ expect(mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000)).not.toEqual(+ mergeOpIdFromRequest(2, 'event-uuid', 'd1', ['anon-1'], 10_000)+ )+ // Two events sharing a uuid must not collide across targets.+ expect(mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000)).not.toEqual(+ mergeOpIdFromRequest(1, 'event-uuid', 'd2', ['anon-1'], 10_000)+ )+ })+})diff --git a/nodejs/src/ingestion/common/persons/person-uuid.ts b/nodejs/src/ingestion/common/persons/person-uuid.tsindex e3d227966963..235bdf34dec8 100644--- a/nodejs/src/ingestion/common/persons/person-uuid.ts+++ b/nodejs/src/ingestion/common/persons/person-uuid.ts@@ -18,3 +18,27 @@ export function uuidFromDistinctId(teamId: number, distinctId: string): string {export function lifecycleOpIdFromEvent(teamId: number, eventUuid: string): string {return uuidv5(`${teamId}:${eventUuid}`, LIFECYCLE_OP_UUIDV5_NAMESPACE)}++/**+ * The merge saga's idempotency key. A multi-source fold and its per-source+ * fallback merges derive different ids through the source list, while a+ * single-pair fold deliberately shares its id with its fallback, whose+ * retry then attaches to and resumes the same recorded op. Source order+ * and the length-prefixed encoding are part of the identity, so a comma+ * inside a distinct id cannot make two source lists read as one.+ */+export function mergeOpIdFromRequest(+ teamId: number,+ eventUuid: string,+ targetDistinctId: string,+ sourceDistinctIds: string[],+ moveLimit: number+): string {+ // The move limit is part of the op's identity: a redirected re-attempt+ // with a raised limit must derive a fresh op rather than attach to the+ // recorded skip it exists to overcome. The target is too, so two events+ // sharing a uuid cannot collide across different merges.+ const sources = sourceDistinctIds.map((distinctId) => `${distinctId.length}:${distinctId}`).join(',')+ const target = `${targetDistinctId.length}:${targetDistinctId}`+ return uuidv5(`${teamId}:${eventUuid}:${moveLimit}:${target}:${sources}`, LIFECYCLE_OP_UUIDV5_NAMESPACE)+}diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.tsindex bb1c5a068464..30cf63318bb7 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts@@ -1,18 +1,40 @@+import { Code, ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'-import { PersonhogPropertiesSizeError } from '~/common/personhog/persons'+import { PersonhogFencedError, PersonhogPropertiesSizeError } from '~/common/personhog/persons'+import { PersonClaimedByLifecycleOpError } from '~/common/persons/repositories/person-repository'import { NoRowsUpdatedError } from '~/common/utils/utils'import { InternalPerson } from '~/types'-import { extractEventOps } from './person-update'-import { PersonhogPendingRpcError, PersonhogPersonsStore } from './personhog-persons-store'+import { PersonMergeCallFailedError, createDefaultSyncMergeMode } from './person-merge-types'+import { EventOps, extractEventOps } from './person-update'+import { mergeOpIdFromRequest } from './person-uuid'+import {+ PersonhogPersonsStore,+ PersonhogUnsupportedFieldError,+ personhogStoreCachePurgeCounter,+ personhogStoreFlushCounter,+ personhogStoreFlushErrorCounter,+ personhogStoreMergeDrainCounter,+ personhogStoreShadowShedCounter,+} from './personhog-persons-store'++const counterTotal = async (counter: { get: () => Promise<{ values: { value: number }[] }> }): Promise<number> =>+ (await counter.get()).values.reduce((sum, entry) => sum + entry.value, 0)describe('PersonhogPersonsStore', () => {let repository: jest.Mocked<PersonHogPersonWriteRepository>let store: PersonhogPersonsStorelet person: InternalPerson+ // The cache has no public inspection surface; these reach the maps the+ // assertions are about.+ const edgeOf = (distinctKey: string): string | null | undefined => (store as any).resolutions.get(distinctKey)+ const hasProjection = (personKey: string): boolean => (store as any).projections.has(personKey)+ const projectionOf = (personKey: string): InternalPerson | undefined => (store as any).projections.get(personKey)+ const projectionCount = (): number => (store as any).projections.size+const ops = (properties: Record<string, unknown>, event = '$set') =>extractEventOps({event,@@ -43,13 +65,123 @@ describe('PersonhogPersonsStore', () => {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 }),+ // Answering the document unchanged would model a leader that+ // ignored the ops it was sent.+ updatePersonProperties: jest.fn().mockImplementation((request: any) => {+ const properties = { ...person.properties }+ for (const [key, value] of Object.entries(request.setOnceProperties ?? {})) {+ if (!(key in properties)) {+ properties[key] = value+ }+ }+ Object.assign(properties, request.setProperties ?? {})+ for (const key of request.unsetProperties ?? []) {+ delete properties[key]+ }+ return Promise.resolve({+ person: {+ ...person,+ version: 2,+ properties,+ is_identified: request.isIdentified ? true : person.is_identified,+ // The leader max-merges this rather than taking the+ // request's value, so an out-of-order event cannot+ // walk it backwards.+ last_seen_at:+ request.lastSeenAtMs &&+ (!person.last_seen_at || request.lastSeenAtMs > person.last_seen_at.toMillis())+ ? DateTime.fromMillis(request.lastSeenAtMs, { zone: 'utc' })+ : person.last_seen_at,+ },+ updated: true,+ })+ }),getDistinctIdsForPersons: jest.fn().mockResolvedValue({}),getOrCreatePersonByDistinctId: jest.fn().mockResolvedValue({ person, created: true }),} as unknown as jest.Mocked<PersonHogPersonWriteRepository>store = new PersonhogPersonsStore(repository)})+ it.each([0, -1, 1.5])('refuses a max concurrent updates of %p at construction', (maxConcurrentUpdates) => {+ // pLimit throws on these, and it is built after lanes are claimed for+ // a write: the throw leaves them marked in flight with nothing left+ // to clear the mark, so every later pass defers them and the flush+ // exhausts its rounds. In shadow the whole thing is swallowed.+ expect(() => new PersonhogPersonsStore(repository, { maxConcurrentUpdates })).toThrow(+ 'PERSONHOG_STORE_MAX_CONCURRENT_UPDATES must be an integer >= 1'+ )+ })++ it.each([0, -1, 1.5])('refuses a sync merge move limit of %p at construction', (syncMergeMoveLimit) => {+ // Below 1 the saga skips every merge; a non-integer throws a RangeError+ // inside BigInt() at merge time. Both lose merges deployment-wide.+ expect(() => new PersonhogPersonsStore(repository, { syncMergeMoveLimit })).toThrow(+ 'PERSONHOG_SYNC_MERGE_MOVE_LIMIT must be an integer >= 1'+ )+ })++ it.each([0, -1, 1.5])('refuses a request timeout of %p at construction', (requestTimeoutMs) => {+ // The flush's lane wait budget derives from it; a bad value would+ // make every flush give up instantly or never.+ expect(() => new PersonhogPersonsStore(repository, { requestTimeoutMs })).toThrow(+ 'PERSONHOG_TIMEOUT_MS must be an integer >= 1'+ )+ })++ it('keeps an entry writable when the redirect resolve fails transiently', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ repository.updatePersonProperties.mockRejectedValueOnce(new NoRowsUpdatedError('merged away') as never)+ repository.resolvePersonsByDistinctIds.mockRejectedValue(new Error('identity unavailable') as never)++ await expect(bound.flush()).rejects.toThrow('identity unavailable')++ // A throw skips the success path, so an in-flight mark left set would+ // make every later pass skip this entry and strand its ops.+ // Cleared so only a fresh write on the second pass can satisfy this.+ repository.updatePersonProperties.mockClear()+ repository.updatePersonProperties.mockResolvedValue({ person, updated: true } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([])+ await bound.flush()+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(+ expect.objectContaining({ setProperties: { a: '1' } }),+ expect.any(String)+ )+ })++ it('ops folded during a write land behind it rather than in it', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ let releaseWrite: () => void = () => {}+ let writeStarted: () => void = () => {}+ const writing = new Promise<void>((resolve) => {+ writeStarted = resolve+ })+ repository.updatePersonProperties.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ writeStarted()+ releaseWrite = () => resolve({ person, updated: true } as never)+ }) as never+ )++ const flushing = bound.flush()+ await writing+ // Folded while the first payload is on the wire: merging into it+ // would change what is being sent, and truncating the snapshot+ // afterwards would take this event with it.+ await bound.applyEventOps(person, ops({ $set: { b: '2' } }), 'd1')+ releaseWrite()+ await flushing++ expect(repository.updatePersonProperties.mock.calls[0][0].setProperties).toEqual({ a: '1' })++ repository.updatePersonProperties.mockClear()+ await bound.flush()+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)+ expect(repository.updatePersonProperties.mock.calls[0][0].setProperties).toEqual({ b: '2' })+ })+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')@@ -64,7 +196,7 @@ describe('PersonhogPersonsStore', () => {expect(sent.setProperties).toEqual({ a: '2', first: 'shadowed' })expect(sent.setOnceProperties).toEqual({})expect(sent.unsetProperties).toEqual(['gone'])- // The changelog is this backend's ClickHouse feed: a flush ships+ // The changelog is this backend's ClickHouse feed: a flush writes// segments and publishes nothing.expect(results).toEqual([])})@@ -84,44 +216,35 @@ describe('PersonhogPersonsStore', () => {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 () => {+ describe('every lane reaches the leader, carrying the event force flag', () => {+ // Classification moved server-side: the leader decides whether a+ // filtered-only lane writes, so the store must send everything and+ // the force flag is what the leader classifies under.+ it('a filtered-only lane still writes, unforced', 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)+ expect(repository.updatePersonProperties.mock.calls[0][0].forceUpdate).toBe(false)})- it('a scalar move ships without property changes', async () => {+ it('a person event writes forced', async () => {+ person.properties = { $browser: 'Firefox' }const bound = store.forBatch(0)- const scalarOnly = ops({}, 'pageview')- scalarOnly.isIdentified = true- await bound.applyEventOps(person, scalarOnly, 'd1')+ await bound.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, '$set'), 'd1')await bound.flush()expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)+ expect(repository.updatePersonProperties.mock.calls[0][0].forceUpdate).toBe(true)})- it('one update-worthy event makes the whole lane ship', async () => {- person.properties = { $browser: 'Firefox' }+ it('a forced event folded behind an unforced one forces the segment', async () => {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.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, '$set'), 'd1')await bound.flush()expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)+ expect(repository.updatePersonProperties.mock.calls[0][0].forceUpdate).toBe(true)})})@@ -133,7 +256,7 @@ describe('PersonhogPersonsStore', () => {expect(results).toEqual([])})- it('a denied event still ships its scalars, without its properties', async () => {+ it('a denied event still writes its scalars, without its properties', async () => {const bound = store.forBatch(0)const denied = ops({ $set: { a: '1' } }, '$exception')denied.lastSeenAtMs = 7_200_000@@ -179,17 +302,51 @@ describe('PersonhogPersonsStore', () => {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 }])+ 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' } } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, version: 5, properties: { plan: 'fresh' } } as never)const bound = store.forBatch(0)- const fetched = await bound.fetchForUpdate(1, 'd1')- expect(fetched?.id).toBe('7')- expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)++ const checked = await bound.fetchForChecking(1, 'd1')+ expect(checked?.properties).toEqual({ plan: 'lagged' })+ 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.+ const updated = await bound.fetchForUpdate(1, 'd1')+ expect(updated?.properties).toEqual({ plan: 'fresh' })+ expect(repository.fetchPersonById).toHaveBeenCalledTimes(1)++ // Upgraded once: the next update read serves the memo.+ await bound.fetchForUpdate(1, 'd1')expect(repository.fetchPersonById).toHaveBeenCalledTimes(1)})+ it('prefetch resolves a whole batch in one call instead of one per id', async () => {+ // The saving is the batching, not the caching: without a prefetch+ // each id resolves on its own. A single id cannot show the+ // difference, because one lazy resolve and one prefetched resolve+ // are both one call.+ const ids = ['d1', 'd2', 'd3']+ repository.resolvePersonsByDistinctIds.mockImplementation(((keys: { distinctId: string }[]) =>+ Promise.resolve(keys.map(({ distinctId }) => ({ teamId: 1, distinctId, person: { ...person } })))) as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)++ // Ordered as production does it: the prefetch step reaches the store+ // through the batch handle, so the batch exists before it fires.+ const bound = store.forBatch(0)+ await store.prefetchPersons(ids.map((distinctId) => ({ teamId: 1, distinctId, batchId: 0 })))+ for (const distinctId of ids) {+ expect((await bound.fetchForUpdate(1, distinctId))?.id).toBe('7')+ }++ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ expect(repository.resolvePersonsByDistinctIds.mock.calls[0][0]).toHaveLength(ids.length)+ })+it('a stale null result cannot downgrade a live mapping', async () => {repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }])repository.fetchPersonById.mockResolvedValue({ ...person })@@ -199,7 +356,10 @@ describe('PersonhogPersonsStore', () => {// A late prefetch response reporting absence must not erase the// resolved mapping.- ;(store as any).recordFetch(1, 'd1', null, 0)+ ;(store as any).cacheFetchedPerson(1, 'd1', null, 0, {+ grade: 'update',+ generation: (store as any).generationOf(1),+ })const again = await bound.fetchForUpdate(1, 'd1')expect(again?.id).toBe('7')})@@ -226,7 +386,288 @@ describe('PersonhogPersonsStore', () => {expect(fetched?.id).toBe('7')})- it('creation resolves through identity and memoizes every distinct id it mapped', async () => {+ describe('mergePersons runs the saga and folds it into the batch view', () => {+ const survivor = () => ({ ...person, id: '7', properties: { plan: 'merged' }, version: 5 })++ beforeEach(() => {+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: survivor(),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ // Serves the fetch paths; in this world the leader holds the+ // folded document.+ repository.fetchPersonById.mockImplementation(((_teamId: number, personId: string) =>+ Promise.resolve(personId === '7' ? survivor() : { ...person, id: personId })) as never)+ })++ const mergeRequest = () => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({ $set: { plan: 'pro' } }, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('an op-id-reused refusal settles raw and purges the merge ids', async () => {+ // The replay guard's refusal is deterministic, so wrapping it+ // would redeliver one duplicated event uuid into the same+ // refusal until the recorded op ages out — a wedged partition.+ // The purge still runs: Postgres purges both ids on any merge+ // throw, and a stale entry costs one re-read either way.+ repository.mergePersons = jest+ .fn()+ .mockRejectedValue(+ new ConnectError(+ 'op_id was already used for a different request',+ Code.FailedPrecondition,+ new Headers({ 'x-semantic-refusal': 'op_id_reused' })+ )+ )+ const bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'd1')+ const error = await bound.mergePersons(mergeRequest()).catch((e) => e)+ expect(error).toBeInstanceOf(ConnectError)+ expect(error).not.toBeInstanceOf(PersonMergeCallFailedError)+ expect(edgeOf('1:d1')).toBeUndefined()+ })++ it('any other failed call fails the batch and purges the merge ids', async () => {+ // A semantic refusal from a later saga step (a parked op) and a+ // transport failure both redeliver rather than settle. The saga+ // may have run without answering, so its persons purge and the+ // next touch re-resolves.+ const refuse = (code: Code, metadata?: Headers) => {+ repository.mergePersons = jest+ .fn()+ .mockRejectedValue(new ConnectError('refused after the flip', code, metadata))+ }++ refuse(Code.FailedPrecondition, new Headers({ 'x-semantic-refusal': 'release-unverified' }))+ let bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'd1')+ await expect(bound.mergePersons(mergeRequest())).rejects.toBeInstanceOf(PersonMergeCallFailedError)+ expect(edgeOf('1:d1')).toBeUndefined()++ refuse(Code.Unavailable)+ bound = store.forBatch(1)+ await expect(bound.mergePersons(mergeRequest())).rejects.toBeInstanceOf(PersonMergeCallFailedError)+ expect(edgeOf('1:d1')).toBeUndefined()+ })++ it('derives one op id per delivery regardless of how the event payload drifts', async () => {+ // Two deliveries of one event disagree on properties later stages+ // refresh, but must present the same op id so the second attaches+ // to what the first recorded.+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: survivor(),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ const bound = store.forBatch(0)++ await bound.mergePersons(mergeRequest())+ await bound.mergePersons({+ ...mergeRequest(),+ eventOps: ops({ $set: { $geoip_city_name: 'Berlin' } }, '$identify'),+ createdAtMs: 9_999_999,+ })++ const opIds = (repository.mergePersons as jest.Mock).mock.calls.map(([call]) => call.opId)+ expect(opIds).toHaveLength(2)+ expect(opIds[1]).toBe(opIds[0])+ })++ it('floors a pre-epoch created_at, which the saga refuses', async () => {+ // The Postgres backend stores the raw value, so the floor lives+ // here rather than in the shared request both backends read.+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ const bound = store.forBatch(0)++ await bound.mergePersons({ ...mergeRequest(), createdAtMs: -86_400_000 })++ expect((repository.mergePersons as jest.Mock).mock.calls[0][0].createdAtMs).toBe(0)+ })++ it('a conflict verdict passes through in one call, unsalted', async () => {+ // The saga no longer records claim conflicts, so a plain retry+ // under the same op id re-runs fresh; the store neither salts+ // nor retries, and the caller's settled gate redelivers.+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: null,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict', settled: false }],+ })+ const bound = store.forBatch(0)++ const result = await bound.mergePersons(mergeRequest())++ expect(result.results[0]?.outcome).toBe('skipped_conflict')+ expect(result.results[0]?.settled).toBe(false)+ expect(repository.mergePersons).toHaveBeenCalledTimes(1)+ })++ it('later fetches of the merged ids re-resolve and read the leader', async () => {+ const bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'd1')+ const result = await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({ $set: { plan: 'pro' } }, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ expect(result.survivor?.properties).toEqual({ plan: 'merged' })+ // The store owns the saga's move-limit policy: SYNC mode sends+ // its configured guard, and the event ops carry the property sets.+ // The op id is team-scoped, never the raw client-supplied event+ // uuid, so one team's uuid cannot collide with another team's op.+ expect(repository.mergePersons).toHaveBeenCalledWith(+ expect.objectContaining({+ moveLimit: 10_000,+ eventSet: { plan: 'pro' },+ eventSetOnce: {},+ opId: mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000),+ }),+ expect.any(String)+ )++ // The merge purged everything it touched; the next fetch pays+ // one identity resolve and one leader read, and heals fresh.+ repository.resolvePersonsByDistinctIds.mockClear()+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: survivor() },+ ] as never)+ const viaTarget = await bound.fetchForUpdate(1, 'd1')+ expect(viaTarget?.version).toBe(5)+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })++ it.each([+ [{ type: 'LIMIT' as const, limit: 123 }, 123],+ [{ type: 'ASYNC' as const, limit: 456 }, 456],+ ])('mode %o carries its own limit as the saga move limit', async (mergeMode, expectedMoveLimit) => {+ const bound = store.forBatch(0)+ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode,+ createdAtMs: 3_600_000,+ })+ expect(repository.mergePersons).toHaveBeenCalledWith(+ expect.objectContaining({ moveLimit: expectedMoveLimit }),+ expect.any(String)+ )+ })++ it('purges every resolution of a merged-away person, not just the named source', async () => {+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ const bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'anon-1')+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'anon-1-alias', person: { ...person, id: '9' } },+ ] as never)+ await bound.fetchForUpdate(1, 'anon-1-alias')++ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ repository.resolvePersonsByDistinctIds.mockClear()+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1-alias', person: survivor() },+ ] as never)++ // The alias resolved to the merged-away person. Its edge purged+ // with that person, so the read re-resolves through identity,+ // which already names the survivor.+ const seen = await bound.fetchForUpdate(1, 'anon-1-alias')+ expect(seen?.id).toBe('7')+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })++ it("a skipped source's id re-resolves and still reads its own person", async () => {+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ])+ repository.fetchPersonById.mockResolvedValue({ ...person, id: '9' })+ const bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'anon-1')+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: survivor(),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_already_identified' }],+ })++ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ repository.resolvePersonsByDistinctIds.mockClear()++ // Every named id purges whatever the verdict: a skip destroyed+ // nothing, so identity still names the source's own person and+ // the re-read answers it unchanged.+ const viaSource = await bound.fetchForUpdate(1, 'anon-1')+ expect(viaSource?.id).toBe('9')+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })++ it('purges a resolution under an id the request never named, via the reported person', async () => {+ // Only the person id reaches this: the batch resolved the person+ // under anon-2, and the merge names anon-1, so the sibling scan+ // is what discovers the dead edge.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-2', person: { ...person, id: '9' } },+ ] as never)+ const bound = store.forBatch(0)+ await bound.fetchForUpdate(1, 'anon-2')++ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ repository.resolvePersonsByDistinctIds.mockClear()+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-2', person: survivor() },+ ] as never)++ const seen = await bound.fetchForUpdate(1, 'anon-2')+ expect(seen?.id).toBe('7')+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })+ })++ it('creation memoizes the primary id and leaves the extras to resolve', async () => {const bound = store.forBatch(0)const result = await bound.createPerson(DateTime.fromMillis(3_600_000, { zone: 'utc' }),@@ -253,124 +694,2046 @@ describe('PersonhogPersonsStore', () => {expect.any(String))await bound.fetchForUpdate(1, 'd1')+ expect(repository.resolvePersonsByDistinctIds).not.toHaveBeenCalled()++ // The created flag speaks only for the primary: the service leaves+ // a live conflicting extra mapped to its existing person, so an+ // edge memoized here could name a person the service never mapped+ // d2 to. The extra pays one resolve on first touch instead.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd2', person }] as never)await bound.fetchForUpdate(1, 'd2')+ expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(1)+ })++ it('a create that finds an existing person leaves its id readable for updates', async () => {+ // The found branch pays a leader read to get current state. That+ // state satisfies the update read class, so the id it resolves must+ // be recorded as such — otherwise the next update fetch re-resolves+ // and re-reads the leader for state this call already holds.+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({ person, created: false } as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, properties: { plan: 'fresh' } } as never)+ const bound = store.forBatch(0)++ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd1' },+ undefined+ )+ repository.resolvePersonsByDistinctIds.mockClear()+ repository.fetchPersonById.mockClear()++ const fetched = await bound.fetchForUpdate(1, 'd1')++ expect(fetched?.properties).toEqual({ plan: 'fresh' })expect(repository.resolvePersonsByDistinctIds).not.toHaveBeenCalled()+ expect(repository.fetchPersonById).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)+ it('drops a size-rejected segment from the lane rather than retrying it forever', async () => {+ repository.updatePersonProperties.mockRejectedValue(new PersonhogPropertiesSizeError('too big', 1, '7'))const bound = store.forBatch(0)await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')- const results = await bound.flush()- expect(results).toEqual([])+ await bound.flush()++ // The leader can never accept this payload, so leaving it in the+ // lane would re-send it on every pass for the rest of the batch.+ repository.updatePersonProperties.mockClear()+ await bound.flush()+ expect(repository.updatePersonProperties).not.toHaveBeenCalled()})- it('fails the flush on unexpected errors so the batch retries whole', async () => {- repository.updatePersonProperties.mockRejectedValue(new Error('leader unreachable'))+ it('redirects a merged-away lane to the survivor at flush', async () => {const bound = store.forBatch(0)await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')- await expect(bound.flush()).rejects.toThrow('leader unreachable')+ repository.updatePersonProperties+ .mockRejectedValueOnce(new NoRowsUpdatedError('merged away'))+ .mockResolvedValue({ person: { ...person, id: '9', version: 3 }, updated: true } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },+ ] as never)++ await bound.flush()++ expect(repository.updatePersonProperties).toHaveBeenLastCalledWith(+ expect.objectContaining({ personId: '9', setProperties: { a: '1' } }),+ expect.any(String)+ )})- describe('concurrent batches share one flush', () => {- const personB: () => InternalPerson = () => ({ ...person, id: '8', uuid: 'person-uuid-8' })+ it('a failed redirect write still purges the survivor projection', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ // A stale survivor projection; the redirect's ops may have partly+ // landed even when the write throws, so it must go either way.+ ;(store as any).projections.set('1:9', { ...person, id: '9', properties: { stale: 'yes' } })+ repository.updatePersonProperties.mockImplementation(((request: { personId: string }) =>+ request.personId === '7'+ ? Promise.reject(new NoRowsUpdatedError('merged away'))+ : Promise.reject(new Error('survivor write failed'))) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },+ ] as never)- it("a sibling entry's failure leaves it in its lane for the next pass", async () => {- const bound0 = store.forBatch(0)- const bound1 = store.forBatch(1)- await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')- await bound1.applyEventOps(personB(), ops({ $set: { b: '2' } }), 'd2')+ await expect(bound.flush()).rejects.toThrow()- repository.updatePersonProperties.mockImplementation((request) =>- request.personId === '8'- ? Promise.reject(new Error('leader unreachable'))- : Promise.resolve({ person: { ...person, version: 2 }, updated: true })- )- await expect(store.flush()).rejects.toThrow('leader unreachable')+ expect((store as any).projections.get('1:9')).toBeUndefined()+ })- repository.updatePersonProperties.mockClear()- repository.updatePersonProperties.mockResolvedValue({ person: { ...person, version: 2 }, updated: true })- await store.flush()- // Only the failed entry survives to re-ship; the succeeded- // one was consumed by the first pass.- expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)- expect(repository.updatePersonProperties.mock.calls[0][0].personId).toBe('8')+ describe('round-6 closures', () => {+ const mergeReq = (sources = ['anon-1', 'anon-2']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,})- it('flush passes serialize, so ops folded mid-pass ship strictly after it', async () => {- let releaseFirst!: () => void- const firstGate = new Promise<void>((resolve) => {- releaseFirst = resolve- })- const callOrder: string[] = []- repository.updatePersonProperties- .mockImplementationOnce(async () => {- callOrder.push('first:start')- await firstGate- callOrder.push('first:end')- return { person: { ...person, version: 2 }, updated: true }- })- .mockImplementation(() => {- callOrder.push('second')- return Promise.resolve({ person: { ...person, version: 3 }, updated: true })- })+ it('a single-pair fold request still aborts on a refused verdict', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_refused' }],+ } as never)++ const result = await bound.mergePersons({ ...mergeReq(['anon-1']), triggerSourceDistinctId: 'anon-1' })++ expect(result.foldAborted).toBe('refused')+ })+ it('a fold racing a purge declines its cache install and keeps the ops', async () => {const bound = store.forBatch(0)- await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')- const firstFlush = store.flush()- // Spin microtasks until the first pass is mid-ship, blocked- // on the gate, so the next fold genuinely lands mid-pass.- for (let i = 0; i < 100 && !callOrder.includes('first:start'); i++) {- await Promise.resolve()- }- await bound.applyEventOps(person, ops({ $set: { a: '2' } }), 'd1')- const secondFlush = store.flush()- releaseFirst()- await Promise.all([firstFlush, secondFlush])+ ;(store as any).setDistinctIdToPersonId('1:d1', '1:9')+ // The standing edge sends the update fetch to the leader read;+ // holding it open is the window the purge lands in.+ let release!: (value: unknown) => void+ repository.fetchPersonById.mockReturnValueOnce(+ new Promise((resolve) => {+ release = resolve+ }) as never+ )- expect(callOrder).toEqual(['first:start', 'first:end', 'second'])+ const applying = bound.applyEventOps(person, ops({ $set: { folded: 'yes' } }), 'd1')+ ;(store as any).bumpGeneration(1)+ release({ ...person, id: '9' })+ await applying++ expect((store as any).projections.get('1:7')?.properties?.folded).toBeUndefined()+ expect((store as any).projections.get('1:9')?.properties?.folded).toBeUndefined()+ expect((store as any).entries.get('1:7')?.segments).toHaveLength(1)})- it('a no-change lane ships anyway when a sibling batch holds ops for the person', async () => {- person.properties = { $browser: 'Firefox' }- const bound0 = store.forBatch(0)- const bound1 = store.forBatch(1)- // Batch 0 folds a filtered-only no-change; batch 1 holds real- // ops for the same person, so batch 0's verdict may be stale- // and the leader judges it instead.- await bound0.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, 'pageview'), 'd1')- await bound1.applyEventOps(person, ops({ $set: { plan: 'pro' } }, 'pageview'), 'd1')- await store.flush()- expect(repository.updatePersonProperties).toHaveBeenCalledTimes(2)+ it('releasing one batch keeps a dirty person document for the others', async () => {+ const a = store.forBatch(1)+ const b = store.forBatch(2)+ // Both ids resolve to person 7, so releasing A's edge would+ // evict the person B still holds dirty.+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)+ await a.fetchForChecking(1, 'd1')+ await b.applyEventOps(person, ops({ $set: { pending: 'yes' } }), 'd2')+ expect((store as any).resolutions.get('1:d1')).toBe('1:7')++ store.releaseBatch(1)++ expect((store as any).projections.get('1:7')).toBeDefined()})- })- 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('retiring a written lane drops the documents its dirtiness kept alive', async () => {+ const a = store.forBatch(1)+ const b = store.forBatch(2)+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd1', person: { ...person } },+ ] as never)+ await a.fetchForChecking(1, 'd1')+ await b.applyEventOps(person, ops({ $set: { pending: 'yes' } }), 'd2')+ store.releaseBatch(1)+ store.releaseBatch(2)+ // Both holders left, but the dirty lane deferred the eviction.+ expect((store as any).projections.get('1:7')).toBeDefined()- 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')+ await b.flush()+ expect((store as any).entries.get('1:7')).toBeUndefined()+ expect((store as any).projections.get('1:7')).toBeUndefined()+ expect((store as any).personCheckCache.get('1:7')).toBeUndefined()+ })++ it('a flush over a redirect-owned lane waits its rounds instead of failing instantly', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { late: 'yes' } }), 'd1')+ const entry = (store as any).entries.get('1:7')+ entry.inFlight = true+ setTimeout(() => {+ entry.inFlight = false+ }, 100)++ await expect(bound.flush()).resolves.toBeDefined()+ })++ it('an aborted row recorded in the error vocabulary still aborts the fold', async () => {+ // Completion implies at least one merged source, so an+ // error-without-merged row can only be an abort; executing it+ // would misattribute the run.+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'error' },+ { sourceDistinctId: 'anon-2', outcome: 'error' },+ ],+ })++ const result = await bound.mergePersons(mergeReq())++ expect(result.foldAborted).toBe('error')+ expect(result.survivor).toBeNull()+ })++ it('an aborted fold purges the survivor projection it may have moved past', async () => {+ const bound = store.forBatch(0)+ ;(store as any).setCachedPersonForUpdate('1:7', { ...person, version: 3 })+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, version: 9 },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' },+ { sourceDistinctId: 'anon-2', outcome: 'skipped_conflict' },+ ],+ })++ await bound.mergePersons(mergeReq())++ // The saga's partial folds moved the leader past the standing+ // projection despite the abort, so the next reader re-reads.+ expect(hasProjection('1:7')).toBe(false)+ })++ it("the merge answers the saga's survivor without a refresh read", async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, version: 5, properties: { plan: 'folded' } },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ // A deposed leader inside its detection window can answer below+ // the merge's own commit; a refresh read here would serve that+ // older document as the fold plan's survivor.+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 4,+ properties: { plan: 'old' },+ } as never)++ const result = await bound.mergePersons(mergeReq(['anon-1']))++ expect(result.survivor).toMatchObject({ version: 5, properties: { plan: 'folded' } })+ })++ it('a direct diff answered with no document but an applied write drops the projection', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ repository.updatePersonProperties.mockResolvedValueOnce({ person: null, updated: true } as never)++ await bound.updatePersonWithPropertiesDiffForUpdate(person, { plan: 'pro' }, [], {}, 'd1')++ // The write applied, so the pre-write projection must not go on+ // serving; the next reader re-reads.+ expect(hasProjection('1:7')).toBe(false)+ })+ })++ describe('round-5 closures', () => {+ it('a leading size rejection does not strand the snapshot tail past the ack', async () => {+ const bound = store.forBatch(0)+ // A pair-then-set_once composition forces two segments; the+ // leader rejects the first on size. The tail is a real write+ // from THIS batch: leaving it for "the next pass" leaves it for+ // a later batch, past this batch's ack — a crash then loses it.+ await bound.applyEventOps(person, ops({ $set: { big: 'x', k: 'a' }, $unset: ['k'] }), 'd1')+ await bound.applyEventOps(person, ops({ $set: { tail: 'kept' }, $set_once: { k: 'b' } }), 'd1')+ expect((store as any).entries.get('1:7').segments).toHaveLength(2)+ repository.updatePersonProperties+ .mockRejectedValueOnce(new PersonhogPropertiesSizeError('too big', 1, '7') as never)+ .mockResolvedValue({ person, updated: true } as never)++ await bound.flush()++ // The tail was written within the same flush, before the batch acks.+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(2)+ expect(repository.updatePersonProperties.mock.calls[1][0].setProperties).toEqual({ tail: 'kept' })+ expect((store as any).entries.get('1:7').segments).toHaveLength(0)+ })++ it('a size rejection mid-redirect still delivers the remainder to the survivor', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { big: 'x', k: 'a' }, $unset: ['k'] }), 'd1')+ await bound.applyEventOps(person, ops({ $set: { tail: 'kept' }, $set_once: { k: 'b' } }), 'd1')+ // The person is merged away; the redirect's first unit bounces on+ // size; the remainder must re-enter the redirect, not wait for a+ // later batch's flush.+ repository.updatePersonProperties.mockImplementation(((request: {+ personId: string+ setProperties?: Record<string, unknown>+ setOnceProperties?: Record<string, unknown>+ }) => {+ if (request.personId === '7') {+ return Promise.reject(new NoRowsUpdatedError('merged away'))+ }+ if (request.setProperties?.big !== undefined || request.setOnceProperties?.big !== undefined) {+ return Promise.reject(new PersonhogPropertiesSizeError('too big', 1, '9'))+ }+ return Promise.resolve({ person, updated: true })+ }) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },+ ] as never)++ await bound.flush()++ const landed = repository.updatePersonProperties.mock.calls+ .map(([request]) => request)+ .filter((request) => request.personId === '9' && request.setProperties?.tail !== undefined)+ expect(landed).toHaveLength(1)+ expect((store as any).entries.get('1:7').segments).toHaveLength(0)+ })+ })++ describe('round-4 closures', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it("a create that finds an existing person serves the leader's document, not identity's", async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { fromBatch: 'yes' } }), 'd1')+ await bound.flush()+ // The lane drained but the entry survives while the batch holds+ // it, so nothing unwritten is left to protect.+ expect((store as any).entries.get('1:7').segments).toHaveLength(0)++ // A second id lands on the same person. Identity answers a+ // document that predates this batch's flushed write; the+ // branch's leader read answers the truth, which contains it.+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({+ person: { ...person, properties: { plan: 'free' } },+ created: false,+ } as never)+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 2,+ properties: { plan: 'free', fromBatch: 'yes' },+ } as never)++ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd2' }+ )++ // Installing identity's lagging document instead would roll the+ // batch's own flushed write out of its view.+ expect((store as any).getCachedPerson(1, 'd1', 'check')).toMatchObject({+ properties: { plan: 'free', fromBatch: 'yes' },+ })+ })++ it('a read straddling a purge declines to record', async () => {+ const bound = store.forBatch(0)+ // A merge purges the team while this read's resolve is on the+ // wire; the answer predates the purge, so serving it is fine but+ // recording it would refill exactly what the purge dropped.+ repository.resolvePersonsByDistinctIds.mockImplementation((() => {+ ;(store as any).purgeAfterMerge(1, ['d1'], new Set<string>(), 'merge_verdict')+ return Promise.resolve([{ teamId: 1, distinctId: 'd1', person }])+ }) as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)++ const fetched = await bound.fetchForUpdate(1, 'd1')++ expect(fetched?.id).toBe('7')+ expect(edgeOf('1:d1')).toBeUndefined()+ expect(hasProjection('1:7')).toBe(false)+ })++ it('the staler of two leader reads does not replace the newer', async () => {+ const bound = store.forBatch(0)+ // A read lands and installs the person at version 5.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, version: 5, properties: { plan: 'pro' } } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 5,+ properties: { plan: 'pro' },+ } as never)+ await bound.fetchForUpdate(1, 'd1')++ // A second read of the same person, issued earlier and delivered+ // now, answers the document as it stood before. Both came from+ // the leader, so only the version tells them apart.+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({+ person: { ...person, version: 3, properties: { plan: 'free' } },+ created: false,+ } as never)+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 3,+ properties: { plan: 'free' },+ } as never)++ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd2' }+ )++ expect((store as any).getCachedPerson(1, 'd1', 'check')).toMatchObject({+ version: 5,+ properties: { plan: 'pro' },+ })+ })++ it('a direct diff update leaves the projection naming the leader', async () => {+ const bound = store.forBatch(0)+ await bound.updatePersonWithPropertiesDiffForUpdate(person, { plan: 'pro' }, [], {}, 'd1')++ // Installing the person it was handed instead of the one the+ // leader answered is the failure this names, and asserting only+ // that some projection exists would not see it.+ expect(projectionOf('1:7')).toMatchObject({+ version: 2,+ properties: { plan: 'pro' },+ })+ })++ it('a write whose response carries no document drops the projection it outran', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ expect(hasProjection('1:7')).toBe(true)+ repository.updatePersonProperties.mockResolvedValueOnce({ person: null, updated: true } as never)++ await bound.flush()++ // The write landed, so the leader moved past the version the+ // projection holds; the next reader re-reads.+ expect(hasProjection('1:7')).toBe(false)+ })++ it('a person gone from identity fails the flush to redeliver, releasing the id', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ expect(edgeOf('1:d1')).toBe('1:7')+ // The person is deleted rather than merged, so the redirect's+ // resolve answers nobody. Redelivery recreates through the+ // normal pipeline, as Postgres does; dropping here would lose+ // the ops.+ repository.updatePersonProperties.mockRejectedValue(new NoRowsUpdatedError('deleted') as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([] as never)++ await expect(bound.flush()).rejects.toThrow(/resolves to nobody/)++ expect((store as any).entries.get('1:7').segments).toHaveLength(1)+ // Released, so the redelivered events re-resolve rather than+ // folding onto the deleted person again.+ expect(edgeOf('1:d1')).toBeUndefined()+ expect(hasProjection('1:7')).toBe(false)+ })++ it.each([+ ['its resolve', 'resolve' as const],+ ['its person read', 'fetch' as const],+ ])('a prefetch released during %s records nothing', async (_case, window) => {+ store.forBatch(0)+ let release: () => void = () => {}+ const deferred = <T>(value: T): Promise<T> =>+ new Promise((resolve) => {+ release = () => resolve(value)+ })+ if (window === 'resolve') {+ repository.resolvePersonsByDistinctIds.mockImplementation((() =>+ deferred([{ teamId: 1, distinctId: 'd9', person }])) as never)+ repository.fetchPersonById.mockResolvedValue(person as never)+ } else {+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd9', person },+ ] as never)+ repository.fetchPersonById.mockImplementation((() => deferred(person)) as never)+ }++ const prefetching = store.prefetchPersons([{ teamId: 1, distinctId: 'd9', batchId: 0 }])+ await new Promise((resolve) => setImmediate(resolve))+ // Released while that call is still out. Both windows need their+ // own check: a guard before the first await does not cover a+ // release that happens during the second.+ store.releaseBatch(0)+ release()+ await prefetching++ // Recording for a batch that has gone recreates its key set, and+ // every later release then reads the key as held elsewhere, so+ // nothing frees it again.+ expect(edgeOf('1:d9')).toBeUndefined()+ expect(projectionCount()).toBe(0)+ })++ it('a create that finds a person the leader has lost memoizes nothing', async () => {+ // The leader answers null only for a destroyed person; the+ // caller keeps identity's answer, and memoizing it would serve+ // the dead person for the rest of the batch.+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({ person, created: false } as never)+ repository.fetchPersonById.mockResolvedValue(null as never)+ const bound = store.forBatch(0)++ const result = await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd1' },+ undefined+ )++ expect(result.success && result.person?.id).toBe('7')+ expect(edgeOf('1:d1')).toBeUndefined()+ expect(hasProjection('1:7')).toBe(false)+ })++ it('a direct diff update releases its projection with the batch', async () => {+ // The diff path installs outside the lane protocol; without a+ // recorded edge the projection would have no reference and no+ // lane, and nothing would ever evict it.+ const bound = store.forBatch(0)+ await bound.updatePersonWithPropertiesDiffForUpdate(person, { plan: 'pro' }, [], {}, 'd1')+ expect(projectionCount()).toBe(1)++ store.releaseBatch(0)++ expect(projectionCount()).toBe(0)+ })++ it("a merge on another team's persons does not discard this read", async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockImplementation((() => {+ // A merge for a different person, in a different team,+ // settles while this read is in flight. The generation guard+ // is per team, so this read still records.+ ;(store as any).purgeAfterMerge(2, ['elsewhere'], new Set(['2:99', '2:98']), 'merge_verdict')+ return Promise.resolve([{ teamId: 1, distinctId: 'd1', person }]) as never+ }) as never)+ repository.fetchPersonById.mockResolvedValue(person as never)++ await bound.fetchForUpdate(1, 'd1')++ // Discarding it would make the cache useless under merge load+ // and leave any loop that re-reads unable to make progress,+ // which is what a process-wide counter did.+ expect(edgeOf('1:d1')).toBe('1:7')+ })++ it('folds onto the person the cache names, not the caller’s stale copy', async () => {+ const bound = store.forBatch(0)+ const other = { ...person, id: '9' }+ // d1 belongs to 9 and its document was dropped, so the fold has+ // to read rather than trust the caller's copy of person 7.+ ;(store as any).setDistinctIdToPersonId('1:d1', '1:9')+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: other },+ ] as never)+ repository.fetchPersonById.mockResolvedValue(other as never)++ const [projected] = await bound.applyEventOps(person, ops({ $set: { late: 'op' } }), 'd1')++ // Folding onto person 7 would repoint d1 off 9 and onto a person+ // a merge left behind, and later events would compose on top.+ expect(projected.id).toBe('9')+ expect(edgeOf('1:d1')).toBe('1:9')+ })++ it('a write in flight stays visible in the view until its answer lands', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ let releaseWrite: () => void = () => {}+ repository.updatePersonProperties.mockImplementation((() => {+ return new Promise((resolve) => {+ releaseWrite = () =>+ resolve({ person: { ...person, version: 3, properties: { k: 'A' } }, updated: true })+ })+ }) as never)+ const flushing = bound.flush()+ await new Promise((resolve) => setImmediate(resolve))++ // The op is on the wire and not yet in any document a service+ // would answer. Dropping it from the view here would show a+ // later event in this batch a person without its own write.+ expect(projectionOf('1:7')?.properties).toMatchObject({ k: 'A' })++ releaseWrite()+ await flushing+ expect(projectionOf('1:7')?.properties).toMatchObject({ k: 'A' })+ })++ it("a fold after a dropped projection rebuilds the view from the caller's composed person", async () => {+ const bound = store.forBatch(0)+ const held = { ...person, properties: { k: 'x' } }+ // One event both writing and unsetting k resolves to gone,+ // because k was there before the op.+ const [afterOne] = await bound.applyEventOps(held, ops({ $set: { k: 'v' }, $unset: ['k'] }), 'd1')+ expect(afterOne.properties).toEqual({})+ // A redirect on another lane drops this person's document while+ // that op is still unsent.+ ;(store as any).clearPersonCacheForPersonId('1:7', 'redirect_survivor')++ // The caller folds again holding the view it was just given: the+ // composed view already resolved the k pair, so folding over it+ // adds only the new op and cannot double-count.+ await bound.applyEventOps(afterOne, ops({ $set: { j: 'B' } }), 'd1')++ expect(projectionOf('1:7')?.properties).toEqual({ j: 'B' })+ // The rebuilt projection serves the batch's later reads without+ // going back to the leader.+ const seen = await bound.fetchForUpdate(1, 'd1')+ expect(seen?.properties).toEqual({ j: 'B' })+ expect(repository.fetchPersonById).not.toHaveBeenCalled()+ })++ it('a refused write leaves nothing asserted that the leader never took', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ repository.updatePersonProperties.mockRejectedValueOnce(+ new PersonhogPropertiesSizeError('too big', 1, '7') as never+ )+ await bound.flush()+ repository.updatePersonProperties.mockClear()++ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ await bound.flush()++ // A view still counting the refused ops would make this diff+ // clean against a value the leader never took, and the write+ // would be filtered away rather than retried on its own.+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(+ expect.objectContaining({ personId: '7', setProperties: { k: 'A' } }),+ expect.anything()+ )+ })++ it('an id repointed by a redirect still folds onto the survivor', async () => {+ const bound = store.forBatch(0)+ // Version above the redirect's own write answers: leader versions+ // are monotonic, so a post-redirect read can never come back+ // below what the redirect's writes reached.+ const survivor = { ...person, id: '9', version: 3 }+ // The batch knows the survivor, then a lane whose person was+ // merged away redirects its ops onto it.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd2', person: survivor },+ ] as never)+ repository.fetchPersonById.mockResolvedValue(survivor as never)+ await bound.fetchForUpdate(1, 'd2')++ await bound.applyEventOps(person, ops({ $set: { early: 'op' } }), 'd1')+ repository.updatePersonProperties.mockImplementationOnce((() =>+ Promise.reject(new NoRowsUpdatedError('merged away'))) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: survivor },+ ] as never)+ await bound.flush()++ // d1 belongs to the survivor now. A caller still holding the+ // person it read before the merge must not get it back.+ const [landed] = await bound.applyEventOps(person, ops({ $set: { late: 'op' } }), 'd1')+ expect(landed.id).toBe('9')+ })++ it('a redirect drops the survivor projection it just made stale', async () => {+ const bound = store.forBatch(0)+ // The survivor is known to the batch, then a lane whose person+ // was merged away writes its ops onto it.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd2', person: { ...person, id: '9' } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, id: '9' } as never)+ await bound.fetchForUpdate(1, 'd2')+ expect(hasProjection('1:9')).toBe(true)++ await bound.applyEventOps(person, ops({ $set: { late: 'op' } }), 'd1')+ repository.updatePersonProperties.mockImplementationOnce((() =>+ Promise.reject(new NoRowsUpdatedError('merged away'))) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },+ ] as never)++ await bound.flush()++ // Its own lane cannot know about those ops and this batch cannot+ // order the two together, so the leader answers the next read.+ expect(hasProjection('1:9')).toBe(false)+ })++ it('a discarded projection re-reads the leader while the lane still lands its ops', async () => {+ const bound = store.forBatch(0)+ // The lane holds k='A' unsent while the leader still answers the+ // value it replaces.+ await bound.applyEventOps(person, ops({ $set: { k: 'A' } }), 'd1')+ ;(store as any).clearPersonCacheForPersonId('1:7', 'redirect_survivor')+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 9,+ properties: { k: 'old' },+ } as never)++ const seen = await bound.fetchForUpdate(1, 'd1')++ // The hole fills with leader state, which cannot know the unsent+ // op: a brief stale view at the Postgres cache's own grade. The+ // lane still writes as stated, so no data is lost, and the store+ // never filters a write against this view.+ expect(seen).toMatchObject({ version: 9, properties: { k: 'old' } })+ await bound.flush()+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(+ expect.objectContaining({ setProperties: { k: 'A' } }),+ expect.any(String)+ )+ })++ it('a size rejection mid-redirect still heals the id it resolved', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ // The person is merged away and the survivor rejects the only+ // unit on size. The resolve still proved where the id belongs.+ repository.updatePersonProperties.mockImplementation(((request: { personId: string }) =>+ request.personId === '7'+ ? Promise.reject(new NoRowsUpdatedError('merged away'))+ : Promise.reject(new PersonhogPropertiesSizeError('too big', 1, '9'))) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } },+ ] as never)++ await bound.flush()++ // Left pointing at the dead person, every later event in the+ // batch would fold onto it and pay the redirect again.+ expect(edgeOf('1:d1')).toBe('1:9')+ })++ it('an id whose person was merged twice folds onto the last survivor', async () => {+ const bound = store.forBatch(0)+ const first = { ...person, id: '9', uuid: 'first-uuid', properties: { plan: 'first' } }+ const second = { ...person, id: '7', uuid: 'second-uuid', properties: { plan: 'second' } }+ const third = { ...person, id: '11', uuid: 'third-uuid', properties: { plan: 'third' } }+ // A real identity graph, repointed by each merge. A fixed mock row+ // answers every resolve with the same person, and the merge's own+ // fence resolve then writes that answer into the memo.+ const persons = new Map([+ ['9', first],+ ['7', second],+ ['11', third],+ ])+ const graph = new Map([['anon-1', '9']])+ repository.resolvePersonsByDistinctIds.mockImplementation(+ (keys: { distinctId: string }[]) =>+ Promise.resolve(+ keys.map(({ distinctId }) => {+ const personId = graph.get(distinctId)+ return { teamId: 1, distinctId, person: personId ? persons.get(personId) : null }+ })+ ) as never+ )+ repository.fetchPersonById.mockImplementation(((_t: number, id: string) =>+ Promise.resolve(persons.get(id) ?? null)) as never)+ await bound.fetchForUpdate(1, 'anon-1')++ const merge = (targetDistinctId: string, sourceDistinctId: string, eventUuid: string) => ({+ teamId: 1,+ targetDistinctId,+ sources: [{ distinctId: sourceDistinctId, eventUuid }],+ eventOps: ops({}, '$identify'),+ eventUuid,+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ const settle = (survivor: InternalPerson, sourceDistinctId: string, sourcePersonId: string) => {+ for (const [distinctId, personId] of graph) {+ if (personId === sourcePersonId) {+ graph.set(distinctId, survivor.id)+ }+ }+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor,+ results: [{ sourceDistinctId, outcome: 'merged', sourcePersonId }],+ } as never)+ }++ graph.set('d1', '7')+ settle(second, 'anon-1', '9')+ await bound.mergePersons(merge('d1', 'anon-1', 'event-uuid'))+ graph.set('d2', '11')+ settle(third, 'd1', '7')+ await bound.mergePersons(merge('d2', 'd1', 'event-uuid-2'))++ // Both merges purged anon-1's edge, so a caller still holding+ // the head of the chain folds onto its stale copy; the write+ // meets the tombstone and the redirect carries it to the+ // chain's end rather than a person from the middle.+ const [folded] = await bound.applyEventOps(first, ops({ $set: { late: 'op' } }), 'anon-1')+ expect(folded.id).toBe('9')+ const written: string[] = []+ repository.updatePersonProperties.mockImplementation(((request: { personId: string }) => {+ written.push(request.personId)+ return request.personId === '11'+ ? Promise.resolve({ person: third, updated: true })+ : Promise.reject(new NoRowsUpdatedError('merged away'))+ }) as never)++ await bound.flush()++ expect(written[written.length - 1]).toBe('11')+ })++ it('a fence releasing mid-round cannot make the flush ack over a deferred lane', async () => {+ const narrowStore = new PersonhogPersonsStore(repository, { maxConcurrentUpdates: 1 })+ const bound = narrowStore.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ // Three lanes, one slot. 7 starts under the fence and defers; the+ // merge releases while 10's RPC holds the round open, so the+ // round's scan finds 7 neither fenced nor in flight.+ await bound.applyEventOps({ ...person, id: '8', uuid: 'u8' }, ops({ $set: { a: '1' } }), 'other-1')+ await bound.applyEventOps(person, ops({ $set: { plan: 'held' } }), 'd1')+ await bound.applyEventOps({ ...person, id: '10', uuid: 'u10' }, ops({ $set: { c: '3' } }), 'other-2')++ const releases = new Map<string, () => void>()+ const written: string[] = []+ repository.updatePersonProperties.mockImplementation(((request: { personId: string }) => {+ written.push(request.personId)+ if (request.personId === '8' || request.personId === '10') {+ return new Promise((resolve) => {+ releases.set(request.personId, () => resolve({ person, updated: true }))+ })+ }+ return Promise.resolve({ person, updated: true })+ }) as never)+ let releaseMerge: () => void = () => {}+ repository.mergePersons = jest.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseMerge = () => resolve({ survivor: person, results: [] })+ })+ )++ const flushing = bound.flush()+ await new Promise((resolve) => setTimeout(resolve, 0))+ // The merge fences person 7 while 8's write holds the slot, and+ // stays in flight.+ const merging = bound.mergePersons(mergeReq())+ await new Promise((resolve) => setTimeout(resolve, 0))+ // 8 lands; 7 starts under the live fence and defers; 10 takes+ // the slot.+ releases.get('8')?.()+ await new Promise((resolve) => setTimeout(resolve, 0))+ // 7 started under the live fence and deferred; the merge waited+ // that out and wrote the lane itself rather than leaving it for a+ // later round to find. 10 is still on the wire.+ expect(written).toContain('7')+ expect(written).toContain('8')+ // The merge resolves and releases its fence while 10 is still on+ // the wire — the exact window where 7 is invisible to a+ // parked-only scan.+ releaseMerge()+ await merging+ releases.get('10')?.()+ await flushing++ // Whatever the interleaving, nothing acks over unwritten ops.+ expect(written).toEqual(expect.arrayContaining(['8', '10', '7']))+ expect((narrowStore as any).entries.get('1:7')?.segments ?? []).toHaveLength(0)+ })+ })++ describe('parity with the Postgres backend', () => {+ const mergeReq = () => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it.each([+ ['the move limit', 'skipped_move_limit', 'limit'],+ ['a lifecycle conflict', 'skipped_conflict', 'conflict'],+ ])('a fold that skipped one source on %s aborts after keeping what merged', async (_case, skip, reason) => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, version: 7 },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' },+ { sourceDistinctId: 'anon-2', outcome: skip },+ ],+ })++ const result = await bound.mergePersons({+ ...mergeReq(),+ sources: [+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ { distinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ],+ })++ // Postgres's fold is all-or-nothing, so a skipped source there+ // falls back to its own sequential merge and its own durability+ // decision. Executing here instead would ack anon-2's event with+ // no merge behind it.+ expect(result.foldAborted).toBe(reason)+ expect(result.survivor).toBeNull()+ // The abort does not unwind what the saga durably did: anon-1's+ // person really merged, so its purged id re-resolves through+ // identity, which already names the survivor.+ expect(edgeOf('1:anon-1')).toBeUndefined()+ })++ it('a fold with an unsettled source aborts, whatever name carries it', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ // An unsettled verdict under a name outside the conflict+ // vocabulary: a retry may change it, so executing the fold would+ // ack anon-2's event on an answer that is not final.+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, version: 7 },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9', settled: true },+ { sourceDistinctId: 'anon-2', outcome: 'error', settled: false },+ ],+ })++ const result = await bound.mergePersons({+ ...mergeReq(),+ sources: [+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ { distinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ],+ })++ expect(result.foldAborted).toBe('conflict')+ expect(result.survivor).toBeNull()+ })++ it('reports a fold whose every source conflicted as an abort, not a success', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' },+ { sourceDistinctId: 'anon-2', outcome: 'skipped_conflict' },+ ],+ })++ const result = await bound.mergePersons({+ ...mergeReq(),+ sources: [+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ { distinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ],+ })++ // The saga still answers a survivor here, so without the abort+ // the caller reads a fold that merged nothing as executed and+ // acks every event in the run. Postgres falls back to per-event+ // merges for the same condition, and each of those retries.+ expect(result.foldAborted).toBe('conflict')+ expect(result.survivor).toBeNull()+ expect(repository.mergePersons).toHaveBeenCalledTimes(1)+ })++ it('reports a fold the leader definitively refused as an abort, not a success', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'skipped_refused' },+ { sourceDistinctId: 'anon-2', outcome: 'skipped_refused' },+ ],+ })++ const result = await bound.mergePersons({+ ...mergeReq(),+ sources: [+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ { distinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ],+ })++ // An aborted response still carries a survivor, so without the+ // abort flag the caller would read a fold that merged nothing+ // as executed and misattribute every event in the run.+ expect(result.foldAborted).toBe('refused')+ expect(result.survivor).toBeNull()+ })++ it('carries ops its own merge missed to the survivor rather than dropping them', async () => {+ // The reference backend folds a source's pending properties into+ // the survivor before deleting the row, so ops that missed the+ // fold are not lost there and must not be lost here. The redirect+ // is what carries them.+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, id: '9' } as never)+ await bound.fetchForUpdate(1, 'anon-1')+ await bound.applyEventOps({ ...person, id: '9' }, ops({ $set: { plan: 'stale' } }), 'anon-1')+ expect((store as any).entries.get('1:9')?.segments).toHaveLength(1)++ // The lane goes unwritten: the leader fence naming this merge's+ // own saga is the one refusal the pre-merge write proceeds past.+ repository.updatePersonProperties.mockRejectedValueOnce(+ new PersonhogFencedError('fenced', '9', mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000))+ )+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ await bound.mergePersons(mergeReq())++ // Still pending: the purge leaves lanes, and the flush redirects.+ expect((store as any).entries.get('1:9')?.segments).toHaveLength(1)+ repository.updatePersonProperties.mockReset()+ repository.updatePersonProperties.mockImplementation((({ personId }: { personId: string }) =>+ personId === '9'+ ? Promise.reject(new NoRowsUpdatedError('merged away'))+ : Promise.resolve({ person: { ...person, id: '7' }, updated: true })) as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '7' } },+ ] as never)++ await bound.flush()++ const landed = repository.updatePersonProperties.mock.calls+ .filter(([request]) => request.personId === '7')+ .map(([request]) => request.setProperties)+ expect(landed).toContainEqual({ plan: 'stale' })+ })++ it('keeps a lane the server never named, since the cache can be wrong about it', async () => {+ // No sourcePersonId, so the person is only inferred from this+ // pod's own cache. A replayed verdict or another pod's merge can+ // make that name a live person, and discarding is irreversible,+ // so the ops stay and the write redirects if the person did die.+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, id: '9' } as never)+ await bound.fetchForUpdate(1, 'anon-1')+ await bound.applyEventOps({ ...person, id: '9' }, ops({ $set: { plan: 'stale' } }), 'anon-1')++ repository.updatePersonProperties.mockRejectedValueOnce(+ new PersonhogFencedError('fenced', '9', mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000))+ )+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '7' },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ await bound.mergePersons(mergeReq())++ expect((store as any).entries.get('1:9')?.segments).toHaveLength(1)+ })++ it('keeps a lane buffered when the merge call returns no verdict', async () => {+ // Postgres keeps its pending updates across a rolled-back merge.+ // Nothing here knows whether the source died, so discarding would+ // lose writes for a merge that never happened.+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, id: '9' } as never)+ await bound.fetchForUpdate(1, 'anon-1')+ await bound.applyEventOps({ ...person, id: '9' }, ops({ $set: { plan: 'stale' } }), 'anon-1')+ // Same bounce as above, so the lane is still buffered when the+ // call goes out and its fate is what this pins.+ repository.updatePersonProperties.mockRejectedValueOnce(+ new PersonhogFencedError('fenced', '9', mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000))+ )+ repository.mergePersons = jest.fn().mockRejectedValue(new Error('no verdict'))++ await expect(bound.mergePersons(mergeReq())).rejects.toThrow(PersonMergeCallFailedError)+ expect((store as any).entries.get('1:9')?.segments).toHaveLength(1)+ })+ })++ describe('round-3 closures', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('a queued write that starts under a fence defers instead of racing the merge', async () => {+ // One concurrency slot forces the second lane's write to start in+ // a later macrotask — after the merge fenced its person. The+ // capture-time fence check cannot see that future; only a check+ // at execution start can.+ const narrowStore = new PersonhogPersonsStore(repository, { maxConcurrentUpdates: 1 })+ const bound = narrowStore.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ await bound.applyEventOps({ ...person, id: '8', uuid: 'other' }, ops({ $set: { a: '1' } }), 'other-1')+ await bound.applyEventOps(person, ops({ $set: { plan: 'older' } }), 'd1')++ let releaseFirstWrite: () => void = () => {}+ const written: string[] = []+ repository.updatePersonProperties.mockImplementation(((request: { personId: string }) => {+ written.push(request.personId)+ if (written.length === 1) {+ return new Promise((resolve) => {+ releaseFirstWrite = () => resolve({ person, updated: true })+ })+ }+ return Promise.resolve({ person, updated: true })+ }) as never)+ let releaseMerge: () => void = () => {}+ repository.mergePersons = jest.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseMerge = () => resolve({ survivor: person, results: [] })+ })+ )++ const flushing = bound.flush()+ await new Promise((resolve) => setTimeout(resolve, 0))+ // Lane 8's write holds the only slot; person 7's lane is captured+ // but unstarted. The merge fences 7 now.+ const merging = bound.mergePersons(mergeReq())+ await new Promise((resolve) => setTimeout(resolve, 0))++ // Free the slot: 7's queued write begins under the fence and must+ // defer rather than send its unscrubbed segment mid-merge.+ releaseFirstWrite()+ await new Promise((resolve) => setTimeout(resolve, 0))+ // 7's queued write began under the fence and deferred rather than+ // racing the saga. The merge waited that deferral out and wrote+ // the lane itself, so the ops are durable before its request goes+ // out — not left for a later drain to chase.+ expect(written).toEqual(['8', '7'])+ expect(repository.mergePersons).toHaveBeenCalledTimes(1)++ releaseMerge()+ await merging+ await flushing+ expect(written).toEqual(['8', '7'])+ })++ it('a stale finalizer cannot retire a recreated lane', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ const oldEntry = (store as any).entries.get('1:7')+ // The old entry drained and was replaced while an old write's+ // finalizer was still pending; retiring by key would take the+ // new lane's unwritten ops with it.+ ;(store as any).entries.delete('1:7')+ await bound.applyEventOps(person, ops({ $set: { b: '2' } }), 'd1')+ oldEntry.segments = []+ store.releaseBatch(0)+ ;(store as any).releaseWritten('1:7', oldEntry)++ expect((store as any).entries.get('1:7')?.segments).toHaveLength(1)+ })+ })++ describe('round-2 closures', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('a merge waits for a write already on the wire before sending', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ await bound.applyEventOps(person, ops({ $set: { plan: 'older' } }), 'd1')++ // The lane's write is mid-RPC when the merge starts. If the merge+ // request goes out first, the saga applies its newer $set and+ // this older in-flight write lands on top of it — silently.+ let releaseWrite: () => void = () => {}+ repository.updatePersonProperties.mockImplementationOnce(+ (() =>+ new Promise((resolve) => {+ releaseWrite = () => resolve({ person, updated: true })+ })) as never+ )+ const events: string[] = []+ repository.mergePersons = jest.fn().mockImplementation(() => {+ events.push('merge-sent')+ return Promise.resolve({ survivor: person, results: [] })+ })++ const flushing = bound.flush()+ await new Promise((resolve) => setTimeout(resolve, 0))+ const merging = bound.mergePersons(mergeReq())+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(events).toEqual([])++ events.push('write-landed')+ releaseWrite()+ await merging+ await flushing++ expect(events).toEqual(['write-landed', 'merge-sent'])+ })+ })++ describe('convergence closures', () => {+ it('a fence bounce counts as coordination, not on the flush error series', async () => {+ personhogStoreFlushCounter.reset()+ personhogStoreFlushErrorCounter.reset()+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { mine: 'kept' } }), 'd1')+ repository.updatePersonProperties.mockRejectedValue(+ new PersonhogFencedError('PERSON_MERGING', '7', 'op-1') as never+ )++ await expect(bound.flush()).rejects.toThrow(PersonhogFencedError)++ const outcomes = (await personhogStoreFlushCounter.get()).values+ expect(outcomes.find((entry) => entry.labels.outcome === 'fenced')?.value).toBe(1)+ expect(outcomes.find((entry) => entry.labels.outcome === 'error')?.value ?? 0).toBe(0)+ expect(await counterTotal(personhogStoreFlushErrorCounter)).toBe(0)+ })++ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it.each([+ [+ 'a settled refusal',+ new ConnectError(+ 'op_id was already used for a different request',+ Code.FailedPrecondition,+ new Headers({ 'x-semantic-refusal': 'op_id_reused' })+ ),+ 'merge_refused',+ ],+ ['a no-verdict call failure', new Error('transport closed'), 'merge_no_verdict'],+ ])('purging on %s counts under its own reason', async (_label, error, reason) => {+ personhogStoreCachePurgeCounter.reset()+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'pro' } }), 'd1')+ repository.mergePersons = jest.fn().mockRejectedValue(error as never)++ await expect(bound.mergePersons(mergeReq())).rejects.toThrow()++ const reasons = (await personhogStoreCachePurgeCounter.get()).values+ expect(reasons.find((entry) => entry.labels.reason === reason)?.value ?? 0).toBeGreaterThan(0)+ })++ it('a merge writes the lanes it fences before its request goes out', async () => {+ personhogStoreFlushCounter.reset()+ const boundA = store.forBatch(0)+ const boundB = store.forBatch(1)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await boundA.fetchForUpdate(1, 'd1')+ // A multi-segment lane, so it cannot be carried: only the fence+ // parks it. Batch A folded these ops and will ack on flush.+ await boundA.applyEventOps(person, ops({ $set: { a: '1', k: 'x' }, $unset: ['k'] }), 'd1')+ await boundA.applyEventOps(person, ops({ $set: { b: '2' }, $set_once: { k: 'y' } }), 'd1')++ let releaseMerge: () => void = () => {}+ repository.mergePersons = jest.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseMerge = () => resolve({ survivor: person, results: [] })+ })+ )+ const merging = boundB.mergePersons(mergeReq())+ await new Promise((resolve) => setTimeout(resolve, 0))++ // Batch A must not ack over ops nobody has written. The merge+ // writes the lane itself before its request goes out, so by the+ // time A flushes the ops are durable — the guarantee holds+ // through the write rather than through a wait.+ expect(repository.updatePersonProperties).toHaveBeenCalled()+ expect((store as any).entries.get('1:7')?.segments ?? []).toHaveLength(0)+ let flushSettled = false+ const flushing = boundA.flush().then(() => {+ flushSettled = true+ })+ await new Promise((resolve) => setTimeout(resolve, 0))+ // A may resolve while the merge is still on the wire, and that is+ // safe precisely because the merge already wrote these ops: the+ // ack covers durable state, which is what the invariant asks.+ expect(flushSettled).toBe(true)++ releaseMerge()+ await merging+ await flushing+ expect((store as any).entries.get('1:7')?.segments ?? []).toHaveLength(0)+ })++ it('the create found branch reads the leader before its doc becomes a baseline', async () => {+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({+ person: { ...person, properties: { plan: 'lagged' } },+ created: false,+ } as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, properties: { plan: 'leader' } } as never)+ const bound = store.forBatch(0)+ const result = await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd1' },+ undefined+ )++ // Identity's found-branch doc lags the leader; folding against it+ // can classify a genuinely new $set as no-change and suppress it.+ expect(repository.fetchPersonById).toHaveBeenCalledTimes(1)+ expect(result.success && result.person.properties).toEqual({ plan: 'leader' })+ })++ it('a deterministic INVALID_ARGUMENT is not wrapped as a call failure', async () => {+ const bound = store.forBatch(0)+ const rejection = new ConnectError('invalid', Code.InvalidArgument)+ repository.mergePersons = jest.fn().mockRejectedValue(rejection as never)++ // Wrapping it would fail the batch, and redelivery presents the+ // same request to the same validation forever — a permanently+ // wedged partition from one malformed id.+ const surfaced = await bound.mergePersons(mergeReq()).catch((error: unknown) => error)+ expect(surfaced).toBe(rejection)+ })+ })++ describe('verdict-pass closures', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('a post-verdict processing bug surfaces as itself, not as a call failure', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: person,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ const bug = new Error('post-verdict bug')+ jest.spyOn(store as any, 'purgeAfterMerge').mockImplementation(() => {+ throw bug+ })++ // Mislabeling this as a call failure would point responders at+ // the network for a merge that answered fine.+ const surfaced = await bound.mergePersons(mergeReq()).catch((error: unknown) => error)+ expect(surfaced).toBe(bug)+ expect(surfaced).not.toBeInstanceOf(PersonMergeCallFailedError)+ })+ })++ describe('residual closures', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('a merge call failure fails the batch instead of acking', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockRejectedValue(new Error('transport closed') as never)++ await expect(bound.mergePersons(mergeReq())).rejects.toThrow(PersonMergeCallFailedError)+ })+ })++ describe('round-3 regressions', () => {+ it('an update fetch never answers from the check cache on a stale absence', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'd2', person: { ...person, id: '8', properties: { plan: 'free' } } },+ ] as never)+ await bound.fetchForChecking(1, 'd2')+ // The standing edge routes the update fetch to the leader read,+ // which answers that the person is gone.+ repository.fetchPersonById.mockResolvedValueOnce(null as never)+ // The lagging check document must not become the update answer;+ // null routes the caller to the healing path.+ expect(await bound.fetchForUpdate(1, 'd2')).toBeNull()+ })++ it('derives a valid op uuid from any event uuid string', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: person,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'not-a-uuid-at-all',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ // Event uuids are client-supplied and not always UUIDs; the wire+ // always carries a well-formed uuidv5 the saga can parse.+ expect(repository.mergePersons.mock.calls[0][0].opId).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/+ )+ })+ })++ describe('round-2 coverage', () => {+ it('a flush exhausts its rounds rather than acking over a lane whose writer never settles', async () => {+ // Degraded to a return, the rounds guard would let the batch+ // commit offsets over segments that exist only in this process.+ jest.useFakeTimers()+ try {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ const entry = (store as any).entries.get('1:7')+ entry.inFlight = true+ entry.directWriteSettled = new Promise<void>(() => {})++ const flushing = bound.flush()+ const settled = flushing.then(+ () => 'acked' as const,+ (error: Error) => error.message+ )+ await jest.advanceTimersByTimeAsync(10_000)+ expect(await settled).toMatch(/flush cannot complete/)+ expect((store as any).entries.get('1:7').segments).toHaveLength(1)+ } finally {+ jest.useRealTimers()+ }+ })++ it('a merged verdict with no survivor releases the dead ids to re-resolve', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValueOnce([+ { teamId: 1, distinctId: 'anon-1', person: { ...person, id: '9' } },+ ] as never)+ repository.fetchPersonById.mockResolvedValueOnce({ ...person, id: '9' } as never)+ await bound.fetchForUpdate(1, 'anon-1')+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: null,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })++ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ // With nowhere to repoint, the id must at least stop naming the+ // destroyed person.+ expect(edgeOf('1:anon-1')).toBeUndefined()+ expect(hasProjection('1:9')).toBe(false)+ })++ it('one batch releasing leaves a shared lane and its cache intact for the other', async () => {+ const boundA = store.forBatch(0)+ const boundB = store.forBatch(1)+ await boundA.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ await boundB.applyEventOps(person, ops({ $set: { b: '2' } }), 'd1')+ await boundA.flush()+ store.releaseBatch(0)++ // B still references the lane and the memo; more folds and a+ // final drain must work, then B's release frees everything.+ await boundB.applyEventOps(person, ops({ $set: { c: '3' } }), 'd1')+ await boundB.flush()+ store.releaseBatch(1)++ expect(store.getFlushStats()).toEqual({+ dirtyEntryCount: 0,+ referencedBatchCount: 0,+ cacheEntryCount: 0,+ })+ })+ })++ describe('round-2 regressions', () => {+ const mergeReq = (sources = ['anon-1']) => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: sources.map((distinctId) => ({ distinctId, eventUuid: 'event-uuid' })),+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ it('a late fill-only response does not roll back a drained lane\u2019s projection', async () => {+ // Batch 1 holds the projection alive by resolution reference+ // while batch 0 retires the lane, leaving a projection with no+ // lane behind it: exactly when a stale install slips past an+ // entries-based guard.+ const bound1 = store.forBatch(1)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound1.fetchForUpdate(1, 'd1')++ const bound0 = store.forBatch(0)+ await bound0.applyEventOps(person, ops({ $set: { flag: 'on' } }), 'd1')+ await bound0.flush()+ store.releaseBatch(0)+ expect((store as any).entries.has('1:7')).toBe(false)++ // A prefetch issued before the flush delivers its stale snapshot+ // now. Installing it would give batch 1 a baseline without `flag`,+ // and a revert-shaped $set would classify no-change.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd2', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person, properties: { plan: 'free' } } as never)+ await store.prefetchPersons([{ teamId: 1, distinctId: 'd2', batchId: 1 }])++ const seen = await bound1.fetchForUpdate(1, 'd1')+ expect(seen?.properties).toEqual(expect.objectContaining({ flag: 'on' }))+ })++ it('a mid-redirect fold survives even when the direct write landed segments first', async () => {+ const bound = store.forBatch(0)+ // Two segments; the first lands, the second hits the merged-away+ // person. The redirect then exhausts against a genuinely deleted+ // person while a new fold arrives — which this pass never+ // attempted and must not discard.+ await bound.applyEventOps(person, ops({ $set: { a: '1', k: 'x' }, $unset: ['k'] }), 'd1')+ await bound.applyEventOps(person, ops({ $set: { b: '2' }, $set_once: { k: 'y' } }), 'd1')+ repository.updatePersonProperties+ .mockResolvedValueOnce({ person, updated: true } as never)+ .mockRejectedValueOnce(new NoRowsUpdatedError('merged away') as never)+ let folded = false+ repository.resolvePersonsByDistinctIds.mockImplementation(async () => {+ if (!folded) {+ folded = true+ await bound.applyEventOps(person, ops({ $set: { later: 'fold' } }), 'd1')+ }+ return [] as never+ })++ await expect(bound.flush()).rejects.toThrow(/resolves to nobody/)++ const sets = (store as any).entries.get('1:7').segments.map((segment: EventOps) => segment.set)+ expect(sets).toContainEqual({ later: 'fold' })+ expect(sets).toContainEqual({ b: '2' })+ })++ it('a replayed merged verdict purges again and keeps the live lane', async () => {+ const bound = store.forBatch(0)+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: person,+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ await bound.mergePersons(mergeReq())+ // A replay of the same verdict meets an already-purged cache:+ // purging again is a no-op for the edges and must not discard+ // the ops the survivor's live lane still holds.+ await bound.applyEventOps(person, ops({ $set: { alive: 'yes' } }), 'd1')+ await bound.mergePersons(mergeReq())++ expect(edgeOf('1:d1')).toBeUndefined()+ // The replay's drain wrote the lane before its call went out, so+ // the ops are durable rather than discarded.+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(+ expect.objectContaining({ setProperties: { alive: 'yes' } }),+ expect.any(String)+ )+ })++ it('a successful redirect repoints the lane\u2019s distinct id at the survivor', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')++ // A merge on another pod destroyed the person; this store only+ // learns of it through the failed write.+ repository.updatePersonProperties+ .mockRejectedValueOnce(new NoRowsUpdatedError('merged away') as never)+ .mockResolvedValue({ person, updated: true } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'd1', person: { ...person, id: '12' } },+ ] as never)+ await bound.flush()++ // Without the repoint, every later event folds onto the dead+ // person and pays the redirect path forever.+ expect(edgeOf('1:d1')).toBe('1:12')+ })++ it('a resolve still naming the vanished person fails the flush to redeliver', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ repository.updatePersonProperties.mockRejectedValue(new NoRowsUpdatedError('merged away') as never)+ // Structurally the mapping is repointed before the leader ever+ // answers a tombstone, so this shape is an anomaly; failing+ // keeps the ops and surfaces it rather than dropping.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)++ await expect(bound.flush()).rejects.toThrow(/the same person/)+ expect((store as any).entries.get('1:7').segments).toHaveLength(1)+ })++ it('does not memoize extra distinct ids when the person already existed', async () => {+ repository.getOrCreatePersonByDistinctId.mockResolvedValue({ person, created: false } as never)+ const bound = store.forBatch(0)+ await bound.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'advisory-uuid',+ { distinctId: 'd1' },+ [{ distinctId: 'd2' }]+ )++ // The service maps extras only on the creation branch; d2 may+ // belong to someone else entirely.+ expect(edgeOf('1:d2')).toBeUndefined()+ })++ it('an abandoned batch sheds the unwritten lane it alone was keeping', async () => {+ // The shadow valve: a failed shadow flush cannot fail the batch,+ // so the release must not retain the lanes it left behind. The+ // counter is the instrument the ledger names for reading a+ // shed-correlated divergence spike.+ const shedBefore = await counterTotal(personhogStoreShadowShedCounter)+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')++ store.abandonBatch(0)++ expect((store as any).entries.has('1:7')).toBe(false)+ expect(projectionCount()).toBe(0)+ expect(await counterTotal(personhogStoreShadowShedCounter)).toBe(shedBefore + 1)+ })++ it('an abandoned in-flight lane is left to its write, then shed when the write fails', async () => {+ const bound0 = store.forBatch(0)+ await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ // Batch 1's merge fences the person; its pre-merge lane write+ // hangs holding the claim across batch 0's release.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ let failWrite: (e: Error) => void = () => {}+ repository.updatePersonProperties.mockImplementation(+ (() =>+ new Promise((_, reject) => {+ failWrite = reject+ })) as never+ )+ repository.mergePersons = jest.fn().mockImplementation(() => new Promise(() => {}))+ const merging = store+ .forBatch(1)+ .mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ .catch((error) => error)+ while (!(store as any).entries.get('1:7')?.inFlight) {+ await new Promise((resolve) => setImmediate(resolve))+ }++ store.abandonBatch(0)++ // The write owns the lane; abandon must not zero segments under+ // its pass.+ expect((store as any).entries.get('1:7').segments).toHaveLength(1)++ failWrite(new Error('identity down'))+ await merging++ // The failed settle sheds what nothing references, so the entry+ // does not persist as ownerless retry work no abandon revisits.+ expect((store as any).entries.has('1:7')).toBe(false)+ })++ it('a live batch folding onto an abandoned lane cancels the pending shed', async () => {+ // The settle-shed exists for ownerless entries; a live batch+ // referencing the entry again owns it, and the settle's own+ // reference check must skip the shed rather than discard the+ // ops that batch is folding.+ const bound0 = store.forBatch(0)+ await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ let failWrite: (e: Error) => void = () => {}+ repository.updatePersonProperties.mockImplementation(+ (() =>+ new Promise((_, reject) => {+ failWrite = reject+ })) as never+ )+ repository.mergePersons = jest.fn().mockImplementation(() => new Promise(() => {}))+ const merging = store+ .forBatch(1)+ .mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ .catch((error) => error)+ while (!(store as any).entries.get('1:7')?.inFlight) {+ await new Promise((resolve) => setImmediate(resolve))+ }+ store.abandonBatch(0)++ // The reference a fold records synchronously; the fold itself+ // would wait out the merge's fence first, which is beside the+ // point here — the claim being pinned is that a live reference+ // cancels the pending shed.+ ;(store as any).referenceEntry(2, '1:7')++ failWrite(new Error('identity down'))+ await merging++ const entry = (store as any).entries.get('1:7')+ expect(entry.segments.length).toBeGreaterThan(0)+ })++ it('an abandoned batch keeps segments a still-open batch references', async () => {+ const bound0 = store.forBatch(0)+ await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ const bound1 = store.forBatch(1)+ await bound1.applyEventOps(person, ops({ $set: { b: '2' } }), 'd1')++ store.abandonBatch(0)++ expect((store as any).entries.get('1:7').segments.length).toBeGreaterThan(0)+ })++ it('shutdown accepts a drained lane a batch has not released yet', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ await bound.flush()++ // The entry outlives its ops until the batch releases it. Reading+ // that as unwritten work would refuse a shutdown with nothing+ // left to write.+ await expect(store.shutdown()).resolves.toBeUndefined()+ })++ it('shutdown fails loudly while lanes still hold unwritten ops', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ await expect(store.shutdown()).rejects.toThrow(/unwritten ops/)+ })+ })++ describe('review regressions', () => {+ it('keeps the segments a failed write never attempted', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1', k: 'x' }, $unset: ['k'] }), 'd1')+ await bound.applyEventOps(person, ops({ $set: { b: '2' }, $set_once: { k: 'y' } }), 'd1')+ const entry = (store as any).entries.get('1:7')+ expect(entry.segments.length).toBe(2)++ // The first segment lands; the second fails transiently. The+ // failure must not take the landed one's place in the lane, nor+ // discard anything it never sent.+ repository.updatePersonProperties+ .mockResolvedValueOnce({ person, updated: true } as never)+ .mockRejectedValueOnce(new Error('leader unavailable') as never)+ await expect(bound.flush()).rejects.toThrow('leader unavailable')++ expect(entry.segments).toHaveLength(1)+ expect(entry.segments[0].set).toEqual({ b: '2' })+ })++ it('frees a person projection once its lane and its ids are gone', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ await bound.flush()+ expect(store.getFlushStats().cacheEntryCount).toBe(1)++ store.releaseBatch(0)++ // The lane drained and the last batch let go of the distinct id,+ // so nothing is left to keep the projection alive.+ expect(store.getFlushStats()).toEqual(expect.objectContaining({ dirtyEntryCount: 0, cacheEntryCount: 0 }))+ })++ it('shows later events the merged properties, with its own writes on top', async () => {+ const bound = store.forBatch(0)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd1', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)+ await bound.fetchForUpdate(1, 'd1')+ // A pending local write on the target, so the projection exists+ // and recordFetch will refuse to overwrite it.+ await bound.applyEventOps(person, ops({ $set: { local: 'mine' } }), 'd1')++ // `local` was written before the merge, so the document the saga+ // folds already holds it and hands it back on the survivor —+ // where the old carry path replayed it locally instead.+ repository.mergePersons = jest.fn().mockResolvedValue({+ // The fold sealed the pre-merge write, so its version sits+ // above the write's answer — a survivor below it is a replay.+ survivor: { ...person, version: 4, properties: { plan: 'free', fromSource: 'merged', local: 'mine' } },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })+ // The refresh reads the leader, which is at or past the fold.+ repository.fetchPersonById.mockResolvedValue({+ ...person,+ version: 5,+ properties: { plan: 'free', fromSource: 'merged', local: 'mine' },+ } as never)+ await bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })++ // The merge folded `fromSource` in, which no local projection+ // could know; the batch's own unwritten `local` still stands.+ const seen = await bound.fetchForUpdate(1, 'd1')+ expect(seen?.properties).toEqual({ plan: 'free', fromSource: 'merged', local: 'mine' })+ })++ it('releases the lanes behind a write that failed', async () => {+ const bound = store.forBatch(0)+ // A throw on one lane must not leave another marked in flight,+ // which every later pass would skip forever.+ await bound.applyEventOps({ ...person, id: '9' }, ops({ $set: { a: '1' } }), 'anon-1')+ await bound.applyEventOps({ ...person, id: '10' }, ops({ $set: { b: '2' } }), 'anon-2')+ repository.updatePersonProperties.mockRejectedValue(new Error('leader unavailable') as never)++ await expect(bound.flush()).rejects.toThrow('leader unavailable')++ expect((store as any).entries.get('1:10').inFlight).toBe(false)+ // And the next pass can actually take them again.+ repository.updatePersonProperties.mockResolvedValue({ person, updated: true } as never)+ await bound.flush()+ const written = repository.updatePersonProperties.mock.calls.map(([request]) => request.personId)+ expect(written).toEqual(expect.arrayContaining(['9', '10']))+ })+ })++ it('redirects through consecutive merges instead of dropping on the second', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), '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([])+ .mockRejectedValueOnce(new NoRowsUpdatedError('merged away'))+ .mockRejectedValueOnce(new NoRowsUpdatedError('survivor merged away too'))+ .mockResolvedValue({ person: { ...person, id: '10', version: 4 }, updated: true } as never)+ repository.resolvePersonsByDistinctIds+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }] as never)+ .mockResolvedValueOnce([{ teamId: 1, distinctId: 'd1', person: { ...person, id: '10' } }] as never)++ await bound.flush()++ expect(repository.updatePersonProperties).toHaveBeenLastCalledWith(+ expect.objectContaining({ personId: '10', setProperties: { a: '1' } }),+ expect.any(String)+ )+ })++ it('fails the flush rather than dropping ops a lineage keeps outrunning', async () => {+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ repository.updatePersonProperties.mockRejectedValue(new NoRowsUpdatedError('merged away') as never)+ let nextId = 8+ repository.resolvePersonsByDistinctIds.mockImplementation(() =>+ Promise.resolve([{ teamId: 1, distinctId: 'd1', person: { ...person, id: String(nextId++) } }] as never)+ )++ // Throwing rather than dropping is the claim; the attempt budget is+ // a tuning constant and not what this pins.+ await expect(bound.flush()).rejects.toThrow('merged away')+ expect((store as any).entries.get('1:7').segments).toHaveLength(1)+ })++ 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')+ })++ describe('concurrent batches share one flush', () => {+ const personB: () => InternalPerson = () => ({ ...person, id: '8', uuid: 'person-uuid-8' })++ it("a sibling entry's failure leaves it in its lane for the next pass", async () => {+ const bound0 = store.forBatch(0)+ const bound1 = store.forBatch(1)+ await bound0.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ await bound1.applyEventOps(personB(), ops({ $set: { b: '2' } }), 'd2')++ repository.updatePersonProperties.mockImplementation((request) =>+ request.personId === '8'+ ? Promise.reject(new Error('leader unreachable'))+ : Promise.resolve({ person: { ...person, version: 2 }, updated: true })+ )+ await expect(store.flush()).rejects.toThrow('leader unreachable')++ repository.updatePersonProperties.mockClear()+ repository.updatePersonProperties.mockResolvedValue({ person: { ...person, version: 2 }, updated: true })+ await store.flush()+ // Only the failed entry survives to re-write; the succeeded+ // one was consumed by the first pass.+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)+ expect(repository.updatePersonProperties.mock.calls[0][0].personId).toBe('8')+ })++ it('flush passes serialize, so ops folded mid-pass write strictly after it', async () => {+ let releaseFirst!: () => void+ const firstGate = new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ const callOrder: string[] = []+ repository.updatePersonProperties+ .mockImplementationOnce(async () => {+ callOrder.push('first:start')+ await firstGate+ callOrder.push('first:end')+ return { person: { ...person, version: 2 }, updated: true }+ })+ .mockImplementation(() => {+ callOrder.push('second')+ return Promise.resolve({ person: { ...person, version: 3 }, updated: true })+ })++ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { a: '1' } }), 'd1')+ const firstFlush = store.flush()+ // Spin microtasks until the first pass is mid-write, blocked+ // on the gate, so the next fold genuinely lands mid-pass.+ for (let i = 0; i < 100 && !callOrder.includes('first:start'); i++) {+ await Promise.resolve()+ }+ await bound.applyEventOps(person, ops({ $set: { a: '2' } }), 'd1')+ const secondFlush = store.flush()+ releaseFirst()+ await Promise.all([firstFlush, secondFlush])++ expect(callOrder).toEqual(['first:start', 'first:end', 'second'])+ })++ it('two batches folding one person write once, and a filtered-only fold rides along', async () => {+ person.properties = { $browser: 'Firefox' }+ const bound0 = store.forBatch(0)+ const bound1 = store.forBatch(1)+ // One shared entry per person, so a filtered-only fold from one+ // batch and a real one from another are the same entry: it writes+ // once, and there is no second writer to race it.+ await bound0.applyEventOps(person, ops({ $set: { $browser: 'Chrome' } }, 'pageview'), 'd1')+ await bound1.applyEventOps(person, ops({ $set: { plan: 'pro' } }, 'pageview'), 'd1')+ await store.flush()+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)+ expect(repository.updatePersonProperties.mock.calls[0][0].setProperties).toEqual({+ $browser: 'Chrome',+ plan: 'pro',+ })+ })})it('pending state is visible through every distinct id of the person', async () => {@@ -390,9 +2753,12 @@ describe('PersonhogPersonsStore', () => {const viaD1 = await bound.fetchForUpdate(1, 'd1')await bound.applyEventOps(viaD1!, ops({ $set: { a: '1' } }), 'd1')+ // The extra pays a resolve to learn which person it names; the+ // state it then sees is the shared view, pending ops included.+ repository.resolvePersonsByDistinctIds.mockResolvedValue([{ teamId: 1, distinctId: 'd2', person }] as never)+ repository.fetchPersonById.mockResolvedValue({ ...person } as never)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 () => {@@ -410,7 +2776,7 @@ describe('PersonhogPersonsStore', () => {expect(afterSecond.properties).toEqual({ plan: 'free', a: '1', b: '2' })})- it('releaseBatch frees the batch memo so later fetches hit the service again', async () => {+ it('releaseBatch frees the batch cache 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)@@ -420,29 +2786,18 @@ describe('PersonhogPersonsStore', () => {expect(repository.resolvePersonsByDistinctIds).toHaveBeenCalledTimes(2)})- it('releaseBatch drops an unflushed lane so nothing ships for the batch', async () => {+ it('releaseBatch defers eviction of an entry that still holds unwritten ops', 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('merges fail loudly until the store merge lands', async () => {- const bound = store.forBatch(0)- await expect(- bound.mergePersons({- teamId: 1,- targetDistinctId: 'd1',- sources: [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],- eventOps: ops({}),- eventUuid: 'op-1',- allowIdentifiedSources: false,- mergeMode: { type: 'SYNC', batchSize: undefined },- createdAtMs: 0,- })- ).rejects.toThrow(PersonhogPendingRpcError)+ // Releasing must not discard writes the batch never got to write;+ // the entry survives its last reference until it drains.+ await store.flush()+ expect(repository.updatePersonProperties).toHaveBeenCalledWith(+ expect.objectContaining({ setProperties: { a: '1' } }),+ expect.any(String)+ )})it('maps a direct diff update onto the folded RPC', async () => {@@ -459,7 +2814,15 @@ describe('PersonhogPersonsStore', () => {expect(sent.unsetProperties).toEqual(['gone'])expect(sent.isIdentified).toBe(true)expect(sent.lastSeenAtMs).toBe(7_200_000)- expect(updated).toEqual({ ...person, version: 2 })+ // What the leader answered, not what was sent: the caller reads the+ // applied document back, scalars included.+ expect(updated).toEqual({+ ...person,+ version: 2,+ properties: { plan: 'pro' },+ is_identified: true,+ last_seen_at: DateTime.fromMillis(7_200_000, { zone: 'utc' }),+ })expect(messages).toEqual([])})@@ -467,7 +2830,308 @@ describe('PersonhogPersonsStore', () => {const bound = store.forBatch(0)await expect(bound.updatePersonWithPropertiesDiffForUpdate(person, {}, [], { created_at: person.created_at }, 'd1')- ).rejects.toThrow(PersonhogPendingRpcError)+ ).rejects.toThrow(PersonhogUnsupportedFieldError)expect(repository.updatePersonProperties).not.toHaveBeenCalled()})++ describe('writing lanes before the merge', () => {+ const request = () => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventOps: ops({}, '$identify'),+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ })+ const sagaOpId = (): string => mergeOpIdFromRequest(1, 'event-uuid', 'd1', ['anon-1'], 10_000)+ // A function, not a value: `person` is assigned in beforeEach, so a+ // literal here would capture undefined and hand back a survivor with+ // no id.+ const merged = (): Record<string, unknown> => ({+ // The fold bumps the survivor's version past every prior read,+ // so a genuine merge survivor always clears the version guard;+ // only a replayed verdict from an earlier merge arrives below it.+ survivor: { ...person, version: 7, properties: { plan: 'merged' } },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '9' }],+ })++ beforeEach(() => {+ // The drain covers the persons the fresh resolve names.+ repository.resolvePersonsByDistinctIds.mockImplementation(((keys: { distinctId: string }[]) =>+ Promise.resolve(+ keys.map(({ distinctId }) => ({ teamId: 1, distinctId, person: { ...person } }))+ )) as never)+ })++ it('a lane opened by a sibling id still reaches the leader before its person dies', async () => {+ const bound = store.forBatch(0)+ // The event that opens the lane arrives on 'sibling', which the+ // merge below never names. Same person either way.+ await bound.applyEventOps(person, ops({ $set: { kept: 'yes' } }), 'sibling')+ repository.mergePersons = jest.fn().mockResolvedValue({+ survivor: { ...person, id: '9', properties: { plan: 'merged' } },+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged', sourcePersonId: '7' }],+ } as never)+ repository.resolvePersonsByDistinctIds.mockResolvedValue([+ { teamId: 1, distinctId: 'anon-1', person },+ ] as never)++ await bound.mergePersons(request())+ await bound.flush()++ // Postgres reaches the same pending update through any of the+ // person's distinct ids, so it folds these into the survivor.+ const sent = repository.updatePersonProperties.mock.calls.map((c: any[]) => c[0].setProperties)+ expect(sent).toContainEqual({ kept: 'yes' })+ })++ it('a lane retained by its own fence stays pending and the survivor is never installed', async () => {+ // The own-fence branch leaves the lane in place: its ops land+ // after the merge through the tombstone redirect. The purge+ // clears the projection, and the response survivor is a caller+ // snapshot only, so the next read goes to the leader.+ repository.updatePersonProperties.mockRejectedValue(+ new PersonhogFencedError('PERSON_MERGING', '7', sagaOpId()) as never+ )+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { mine: 'kept' } }), 'd1')++ const result = await bound.mergePersons(request())++ expect(result.survivor?.properties).toEqual({ plan: 'merged' })+ expect((store as any).entries.get('1:7')?.segments).toHaveLength(1)+ expect(hasProjection('1:7')).toBe(false)+ })++ it('does not let a concurrent flush resolve over a lane a merge is writing', async () => {+ // The merge claims the lane and writes it. A flush that skipped+ // the claim instead of waiting would resolve — and its batch ack+ // — while those ops were still on the wire.+ let releaseWrite: () => void = () => {}+ repository.updatePersonProperties.mockImplementation((() => {+ return new Promise((resolve) => {+ releaseWrite = () => resolve({ person, updated: true })+ })+ }) as never)+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const boundA = store.forBatch(0)+ const boundB = store.forBatch(1)+ await boundA.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ const merging = boundB.mergePersons(request())+ await new Promise((resolve) => setTimeout(resolve, 0))++ let flushSettled = false+ const flushing = boundA.flush().then(() => {+ flushSettled = true+ })+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(flushSettled).toBe(false)+ // One entry, one writer: the flush must wait the merge's write+ // out, not start a second one over the same segments, which would+ // leave two truncations racing over one lane.+ const writesFor7 = () =>+ repository.updatePersonProperties.mock.calls.filter(([call]) => call.personId === '7')+ expect(writesFor7()).toHaveLength(1)++ releaseWrite()+ await merging+ await flushing+ expect(flushSettled).toBe(true)+ expect(writesFor7()).toHaveLength(1)+ })++ it('waits for a write another merge claimed before folding around it', async () => {+ // Two merges overlap on one person. The first claims the lane and+ // its write is on the wire; without arming the promise the second+ // reads, it would fold a document the first is still writing.+ let releaseWrite: () => void = () => {}+ repository.updatePersonProperties.mockImplementation((() => {+ return new Promise((resolve) => {+ releaseWrite = () => resolve({ person, updated: true })+ })+ }) as never)+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const boundA = store.forBatch(0)+ const boundB = store.forBatch(1)+ await boundA.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ const first = boundA.mergePersons(request())+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(repository.updatePersonProperties).toHaveBeenCalledTimes(1)++ const second = boundB.mergePersons(request())+ await new Promise((resolve) => setTimeout(resolve, 0))+ // The second merge is parked on the first's write, so its request+ // has not gone out.+ expect(repository.mergePersons).not.toHaveBeenCalled()++ releaseWrite()+ await first+ await second+ expect(repository.mergePersons).toHaveBeenCalled()+ })++ it('lands the buffered writes before the merge request goes out', async () => {+ // The saga folds documents as it finds them, so anything still+ // buffered here would land after the fold and beat values the+ // merge rules say the target keeps.+ const order: string[] = []+ repository.updatePersonProperties.mockImplementation((() => {+ order.push('write')+ return Promise.resolve({ person, updated: true })+ }) as never)+ repository.mergePersons = jest.fn().mockImplementation(() => {+ order.push('merge')+ return Promise.resolve(merged())+ })+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ await bound.mergePersons(request())++ expect(order).toEqual(['write', 'merge'])+ })++ it("a drain bounce on this merge's own fence does not stop the merge", async () => {+ // The fence names this request's own saga, from an interrupted+ // delivery. Calling the saga is what settles it, and the lane's+ // ops land later via the redirect.+ personhogStoreMergeDrainCounter.reset()+ repository.updatePersonProperties.mockRejectedValue(+ new PersonhogFencedError('PERSON_MERGING', '7', sagaOpId()) as never+ )+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ await bound.mergePersons(request())++ expect(repository.mergePersons).toHaveBeenCalledTimes(1)+ expect((store as any).entries.get('1:7')?.segments ?? []).toHaveLength(1)+ const actions = (await personhogStoreMergeDrainCounter.get()).values.map((v) => v.labels.action)+ expect(actions).toContain('lane_fenced_own')+ })++ it('a drain bounce on a foreign fence maps to the claim-race boundary', async () => {+ // Another lifecycle op holds the person: the same claim race the+ // Postgres merge throws, which the service drops with a warning.+ // Calling the saga anyway would stack a second lifecycle op+ // behind the holder's.+ repository.updatePersonProperties.mockRejectedValue(+ new PersonhogFencedError('PERSON_MERGING', '7', 'another-ops-id') as never+ )+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ await expect(bound.mergePersons(request())).rejects.toBeInstanceOf(PersonClaimedByLifecycleOpError)+ expect(repository.mergePersons).not.toHaveBeenCalled()+ expect((store as any).entries.get('1:7')?.segments ?? []).toHaveLength(1)+ })++ it('a lane mid-redirect does not stop the merge', async () => {+ // Between a direct write finding its person gone and the+ // redirect resolving, the lane is in flight. Its ops land on+ // the survivor through the redirect, so the merge proceeds+ // without them rather than failing the batch.+ let releaseResolve: () => void = () => {}+ const resolving = new Promise<void>((resolve) => {+ releaseResolve = resolve+ })+ let announceRedirect: () => void = () => {}+ const reachedRedirect = new Promise<void>((resolve) => {+ announceRedirect = resolve+ })+ // Only the redirect's single-key resolve parks; the merge's own+ // resolve of its named ids must still answer.+ repository.resolvePersonsByDistinctIds.mockImplementation(((keys: { distinctId: string }[]) =>+ keys.length === 1+ ? (announceRedirect(),+ resolving.then(() => [{ teamId: 1, distinctId: 'd1', person: { ...person, id: '9' } }]))+ : Promise.resolve(+ keys.map(({ distinctId }) => ({ teamId: 1, distinctId, person: { ...person } }))+ )) as never)+ repository.updatePersonProperties.mockRejectedValue(new NoRowsUpdatedError('merged away') as never)+ repository.mergePersons = jest.fn().mockResolvedValue(merged())++ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')+ // Starts the flush; its direct write fails and the redirect parks+ // on the resolve, leaving the lane in the invisible window.+ const flushing = bound.flush()+ // Waits for the redirect to actually reach its resolve rather+ // than for a fixed number of ticks: under load the flush can+ // still be short of that window when a tick count expires, and+ // the merge then sails past a lane that is not yet in flight.+ await reachedRedirect++ await expect(bound.mergePersons(request())).resolves.toBeDefined()+ expect(repository.mergePersons).toHaveBeenCalledTimes(1)++ releaseResolve()+ await flushing.catch(() => undefined)+ })++ it('carries a stranded lane to the survivor at full strength, deletions included', async () => {+ // Another pod merged away a person this one holds ops for.+ // Postgres carries pending sets and unsets across unchanged, so+ // weakening them here would lose a deletion the customer asked+ // for and diverge from that backend.+ repository.resolvePersonsByDistinctIds.mockImplementation(((keys: { distinctId: string }[]) =>+ Promise.resolve(+ keys.map(({ distinctId }) => ({ teamId: 1, distinctId, person: { ...person, id: '7' } }))+ )) as never)+ const writes: { personId: string; set: unknown; setOnce: unknown; unset: unknown }[] = []+ repository.updatePersonProperties.mockImplementation(((call: {+ personId: string+ setProperties: unknown+ setOnceProperties: unknown+ unsetProperties: unknown+ }) => {+ if (call.personId === '9') {+ return Promise.reject(new NoRowsUpdatedError('merged away'))+ }+ writes.push({+ personId: call.personId,+ set: call.setProperties,+ setOnce: call.setOnceProperties,+ unset: call.unsetProperties,+ })+ return Promise.resolve({ person, updated: true })+ }) as never)+ repository.mergePersons = jest.fn().mockResolvedValue(merged())++ const bound = store.forBatch(0)+ await bound.applyEventOps(+ { ...person, id: '9' },+ ops({ $set: { plan: 'ours' }, $unset: ['stale'] }),+ 'anon-1'+ )+ await bound.mergePersons(request())+ await bound.flush()++ const survivorWrite = writes.find((write) => write.personId === '7')+ expect(survivorWrite?.set).toEqual({ plan: 'ours' })+ expect(survivorWrite?.unset).toEqual(['stale'])+ expect(survivorWrite?.setOnce).toEqual({})+ })++ it('fails the merge when the persons it must hold cannot be resolved', async () => {+ // Resolution decides which persons are held and written before+ // the fold, so degrading to the memo leaves a person the saga+ // folds neither held nor written. The resolve retries internally,+ // so reaching here means identity is down.+ repository.resolvePersonsByDistinctIds.mockRejectedValue(new Error('identity unavailable') as never)+ repository.mergePersons = jest.fn().mockResolvedValue(merged())+ const bound = store.forBatch(0)+ await bound.applyEventOps(person, ops({ $set: { plan: 'buffered' } }), 'd1')++ await expect(bound.mergePersons(request())).rejects.toBeInstanceOf(PersonMergeCallFailedError)+ expect(repository.mergePersons).not.toHaveBeenCalled()+ })+ })})diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex 22f633dd2312..e9aa81d80376 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -1,253 +1,473 @@+import { Code, ConnectError } from '@connectrpc/connect'import { DateTime } from 'luxon'import pLimit from 'p-limit'import { Counter } from 'prom-client'+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 { PersonhogPropertiesSizeError } from '~/common/personhog/persons'+import { PersonhogFencedError, PersonhogPropertiesSizeError } from '~/common/personhog/persons'import { PersonMessage } from '~/common/persons/person-message'-import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'+import { PersonClaimedByLifecycleOpError } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'import { CreatePersonResult } from '~/common/utils/db/db'import { logger } from '~/common/utils/logger'import { NoRowsUpdatedError } from '~/common/utils/utils'import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'import { Properties } from '~/plugin-scaffold'-import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'+import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'+import { MergeMode, PersonMergeCallFailedError } from './person-merge-types'import { EventOps, applyEventPropertyUpdates, computeOpsScalarUpdates, foldOps, refineEventOps } from './person-update'-import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'+import { mergeOpIdFromRequest } from './person-uuid'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsStore } from './persons-store'import { BatchBoundPersonsStore, PersonsStoreForBatch } 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',+ help: 'Lane write outcomes across the flush and merge-side paths, by outcome',+ labelNames: ['outcome'],+})++export const personhogStoreCachePurgeCounter = new Counter({+ name: 'personhog_store_cache_purge_total',+ help: 'Cache entries (resolution edges and person documents) discarded by a purge, by reason',+ labelNames: ['reason'],+})++export const personhogStoreMergeDrainCounter = new Counter({+ name: 'personhog_store_merge_drain_total',+ help: 'What the pre-merge drain did with each affected lane, by action',+ labelNames: ['action'],+})++export const personhogStoreShadowShedCounter = new Counter({+ name: 'personhog_store_shadow_shed_segments_total',+ help: 'Unwritten segments discarded at batch release in shadow mode, where a failed flush cannot fail the batch',+})++export const personhogStoreFlushErrorCounter = new Counter({+ name: 'personhog_store_flush_errors_total',+ help: 'Lane writes that failed without a classified outcome, by error class; the breakdown of flush_ops error',+ labelNames: ['error'],+})++export const personhogStorePrefetchFailedCounter = new Counter({+ name: 'personhog_store_prefetch_failed_total',+ help: 'Batch prefetches that failed, degrading the batch to resolving each distinct id on first touch',+})++export const personhogStoreUnsupportedFieldCounter = new Counter({+ name: 'personhog_store_unsupported_field_total',+ help: 'Direct updates refused because they carried a field this backend cannot write, by field',+ labelNames: ['field'],+})++export const personhogStoreMergeCallFailedCounter = new Counter({+ name: 'personhog_store_merge_call_failed_total',+ help: 'Merge calls that failed with no verdict, retried and then given up, by error class',+ labelNames: ['error'],+})++export const personhogStoreMergeOutcomeCounter = new Counter({+ name: 'personhog_store_merge_outcomes_total',+ help: 'Merge saga per-source outcomes observed by the ingestion client, 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.- */+ /** Bounds concurrent RPC fan-out; separate from the Postgres store's same-named pool option. */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.- */+ /** Mirrors the Postgres store's option; both stores must be given the same value. */updateAllProperties: boolean+ /** The saga's per-source move guard for SYNC mode, which carries no limit of its own. */+ syncMergeMoveLimit: number+ /** The injected repository's per-request timeout; the flush's lane wait derives from it. */+ requestTimeoutMs: number}const DEFAULT_OPTIONS: PersonhogPersonsStoreOptions = {maxConcurrentUpdates: 10,updateAllProperties: false,+ syncMergeMoveLimit: 10_000,+ requestTimeoutMs: 3_000,}const CALLER_TAG = 'ingestion/personhog-store'+/** SYNC uses the store's limit; other modes carry their own, validated at startup. */+function moveLimitFor(mergeMode: MergeMode, syncMergeMoveLimit: number): number {+ return mergeMode.type === 'SYNC' ? syncMergeMoveLimit : mergeMode.limit+}+/** 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'+/** A person field the leader's update RPC cannot express; failing loudly beats silent divergence. */+export class PersonhogUnsupportedFieldError extends Error {+ constructor(fields: string[]) {+ super(`PersonhogPersonsStore cannot write person field(s): ${fields.join(', ')}`)+ this.name = 'PersonhogUnsupportedFieldError'}}+/** Redirect re-entries one write pass spends chasing a merge chain before failing to redelivery. */+const REDIRECT_MAX_ATTEMPTS = 3++const FLUSH_WAIT_ROUND_MS = 1_000++/** A redirect failure that already incremented its own flush outcome. */+class CountedRedirectError extends Error {}++interface CapturedLane {+ personKey: string+ entry: OpsLaneEntry+ segments: number+}+interface OpsLaneEntry {teamId: numberpersonId: stringdistinctId: 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.- */+ /** Folded ops; a new segment starts only when foldOps cannot represent the composition. */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+ /** Set while a flush is writing this entry's leading segments; folds arriving meanwhile start a new segment. */+ inFlight?: boolean+ /** Settles when the current direct write finishes, so a merge can await a write already on the wire. */+ directWriteSettled?: Promise<void>+ /** Resolves `directWriteSettled`; armed with it at claim time. */+ settleWrite?: () => void+ /** Set when a shadow-mode release abandoned this entry mid-write; the settle sheds it once unreferenced. */+ abandoned?: 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.+ * The personhog person store: resolution and creation through the identity+ * service, person state through the leader's strong reads, and property+ * updates buffered as per-person lanes of folded ops the leader resolves+ * authoritatively. The cache holds BatchWritingPersonsCache's coherence+ * grade: a merge purges local state rather than repairing it, and a stale+ * view self-heals through the leader's tombstone redirect and re-reads.*/export class PersonhogPersonsStore implements PersonsStore {+ readonly backend = 'personhog' as const+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.+ * Folded ops, one entry per person, keyed by `${teamId}:${personId}` and+ * shared across batches so one writer owns each person.*/- private resolutions: Map<number, Map<string, string | null>> = new Map()+ private entries: Map<string, OpsLaneEntry> = new Map()+ /** Person keys each open batch references, for the release refcount. */+ private batchEntryKeys: Map<number, Set<string>> = 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.+ * Batches with a prefetch still in flight; a response landing after its+ * batch released must not record for a batch nothing can release again.*/- private personState: Map<number, Map<string, InternalPerson>> = new Map()+ private prefetchingBatches: Set<number> = new Set()++ // The cache mirrors BatchWritingPersonsCache structure for structure,+ // with two differences the names carry: `projections` holds a whole+ // projected person rather than a PersonUpdate diff (the diffs live in+ // the lanes as raw ops for the leader), and `resolutions` is tri-state+ // (person key, null for known-absent, missing for never-resolved).++ /** ↔ distinctIdToPersonId. `${teamId}:${distinctId}` to a person key, or null for known-absent. */+ private resolutions: Map<string, string | null> = new Map()+ /**+ * ↔ personUpdateCache. The projected person per `${teamId}:${personId}`:+ * the last update-grade service answer with the lanes' folded ops+ * applied in place.+ */+ private projections: Map<string, InternalPerson> = new Map()+ /**+ * ↔ personCheckCache, keyed by person rather than distinct id.+ * Identity-resolve documents for repeat checking reads, kept apart so+ * the update path never trusts a document that lags the leader.+ */+ private personCheckCache: Map<string, InternalPerson> = new Map()+ /** ↔ batchDistinctKeys. Distinct keys each open batch referenced. */+ private batchDistinctKeys: Map<number, Set<string>> = new Map()+ /** ↔ distinctKeyRefCount. Batches per distinct key; zero at release evicts the key. */+ private distinctKeyRefCount: Map<string, number> = new Map()+ /**+ * The single staleness guard, with no Postgres counterpart: bumped on+ * every purge. A read stamps it before its first await and declines to+ * record on mismatch, so a response from before the purge cannot+ * refill what the purge dropped.+ */+ private teamGeneration: Map<number, number> = new Map()+/** Serializes flush passes; see flush(). */private flushChain: Promise<void> = Promise.resolve()+ /** Total lane wait per flush, derived in the constructor from the transport retry budget. */+ private flushWaitBudgetMs: numberconstructor(private repository: PersonHogPersonWriteRepository,options?: Partial<PersonhogPersonsStoreOptions>) {this.options = { ...DEFAULT_OPTIONS, ...options }+ // A bad limit would fail every merge, or strand claimed lanes when+ // pLimit rejects it mid-flush; startup is where both fail usefully.+ if (!Number.isInteger(this.options.syncMergeMoveLimit) || this.options.syncMergeMoveLimit < 1) {+ throw new Error(+ `PERSONHOG_SYNC_MERGE_MOVE_LIMIT must be an integer >= 1, got ${this.options.syncMergeMoveLimit}`+ )+ }+ if (!Number.isInteger(this.options.maxConcurrentUpdates) || this.options.maxConcurrentUpdates < 1) {+ throw new Error(+ `PERSONHOG_STORE_MAX_CONCURRENT_UPDATES must be an integer >= 1, got ${this.options.maxConcurrentUpdates}`+ )+ }+ if (!Number.isInteger(this.options.requestTimeoutMs) || this.options.requestTimeoutMs < 1) {+ throw new Error(`PERSONHOG_TIMEOUT_MS must be an integer >= 1, got ${this.options.requestTimeoutMs}`)+ }+ // A flush waits out a claimed lane rather than failing past it. The+ // wait outlasts one write's full transport retry budget, derived+ // rather than chosen so the two cannot drift apart; a holder writing+ // a deeper lane can still exhaust it, and that flush fails to+ // redelivery instead of acking over unwritten ops.+ this.flushWaitBudgetMs = (TRANSPORT_MAX_RETRIES + 1) * this.options.requestTimeoutMs + FLUSH_WAIT_ROUND_MS}forBatch(batchId: number): PersonsStoreForBatch {return new BatchBoundPersonsStore(this, batchId)}+ private generationOf(teamId: number): number {+ return this.teamGeneration.get(teamId) ?? 0+ }++ private bumpGeneration(teamId: number): void {+ this.teamGeneration.set(teamId, this.generationOf(teamId) + 1)+ }++ /** Callers get copies, so stamping a result cannot edit the shared cache. */+ private snapshot(person: InternalPerson): InternalPerson+ private snapshot(person: InternalPerson | null): InternalPerson | null+ private snapshot(person: InternalPerson | null): InternalPerson | null {+ return person === null ? null : { ...person, properties: { ...person.properties } }+ }+/**- * 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.+ * Undefined on miss. The update grade insists on a projection, whose+ * lineage is the leader's; check also accepts an identity document.*/- async fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {- const cached = this.lookupMemo(teamId, distinctId, batchId)- if (cached !== undefined) {- return cached+ private getCachedPerson(+ teamId: number,+ distinctId: string,+ grade: 'check' | 'update'+ ): InternalPerson | null | undefined {+ const personKey = this.resolutions.get(`${teamId}:${distinctId}`)+ if (personKey === undefined) {+ return undefined}- const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)- return this.recordFetch(teamId, distinctId, resolved?.person ?? null, batchId)+ if (personKey === null) {+ return null+ }+ const projection = this.projections.get(personKey)+ if (projection !== undefined) {+ return this.snapshot(projection)+ }+ if (grade === 'check') {+ const checkDocument = this.personCheckCache.get(personKey)+ if (checkDocument !== undefined) {+ return this.snapshot(checkDocument)+ }+ }+ return undefined}/**- * 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.+ * An edge moving off a person takes that person's documents with it:+ * over-eviction costs a re-read, an unnamed document is never freed.*/- async fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {- const cached = this.lookupMemo(teamId, distinctId, batchId)- if (cached !== undefined) {- return cached+ private setDistinctIdToPersonId(distinctKey: string, personKey: string | null): void {+ const previous = this.resolutions.get(distinctKey)+ if (previous != null && previous !== personKey) {+ this.projections.delete(previous)+ this.personCheckCache.delete(previous)}- const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)- if (!resolved?.person) {- return this.recordFetch(teamId, distinctId, null, batchId)+ this.resolutions.set(distinctKey, personKey)+ }++ /** Records this batch's reference to a distinct key for the release refcount. */+ private trackBatchEntry(batchId: number, distinctKey: string): void {+ let keys = this.batchDistinctKeys.get(batchId)+ if (!keys) {+ keys = new Set()+ this.batchDistinctKeys.set(batchId, keys)+ }+ if (!keys.has(distinctKey)) {+ keys.add(distinctKey)+ this.distinctKeyRefCount.set(distinctKey, (this.distinctKeyRefCount.get(distinctKey) ?? 0) + 1)}- // 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)+ /**+ * Frees an edge whose last batch released, and the mapped person's+ * documents with it; a sibling id still naming the person pays one+ * re-read, as under the Postgres cache.+ */+ private evictDistinctKey(distinctKey: string): void {+ const personKey = this.resolutions.get(distinctKey)+ if (personKey === undefined) {+ return+ }+ this.resolutions.delete(distinctKey)+ // A dirty lane keeps its documents; the Postgres cache defers this+ // eviction too.+ if (personKey !== null && !this.entries.get(personKey)?.segments.length) {+ this.projections.delete(personKey)+ this.personCheckCache.delete(personKey)+ }}- /** 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+ /**+ * Strictly-newer wins on the version: reads can be delivered out of+ * order, and a projection carries folded ops an equal-version leader+ * document does not, so it must not roll them back.+ */+ private setCachedPersonForUpdate(personKey: string, doc: InternalPerson): void {+ const existing = this.projections.get(personKey)+ if (+ existing !== undefined &&+ typeof doc.version === 'number' &&+ typeof existing.version === 'number' &&+ doc.version <= existing.version+ ) {+ return}- if (resolution === null) {- return null+ this.projections.set(personKey, this.snapshot(doc))+ }++ /** Any lane keeps its unsent ops; the next reader re-reads. */+ private clearPersonCacheForPersonId(personKey: string, reason: string): void {+ if (this.projections.delete(personKey)) {+ personhogStoreCachePurgeCounter.inc({ reason })+ }+ this.personCheckCache.delete(personKey)+ }++ /** The edge goes; the next touch re-resolves through identity. */+ private removeDistinctIdFromCache(teamId: number, distinctId: string, reason: string): void {+ if (this.resolutions.delete(`${teamId}:${distinctId}`)) {+ personhogStoreCachePurgeCounter.inc({ reason })}- 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.+ * The persons' documents and every sibling id, named by the caller or+ * not — one pass over the resolutions however many persons the merge+ * touched.*/- private recordFetch(+ private clearAllCachesForPersonIds(personKeys: Set<string>, reason: string): void {+ for (const [distinctKey, mapped] of this.resolutions) {+ if (mapped !== null && personKeys.has(mapped)) {+ this.resolutions.delete(distinctKey)+ personhogStoreCachePurgeCounter.inc({ reason })+ }+ }+ for (const personKey of personKeys) {+ this.clearPersonCacheForPersonId(personKey, reason)+ }+ }++ /**+ * Caches a fetch result and returns the view callers should see. A+ * generation moved by a purge means the answer predates it: served,+ * never cached.+ */+ private cacheFetchedPerson(teamId: number,distinctId: string,fetched: InternalPerson | null,- batchId: number+ batchId: number,+ options: { grade: 'check' | 'update'; generation: number; fillOnly?: boolean }): InternalPerson | null {- const resolutions = this.resolutionMemo(batchId)+ if (options.generation !== this.generationOf(teamId)) {+ return this.snapshot(fetched)+ }+ const distinctKey = `${teamId}:${distinctId}`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}`)+ // A stale absence must not overwrite presence; a live mapping+ // stands and serves its best available view.+ const existing = this.resolutions.get(distinctKey)if (existing === undefined || existing === null) {- resolutions.set(`${teamId}:${distinctId}`, null)+ this.setDistinctIdToPersonId(distinctKey, null)+ this.trackBatchEntry(batchId, distinctKey)}- return existing != null ? (this.personStateMemo(batchId).get(existing) ?? null) : null+ return existing != null ? (this.getCachedPerson(teamId, distinctId, options.grade) ?? 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)+ // A fill-only response can be arbitrarily late: it must not move a+ // standing edge, and it only fills a hole, because a standing+ // projection carries folds it cannot know about.+ const standingEdge = this.resolutions.get(distinctKey)+ if (options.fillOnly && standingEdge !== undefined) {+ if (standingEdge === personKey && !this.projections.has(personKey)) {+ this.setCachedPerson(personKey, fetched, options.grade)+ }+ return standingEdge !== null ? (this.getCachedPerson(teamId, distinctId, options.grade) ?? null) : null+ }+ this.setDistinctIdToPersonId(distinctKey, personKey)+ this.trackBatchEntry(batchId, distinctKey)+ this.setCachedPerson(personKey, fetched, options.grade)+ return this.getCachedPerson(teamId, distinctId, options.grade) ?? this.snapshot(fetched)+ }++ private setCachedPerson(personKey: string, doc: InternalPerson, grade: 'check' | 'update'): void {+ if (grade === 'update') {+ this.setCachedPersonForUpdate(personKey, doc)+ return+ }+ // A projection is at least as fresh as any identity answer.+ if (!this.projections.has(personKey)) {+ this.personCheckCache.set(personKey, this.snapshot(doc))+ }+ }++ /** Resolves through identity and uses that person 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) {+ return cached+ }+ const generation = this.generationOf(teamId)+ const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)+ return this.cacheFetchedPerson(teamId, distinctId, resolved?.person ?? null, batchId, {+ grade: 'check',+ generation,+ })+ }++ /** Identity resolves the distinct id, then the leader supplies the freshest document. */+ async fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {+ const cached = this.getCachedPerson(teamId, distinctId, 'update')+ if (cached !== undefined) {+ return cached}- return state.get(personKey) ?? fetched+ const generation = this.generationOf(teamId)+ const edge = this.resolutions.get(`${teamId}:${distinctId}`)+ if (edge != null) {+ // The edge is trusted but only a checking read backs it, which+ // lags the leader; the update path pays one leader read.+ const person = await this.repository.fetchPersonById(teamId, edge.slice(edge.indexOf(':') + 1), CALLER_TAG)+ return this.cacheFetchedPerson(teamId, distinctId, person, batchId, { grade: 'update', generation })+ }+ const [resolved] = await this.repository.resolvePersonsByDistinctIds([{ teamId, distinctId }], CALLER_TAG)+ if (!resolved?.person) {+ return this.cacheFetchedPerson(teamId, distinctId, null, batchId, { grade: 'update', generation })+ }+ // A null read here means the person vanished mid-flight; the miss+ // is cached and the caller's create path re-resolves.+ const person = await this.repository.fetchPersonById(teamId, resolved.person.id, CALLER_TAG)+ return this.cacheFetchedPerson(teamId, distinctId, person, batchId, { grade: 'update', generation })}async createPerson(@@ -264,7 +484,8 @@ export class PersonhogPersonsStore implements PersonsStore {_tx: PersonRepositoryTransaction | undefined,batchId: number): Promise<CreatePersonResult> {- const { person, created } = await this.repository.getOrCreatePersonByDistinctId(+ const generation = this.generationOf(teamId)+ const createResult = await this.repository.getOrCreatePersonByDistinctId({teamId,distinctId: primaryDistinctId.distinctId,@@ -276,84 +497,337 @@ export class PersonhogPersonsStore implements PersonsStore {},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)+ 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)+ if (leaderDoc === null) {+ this.clearPersonCacheForPersonId(`${teamId}:${person.id}`, 'stale_write_answer')+ return { success: true, person: this.snapshot(person), messages: [], created }+ }+ person = leaderDoc}- 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 }+ const recorded = this.cacheFetchedPerson(teamId, primaryDistinctId.distinctId, person, batchId, {+ grade: 'update',+ generation,+ })+ // Extras are never cached: the service can leave a conflicting+ // extra mapped to its existing person. No messages: the identity+ // service publishes its own on creation.+ return { success: true, person: recorded ?? this.snapshot(person), messages: [], created }}- applyEventOps(+ async 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.+ // advances identity and last-seen, matching the Postgres store.if (ops.denied && ops.isIdentified === undefined && ops.lastSeenAtMs === undefined) {- return Promise.resolve([person, []])+ return [person, []]}+ const generation = this.generationOf(person.team_id)+ const target = await this.personNow(person, distinctId, batchId)+ return this.foldEventOps(target, ops, distinctId, batchId, generation)+ }- // A local projection for the caller: the same application the- // Postgres backend would perform, so the processor returns a- // sensible person. The leader's application at flush remains the- // authoritative one for this backend.+ /** The person this id belongs to now: a merge may have destroyed the caller's copy. */+ private async personNow(person: InternalPerson, distinctId: string, batchId: number): Promise<InternalPerson> {+ const resolved = this.getCachedPerson(person.team_id, distinctId, 'check')+ if (resolved) {+ return resolved+ }+ // An edge naming somebody else is the newer truth; one read+ // settles it, and a wrong fold heals through the redirect anyway.+ const edge = this.resolutions.get(`${person.team_id}:${distinctId}`)+ if (edge == null || edge === `${person.team_id}:${person.id}`) {+ return person+ }+ await this.fetchForUpdate(person.team_id, distinctId, batchId)+ return this.getCachedPerson(person.team_id, distinctId, 'check') ?? person+ }++ private foldEventOps(+ person: InternalPerson,+ ops: EventOps,+ distinctId: string,+ batchId: number,+ generation: number+ ): [InternalPerson, PersonMessage[]] {+ // The caller's view, matching what Postgres would apply; the+ // leader's application at flush is the authoritative one.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)+ this.referenceEntry(batchId, personKey)+ const existing = this.entries.get(personKey)if (!existing) {- lane.set(personKey, {+ this.entries.set(personKey, {teamId: person.team_id,personId: person.id,distinctId,segments: [ops],- triggersUpdate,})} else {- existing.triggersUpdate = existing.triggersUpdate || triggersUpdateconst last = existing.segments.length - 1- const folded = foldOps(existing.segments[last], ops)+ const lastSegment = existing.segments[last]+ // Folding into a segment already on the wire would change the+ // payload underneath the write or lose this event.+ const folded = lastSegment === undefined || existing.inFlight ? null : foldOps(lastSegment, ops)if (folded === null) {existing.segments.push(ops)} else {existing.segments[last] = folded}}- // 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, []])+ // Replaces the projection outright. A purge during personNow's read+ // outdates the view; the install declines and the next touch+ // re-resolves, while the lane keeps the ops.+ if (generation === this.generationOf(person.team_id)) {+ this.projections.set(personKey, this.snapshot(projected))+ this.setDistinctIdToPersonId(`${person.team_id}:${distinctId}`, personKey)+ this.trackBatchEntry(batchId, `${person.team_id}:${distinctId}`)+ }+ return [this.snapshot(projected), []]}- get backend(): PersonsBackend {- return 'personhog'+ /**+ * Runs the identity service's merge saga. Any verdict purges local+ * state for the merge's persons rather than repairing it; a call with+ * no verdict purges the same set and throws for the caller's bounded+ * retries.+ */+ async mergePersons(request: MergePersonsRequest, _batchId: number): Promise<MergePersonsResult> {+ const { teamId } = request+ const moveLimit = moveLimitFor(request.mergeMode, this.options.syncMergeMoveLimit)+ const opId = mergeOpIdFromRequest(+ teamId,+ request.eventUuid,+ request.targetDistinctId,+ request.sources.map((source) => source.distinctId),+ moveLimit+ )+ const namedIds = [request.targetDistinctId, ...request.sources.map((source) => source.distinctId)]+ // A stale edge can name a person the fresh resolve no longer+ // sees, and its lane still needs draining.+ const believed = namedIds+ .map((distinctId) => this.resolutions.get(`${teamId}:${distinctId}`))+ .filter((personKey): personKey is string => personKey != null)+ const resolved = await this.resolveMergeParticipants(teamId, namedIds)+ const affected = new Set<string>([...believed, ...resolved])+ await this.drainLanesBeforeMerge(teamId, [...affected], opId)++ let result+ try {+ result = await this.repository.mergePersons(+ {+ teamId,+ targetDistinctId: request.targetDistinctId,+ sources: request.sources,+ eventSet: request.eventOps.set,+ eventSetOnce: request.eventOps.setOnce,+ opId,+ allowIdentifiedSources: request.allowIdentifiedSources,+ moveLimit,+ // The saga refuses a negative created_at and pre-1970+ // events exist; floored here where the constraint lives.+ createdAtMs: Math.max(0, request.createdAtMs),+ // The raw event uuid, which the op id carries only as a+ // one-way derivation; the saga stamps it on a birth.+ creatorEventUuid: request.eventUuid,+ },+ CALLER_TAG+ )+ } catch (error) {+ // The saga may have run without answering; Postgres purges on+ // any merge throw too. Settled refusals get their own reason.+ const refused =+ error instanceof ConnectError &&+ (error.code === Code.InvalidArgument ||+ error.metadata.get(SEMANTIC_REFUSAL_METADATA_KEY) === SEMANTIC_REFUSAL_OP_ID_REUSED)+ this.purgeAfterMerge(teamId, namedIds, affected, refused ? 'merge_refused' : 'merge_no_verdict')+ // A verdict: redelivery meets the same validation forever, so+ // it propagates raw rather than wedging the partition.+ if (error instanceof ConnectError && error.code === Code.InvalidArgument) {+ personhogStoreMergeCallFailedCounter.inc({ error: 'InvalidArgumentSettled' })+ throw error+ }+ // Deterministic and pre-durable, so raw. Keyed on the slug: a+ // refusal from a later saga step is a parked op, so it takes the+ // no-verdict path below, whose retries attach and resume it; if+ // they give up, the lifecycle sweeper settles it.+ if (+ error instanceof ConnectError &&+ error.metadata.get(SEMANTIC_REFUSAL_METADATA_KEY) === SEMANTIC_REFUSAL_OP_ID_REUSED+ ) {+ personhogStoreMergeCallFailedCounter.inc({ error: 'OpIdReusedSettled' })+ throw error+ }+ // No verdict, so an ack could lose the merge. Only the call is+ // wrapped, so a post-verdict bug surfaces as itself.+ personhogStoreMergeCallFailedCounter.inc({+ error:+ error instanceof ConnectError+ ? `connect_${Code[error.code] ?? error.code}`+ : error instanceof Error+ ? error.constructor.name+ : 'unknown',+ })+ throw new PersonMergeCallFailedError(+ `personhog merge call failed with no verdict: ${error instanceof Error ? error.message : String(error)}`,+ error+ )+ }+ for (const source of result.results) {+ personhogStoreMergeOutcomeCounter.inc({ outcome: source.outcome })+ }+ const purgedPersons = new Set<string>(affected)+ for (const source of result.results) {+ if (source.sourcePersonId != null) {+ purgedPersons.add(`${teamId}:${source.sourcePersonId}`)+ }+ }+ if (result.survivor) {+ purgedPersons.add(`${teamId}:${result.survivor.id}`)+ }+ this.purgeAfterMerge(teamId, namedIds, purgedPersons, 'merge_verdict')+ // A fold that skipped or failed to settle any source aborts to the+ // sequential path, where each event gets its own durability+ // decision. The trigger id marks a fold request, so a single-pair+ // fold aborts the same way instead of dodging every guard.+ if (request.sources.length > 1 || request.triggerSourceDistinctId !== undefined) {+ const overLimit = result.results.some((source) => source.outcome === 'skipped_move_limit')+ const conflicted = result.results.some(+ (source) => source.outcome === 'skipped_conflict' || source.settled === false+ )+ const refused = result.results.some((source) => source.outcome === 'skipped_refused')+ // Error without a merged source can only be an abort, because+ // completion implies at least one source folded.+ const merged = result.results.some((source) => source.outcome === 'merged')+ const errored = !merged && result.results.some((source) => source.outcome === 'error')+ if (overLimit || conflicted || refused || errored) {+ return {+ survivor: null,+ results: [],+ foldAborted: overLimit ? 'limit' : conflicted ? 'conflict' : refused ? 'refused' : 'error',+ }+ }+ }+ // A caller snapshot, never cached: the next touch re-reads.+ return {+ survivor: this.snapshot(result.survivor),+ results: result.results,+ }}- mergePersons(_request: MergePersonsRequest, _batchId: number): Promise<MergePersonsResult> {- return Promise.reject(new PersonhogPendingRpcError('mergePersons', 'merge saga'))+ /** One batched identity resolve of a merge's named ids, answering the person keys. */+ private async resolveMergeParticipants(teamId: number, distinctIds: string[]): Promise<Set<string>> {+ let resolved+ try {+ resolved = await this.repository.resolvePersonsByDistinctIds(+ distinctIds.map((distinctId) => ({ teamId, distinctId })),+ CALLER_TAG+ )+ } catch (error) {+ // Unwrapped it would reach the merge service's catch-all, which+ // acks the event with the merge lost.+ personhogStoreMergeDrainCounter.inc({ action: 'resolve_failed' })+ throw new PersonMergeCallFailedError(+ `personhog merge drain resolve failed: ${error instanceof Error ? error.message : String(error)}`,+ error+ )+ }+ const personKeys = new Set<string>()+ for (const entry of resolved) {+ if (entry.person) {+ personKeys.add(`${teamId}:${entry.person.id}`)+ }+ }+ return personKeys+ }++ /**+ * Writes every affected lane before the merge goes out, so buffered+ * source properties fold with source precedence, as Postgres reads+ * them through its cache.+ */+ private async drainLanesBeforeMerge(teamId: number, personKeys: string[], opId: string): Promise<void> {+ // Waiting out in-flight writers lets the drain capture their+ // lanes instead of skipping them.+ const inFlightWrites = personKeys+ .map((personKey) => this.entries.get(personKey)?.directWriteSettled)+ .filter((settled): settled is Promise<void> => settled !== undefined)+ if (inFlightWrites.length > 0) {+ await Promise.all(inFlightWrites)+ }+ const captured: CapturedLane[] = []+ for (const personKey of personKeys) {+ const entry = this.entries.get(personKey)+ if (!entry || entry.segments.length === 0) {+ continue+ }+ // A redirect owns the lane; its ops land after the merge.+ if (entry.inFlight) {+ personhogStoreMergeDrainCounter.inc({ action: 'lane_in_flight' })+ continue+ }+ this.claimForWrite(entry)+ captured.push({ personKey, entry, segments: entry.segments.length })+ }+ if (captured.length === 0) {+ return+ }+ const limit = pLimit(this.options.maxConcurrentUpdates)+ const outcomes = await Promise.allSettled(+ captured.map(({ personKey, entry, segments }) => limit(() => this.writeEntry(personKey, entry, segments)))+ )+ for (const outcome of outcomes) {+ if (outcome.status !== 'rejected') {+ continue+ }+ const error = outcome.reason+ if (error instanceof PersonhogFencedError) {+ // Our own fence is an interrupted delivery of this same+ // merge; the saga call resumes it per op id.+ if (error.fencingOpId === opId) {+ personhogStoreMergeDrainCounter.inc({ action: 'lane_fenced_own' })+ continue+ }+ // The claim-race boundary the Postgres merge throws; the+ // service drops with a warning.+ personhogStoreMergeDrainCounter.inc({ action: 'lane_claimed' })+ throw new PersonClaimedByLifecycleOpError(+ `person held by lifecycle op ${error.fencingOpId ?? 'unknown'} during a merge drain`,+ teamId+ )+ }+ // The typed wrapper reaches the merge service's bounded retries.+ throw new PersonMergeCallFailedError(+ `personhog pre-merge write failed: ${error instanceof Error ? error.message : String(error)}`,+ error+ )+ }+ }++ /**+ * Every named id, affected person, and sibling id leaves the cache+ * under one generation bump. Lanes are kept: a destroyed person's ops+ * reach the survivor through the redirect, as they do under Postgres.+ */+ private purgeAfterMerge(teamId: number, distinctIds: string[], personKeys: Set<string>, reason: string): void {+ this.clearAllCachesForPersonIds(personKeys, reason)+ for (const distinctId of distinctIds) {+ this.removeDistinctIdFromCache(teamId, distinctId, reason)+ }+ this.bumpGeneration(teamId)}/** The leader enforces the size ceiling at admission; there is nothing to measure here. */@@ -362,42 +836,39 @@ export class PersonhogPersonsStore implements PersonsStore {}getFlushStats(): BatchWritingStoreFlushStats {- let dirtyEntryCount = 0- for (const lane of this.lanes.values()) {- dirtyEntryCount += lane.size- }- let cacheEntryCount = 0- for (const memo of this.personState.values()) {- cacheEntryCount += memo.size+ return {+ dirtyEntryCount: [...this.entries.values()].filter((entry) => entry.segments.length > 0).length,+ referencedBatchCount: this.batchEntryKeys.size,+ cacheEntryCount: this.projections.size,}- return { dirtyEntryCount, referencedBatchCount: this.lanes.size, cacheEntryCount }}/**- * 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.+ * A direct diff update mapped onto the leader's folded-update RPC;+ * fields with no RPC counterpart fail loudly rather than dropping. This+ * path buffers nothing; a race with a merge bounces on the leader's+ * fence and the batch redelivers.*/async updatePersonWithPropertiesDiffForUpdate(person: InternalPerson,propertiesToSet: Properties,propertiesToUnset: string[],otherUpdates: Partial<InternalPerson>,- _distinctId: string,- _batchId: number,- _forceUpdate?: boolean,+ distinctId: string,+ batchId: number,+ forceUpdate?: boolean,_tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]> {const unsupported = Object.keys(otherUpdates).filter((key) => key !== 'is_identified' && key !== 'last_seen_at')if (unsupported.length > 0) {- throw new PersonhogPendingRpcError(- 'updatePersonWithPropertiesDiffForUpdate',- `UpdatePersonProperties fields for ${unsupported.join(', ')}`- )+ // One count per field bounds the label by the schema.+ for (const field of unsupported) {+ personhogStoreUnsupportedFieldCounter.labels({ field }).inc()+ }+ throw new PersonhogUnsupportedFieldError(unsupported)}- const { person: updated } = await this.repository.updatePersonProperties(+ const generation = this.generationOf(person.team_id)+ const { person: updated, updated: applied } = await this.repository.updatePersonProperties({teamId: person.team_id,personId: person.id,@@ -407,59 +878,32 @@ export class PersonhogPersonsStore implements PersonsStore {unsetProperties: propertiesToUnset,isIdentified: otherUpdates.is_identified === true ? true : undefined,lastSeenAtMs: otherUpdates.last_seen_at?.toMillis(),+ forceUpdate: forceUpdate ?? false,},CALLER_TAG)+ const personKey = `${person.team_id}:${person.id}`if (!updated) {+ // A null document with the write applied means the leader moved+ // past what we held; without an applied write it is a no-op.+ if (applied) {+ this.clearPersonCacheForPersonId(personKey, 'stale_write_answer')+ }return [person, [], false]}- // No ClickHouse message: the leader's changelog is this backend'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'][],- _distinctId: string,- _tx: PersonRepositoryTransaction- ): Promise<Map<string, number>> {- const byPerson = await this.repository.getDistinctIdsForPersons(teamId, personIds, undefined, CALLER_TAG)- return new Map(personIds.map((id) => [id, byPerson[id]?.length ?? 0]))- }-- async fetchPersonDistinctIds(- person: InternalPerson,- _distinctId: string,- limit: number | undefined,- _tx: PersonRepositoryTransaction- ): Promise<string[]> {- const byPerson = await this.repository.getDistinctIdsForPersons(person.team_id, [person.id], limit, CALLER_TAG)- return byPerson[person.id] ?? []- }-- 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)+ // A generation moved by a purge means this answer predates it.+ if (generation === this.generationOf(person.team_id)) {+ this.setDistinctIdToPersonId(`${person.team_id}:${distinctId}`, personKey)+ this.trackBatchEntry(batchId, `${person.team_id}:${distinctId}`)+ this.setCachedPersonForUpdate(personKey, updated)}+ // No ClickHouse message: the leader's changelog is the person feed.+ return [this.snapshot(updated), [], false]}/**- * 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.+ * The update fetch's two-step done once for the whole batch, so+ * per-event processing hits the cache. Best-effort.*/async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {const seen = new Set<string>()@@ -469,11 +913,18 @@ export class PersonhogPersonsStore implements PersonsStore {return false}seen.add(key)- return this.lookupMemo(entry.teamId, entry.distinctId, entry.batchId) === undefined+ return this.getCachedPerson(entry.teamId, entry.distinctId, 'check') === undefined})if (unresolved.length === 0) {return}+ const generations = new Map<number, number>()+ for (const entry of unresolved) {+ this.prefetchingBatches.add(entry.batchId)+ if (!generations.has(entry.teamId)) {+ generations.set(entry.teamId, this.generationOf(entry.teamId))+ }+ }try {const resolved = await this.repository.resolvePersonsByDistinctIds(unresolved.map((entry) => ({ teamId: entry.teamId, distinctId: entry.distinctId })),@@ -484,48 +935,47 @@ export class PersonhogPersonsStore implements PersonsStore {resolved.map((entry, i) =>limit(async () => {const { batchId } = unresolved[i]+ const generation = generations.get(entry.teamId) ?? 0+ // Caching for a released batch recreates its key+ // set, and nothing ever releases it again.+ if (!this.prefetchingBatches.has(batchId)) {+ return+ }if (!entry.person) {- this.recordFetch(entry.teamId, entry.distinctId, null, batchId)+ this.cacheFetchedPerson(entry.teamId, entry.distinctId, null, batchId, {+ grade: 'check',+ generation,+ })return}const person = await this.repository.fetchPersonById(entry.teamId, entry.person.id, CALLER_TAG)- this.recordFetch(entry.teamId, entry.distinctId, person, batchId)+ if (!this.prefetchingBatches.has(batchId)) {+ return+ }+ // Fill-only: this response raced everything the+ // batch did since the request went out.+ this.cacheFetchedPerson(entry.teamId, entry.distinctId, person, batchId, {+ grade: 'update',+ generation,+ fillOnly: true,+ })})))} catch (error) {+ // Counted because the degradation reads as latency.+ personhogStorePrefetchFailedCounter.inc()logger.warn('personhog prefetch failed; resolution falls back to first touch', { error })}}/**- * Ships every batch's folded lanes to the leader, one entry per- * person, segments in order. There is deliberately no Postgres- * fallback. A missing person (deleted or merged mid-batch) and the- * leader's size rejection are counted and skipped, since neither can- * 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.- *- * Passes serialize, one at a time, with later calls queueing behind- * the running one. A pass claims a synchronous snapshot of every- * lane before shipping, so ops folded mid-pass land in fresh entries- * and ship on the next pass, never into an entry already in flight.- * A failed ship restores its entry, ahead of anything folded since:- * the failing flush call fails its own batch, but the entry may- * belong to a sibling batch that never acked its events, and folds- * are idempotent, so re-shipping on a later pass is safe.- *- * A lane entry with no update-worthy change — every refined change- * filtered, nothing forced, no scalar movement — is suppressed here- * rather than shipped, the same no-op classification the Postgres- * store applies at its flush. The exception is a person a sibling- * batch also holds ops for: the no-change verdict was judged against- * this batch's own baseline, so the entry ships instead and the- * leader's refinement no-ops it if it truly is one.+ * Writes the batch's folded lanes to the leader, one call per segment;+ * nothing publishes, because the leader's changelog is the person feed.+ * A missing person redirects to whatever its distinct id resolves to+ * now; a person genuinely gone and a size rejection are counted and+ * dropped since neither can succeed on retry; anything else fails the+ * flush. Passes serialize.*/async flush(): Promise<FlushResult[]> {const run = this.flushChain.then(() => this.flushPass())@@ -537,155 +987,350 @@ export class PersonhogPersonsStore implements PersonsStore {}private async flushPass(): Promise<FlushResult[]> {- const captured: { batchId: number; personKey: string; entry: OpsLaneEntry }[] = []- for (const [batchId, lane] of this.lanes) {- for (const [personKey, entry] of lane) {- captured.push({ batchId, personKey, entry })+ // Success lets the batch ack, so the pass must not return while any+ // lane holds unwritten segments: claimed lanes are waited out and+ // rewritten, or the pass fails and the batch redelivers.+ for (let round = 0; ; round++) {+ const pass = { deferrals: 0 }+ await this.writeEligibleLanes(pass)+ if (pass.deferrals === 0) {+ // No FlushResults: the leader's changelog is the person+ // feed, so a flush publishes nothing.+ return []+ }+ if (round * FLUSH_WAIT_ROUND_MS >= this.flushWaitBudgetMs) {+ personhogStoreFlushCounter.inc({ outcome: 'parked_exhausted' })+ throw new Error(+ `flush cannot complete: ${pass.deferrals} lanes deferred behind writes that did not settle`+ )+ }+ // Bounded, so a wedged writer exhausts the rounds instead of+ // hanging the flush past the consumer's poll budget.+ const settles = [...this.entries.values()]+ .filter((entry) => entry.segments.length > 0)+ .map((entry) => entry.directWriteSettled)+ .filter((settled): settled is Promise<void> => settled !== undefined)+ let timer: NodeJS.Timeout | undefined+ try {+ // A redirect-owned deferral has no settle; the round still+ // waits out the timer rather than racing an empty set.+ const roundTimer = new Promise<void>((resolve) => {+ timer = setTimeout(resolve, FLUSH_WAIT_ROUND_MS)+ })+ await (settles.length > 0 ? Promise.race([Promise.allSettled(settles), roundTimer]) : roundTimer)+ } finally {+ clearTimeout(timer)}}- // One entry per person per lane, so the number of captured- // entries for a person is the number of batches holding it.- const entriesPerPerson = new Map<string, number>()- for (const { personKey } of captured) {- entriesPerPerson.set(personKey, (entriesPerPerson.get(personKey) ?? 0) + 1)- }- for (const { batchId, personKey } of captured) {- this.lanes.get(batchId)?.delete(personKey)+ }++ private async writeEligibleLanes(pass: { deferrals: number }): Promise<void> {+ // No await in this block, so the claim snapshot is atomic.+ const captured: CapturedLane[] = []+ for (const [personKey, entry] of this.entries) {+ if (entry.segments.length === 0) {+ continue+ }+ // Another writer holds the lane; the round loop waits it out.+ if (entry.inFlight) {+ pass.deferrals += 1+ continue+ }+ this.claimForWrite(entry)+ captured.push({ personKey, entry, segments: entry.segments.length })}const limit = pLimit(this.options.maxConcurrentUpdates)const outcomes = await Promise.allSettled(- captured.map(({ batchId, personKey, entry }) =>- limit(() => this.shipEntry(batchId, personKey, entry, (entriesPerPerson.get(personKey) ?? 0) > 1))- )+ captured.map(({ personKey, entry, segments }) => limit(() => this.writeEntry(personKey, entry, segments))))- for (const [batchId, lane] of this.lanes) {- if (lane.size === 0) {- this.lanes.delete(batchId)- }- }const failed = outcomes.find((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')if (failed) {throw failed.reason}- // No FlushResults: the leader's changelog is the ClickHouse- // person feed, so a flush publishes nothing — shipping the- // segments is the whole job.- return []}- private async shipEntry(- batchId: number,- personKey: string,- entry: OpsLaneEntry,- siblingPending: boolean- ): Promise<void> {- if (!entry.triggersUpdate && !siblingPending) {- personhogStoreFlushCounter.inc({ outcome: 'filtered' })+ /** Runs on every exit from a write; a mark left set would strand the ops. */+ private releaseWritten(personKey: string, entry: OpsLaneEntry): void {+ entry.inFlight = false+ entry.settleWrite?.()+ entry.settleWrite = undefined+ entry.directWriteSettled = undefined+ if (entry.segments.length > 0) {+ // The settle is the last hand holding an abandoned entry.+ if (entry.abandoned && !this.entryHeldByAnyBatch(personKey) && this.entries.get(personKey) === entry) {+ personhogStoreShadowShedCounter.inc(entry.segments.length)+ entry.segments.length = 0+ this.entries.delete(personKey)+ this.clearPersonCacheForPersonId(personKey, 'lane_retired')+ }return}+ // Identity-guarded: a stale finalizer must not retire a recreated entry.+ if (!this.entryHeldByAnyBatch(personKey) && this.entries.get(personKey) === entry) {+ this.entries.delete(personKey)+ // Evictions defer the document drop to a dirty lane; it lands here.+ this.clearPersonCacheForPersonId(personKey, 'lane_retired')+ }+ }++ private async writeEntry(personKey: string, entry: OpsLaneEntry, segments: number): Promise<void> {try {- for (const ops of entry.segments) {- await this.repository.updatePersonProperties(- {- teamId: entry.teamId,- personId: entry.personId,- eventName: ops.eventName,- setProperties: ops.set,- setOnceProperties: ops.setOnce,- unsetProperties: ops.unset,- isIdentified: ops.isIdentified,- lastSeenAtMs: ops.lastSeenAtMs,- },- CALLER_TAG- )+ // What this pass owes; the array length is no substitute, since+ // folds arriving mid-redirect inflate it.+ const progress = { remaining: segments }+ // Every iteration writes the remainder, drops a unit, or+ // throws; the redirect budget fails a fast-merging lineage to+ // redelivery rather than chasing it forever.+ let viaRedirect = false+ let redirects = 0+ while (progress.remaining > 0) {+ try {+ if (viaRedirect) {+ await this.redirectToSurvivor(entry, progress)+ personhogStoreFlushCounter.inc({ outcome: 'redirected' })+ break+ }+ await this.writeSegments(entry, entry.personId, progress)+ personhogStoreFlushCounter.inc({ outcome: 'success' })+ break+ } catch (error) {+ if (error instanceof NoRowsUpdatedError && redirects < REDIRECT_MAX_ATTEMPTS) {+ // Merged or deleted since the fold; the lane is+ // redirect-owned from here.+ redirects += 1+ entry.settleWrite?.()+ entry.settleWrite = undefined+ entry.directWriteSettled = undefined+ viaRedirect = true+ continue+ }+ if (error instanceof PersonhogPropertiesSizeError) {+ // The rejected segment can never succeed, so it goes+ // and the loop writes the remainder; the log covers+ // the leader's per-team-throttled customer warning.+ personhogStoreFlushCounter.inc({ outcome: 'size_violation' })+ logger.warn('🤔', 'leader refused a write on properties size; the ops are discarded', {+ team_id: entry.teamId,+ person_id: entry.personId,+ distinct_id: entry.distinctId,+ })+ entry.segments.shift()+ progress.remaining -= 1+ continue+ }+ if (error instanceof PersonhogFencedError) {+ // Expected coordination, so it stays off the error+ // series an alert would page on: the holder settles+ // and redelivery flows.+ personhogStoreFlushCounter.inc({ outcome: 'fenced' })+ logger.warn('flush bounced on a lifecycle fence; the batch redelivers', {+ teamId: entry.teamId,+ personId: entry.personId,+ fencingOpId: error.fencingOpId,+ })+ } else {+ if (!(error instanceof CountedRedirectError)) {+ personhogStoreFlushCounter.inc({ outcome: 'error' })+ personhogStoreFlushErrorCounter.inc({ error: errorClassLabel(error) })+ }+ logger.error('Failed to flush folded update to personhog', {+ teamId: entry.teamId,+ personId: entry.personId,+ error,+ })+ }+ // The unwritten segments stay in the entry for the next pass.+ throw error+ }}- 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', {+ } finally {+ this.releaseWritten(personKey, entry)+ }+ }++ /**+ * Armed at claim time, not write start, so a merge cannot miss a lane+ * yet to reach its concurrency slot.+ */+ private claimForWrite(entry: OpsLaneEntry): void {+ entry.inFlight = true+ entry.settleWrite = undefined+ entry.directWriteSettled = new Promise((resolve) => {+ entry.settleWrite = resolve+ })+ }++ /**+ * Writes a lane's leading segments, removing each as it lands. The+ * answers are not cached: the projection already carries every folded+ * op, and the leader's refinement arrives on the next re-read.+ */+ private async writeSegments(entry: OpsLaneEntry, personId: string, progress: { remaining: number }): Promise<void> {+ const count = Math.min(progress.remaining, entry.segments.length)+ for (let written = 0; written < count; written++) {+ const ops = entry.segments[0]+ const { person: answer } = await this.repository.updatePersonProperties(+ {teamId: entry.teamId,- personId: entry.personId,- error,- })- this.restoreEntry(batchId, personKey, entry)- throw error+ personId,+ eventName: ops.eventName,+ setProperties: ops.set,+ setOnceProperties: ops.setOnce,+ unsetProperties: ops.unset,+ isIdentified: ops.isIdentified,+ lastSeenAtMs: ops.lastSeenAtMs,+ forceUpdate: ops.shouldForceUpdate,+ },+ CALLER_TAG+ )+ entry.segments.shift()+ progress.remaining -= 1+ // A null answer without a throw means the write applied and+ // the leader moved past what we held. Redirect writes are+ // excluded: the redirect purges the survivor itself.+ if (personId === entry.personId && answer === null) {+ this.clearPersonCacheForPersonId(`${entry.teamId}:${personId}`, 'stale_write_answer')}}}/**- * Puts a failed entry back in its lane, its segments ahead of any- * folded since the pass claimed it, preserving order for the next- * pass. A released batch stays released: its redelivery re-folds- * these ops.+ * Re-resolves a vanished person's distinct id and writes to whoever+ * owns it now, matching the Postgres merged-away recovery. One resolve+ * is enough: the saga repoints mappings before the leader answers a+ * tombstone, and no owner means a genuine delete.*/- private restoreEntry(batchId: number, personKey: string, entry: OpsLaneEntry): void {- const lane = this.lanes.get(batchId)- if (!lane) {- return+ private async redirectToSurvivor(entry: OpsLaneEntry, progress: { remaining: number }): Promise<void> {+ const generation = this.generationOf(entry.teamId)+ const [resolved] = await this.repository.resolvePersonsByDistinctIds(+ [{ teamId: entry.teamId, distinctId: entry.distinctId }],+ CALLER_TAG+ )+ const survivorId = resolved?.person?.id+ if (survivorId === undefined || survivorId === entry.personId) {+ // Released, so the redelivered events re-resolve rather than+ // folding onto the corpse again.+ this.removeDistinctIdFromCache(entry.teamId, entry.distinctId, 'redirect_gone')+ this.clearPersonCacheForPersonId(`${entry.teamId}:${entry.personId}`, 'redirect_gone')+ personhogStoreFlushCounter.inc({ outcome: 'redirect_gone' })+ throw new CountedRedirectError(+ `person ${entry.personId} in team ${entry.teamId} vanished and ${entry.distinctId} resolves to ` ++ `${survivorId === undefined ? 'nobody' : 'the same person'}; failing the flush to redeliver`+ )}- const newer = lane.get(personKey)- if (!newer) {- lane.set(personKey, entry)- return+ // The resolve proved where the id belongs, so heal the edge, the+ // repoint the Postgres cache performs too. Skipped when a purge+ // moved the generation (this answer predates it), and for a key no+ // batch recorded (a mapping nothing would ever release).+ if (generation === this.generationOf(entry.teamId)) {+ const distinctKey = `${entry.teamId}:${entry.distinctId}`+ if (this.resolutions.has(distinctKey)) {+ this.setDistinctIdToPersonId(distinctKey, `${entry.teamId}:${survivorId}`)+ }+ }+ this.clearPersonCacheForPersonId(`${entry.teamId}:${entry.personId}`, 'redirect_survivor')+ // Ops travel as they stand, deletions included, matching Postgres.+ try {+ await this.writeSegments(entry, survivorId, progress)+ } finally {+ // The survivor's projection cannot know about these ops, even+ // the partial set a failed write may have landed.+ this.clearPersonCacheForPersonId(`${entry.teamId}:${survivorId}`, 'redirect_survivor')+ }+ }++ /** An entry still holding unwritten ops outlives its last reference. */+ releaseBatch(batchId: number): void {+ // Any prefetch still on the wire answers into nothing from here on.+ this.prefetchingBatches.delete(batchId)+ const keys = this.batchEntryKeys.get(batchId)+ this.batchEntryKeys.delete(batchId)+ for (const personKey of keys ?? []) {+ if (this.entryHeldByAnyBatch(personKey)) {+ continue+ }+ const entry = this.entries.get(personKey)+ if (entry && entry.segments.length > 0) {+ // The entry stays until its write drains it.+ continue+ }+ this.entries.delete(personKey)}- newer.segments = [...entry.segments, ...newer.segments]- newer.triggersUpdate = newer.triggersUpdate || entry.triggersUpdate+ this.releaseBatchId(batchId)}/**- * 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.+ * The shadow valve: a shadow flush failure cannot fail the batch, so+ * unwritten segments only this batch was keeping are shed and counted+ * rather than growing without bound through an outage.*/- releaseBatch(batchId: number): void {- this.resolutions.delete(batchId)- this.personState.delete(batchId)- this.lanes.delete(batchId)+ abandonBatch(batchId: number): void {+ this.prefetchingBatches.delete(batchId)+ const keys = this.batchEntryKeys.get(batchId)+ this.batchEntryKeys.delete(batchId)+ for (const personKey of keys ?? []) {+ if (this.entryHeldByAnyBatch(personKey)) {+ continue+ }+ const entry = this.entries.get(personKey)+ if (entry?.inFlight) {+ // The flag hands the shed to the write's settle instead of+ // zeroing segments under it.+ entry.abandoned = true+ continue+ }+ if (entry && entry.segments.length > 0) {+ personhogStoreShadowShedCounter.inc(entry.segments.length)+ entry.segments.length = 0+ }+ this.entries.delete(personKey)+ }+ this.releaseBatchId(batchId)}- shutdown(): Promise<void> {- return Promise.resolve()+ /** Drops a batch's distinct-key references, freeing edges no other batch holds. */+ private releaseBatchId(batchId: number): void {+ const keys = this.batchDistinctKeys.get(batchId)+ this.batchDistinctKeys.delete(batchId)+ for (const distinctKey of keys ?? []) {+ const refs = (this.distinctKeyRefCount.get(distinctKey) ?? 1) - 1+ if (refs > 0) {+ this.distinctKeyRefCount.set(distinctKey, refs)+ continue+ }+ this.distinctKeyRefCount.delete(distinctKey)+ this.evictDistinctKey(distinctKey)+ }}- private opsLane(batchId: number): Map<string, OpsLaneEntry> {- let lane = this.lanes.get(batchId)- if (!lane) {- lane = new Map()- this.lanes.set(batchId, lane)+ /** Records that this batch is folding into a person's shared entry. */+ private referenceEntry(batchId: number, personKey: string): void {+ let keys = this.batchEntryKeys.get(batchId)+ if (!keys) {+ keys = new Set()+ this.batchEntryKeys.set(batchId, keys)}- return lane+ keys.add(personKey)}- private resolutionMemo(batchId: number): Map<string, string | null> {- let memo = this.resolutions.get(batchId)- if (!memo) {- memo = new Map()- this.resolutions.set(batchId, memo)+ /** A scan, not a counter: batches number in the handful and a counter can drift. */+ private entryHeldByAnyBatch(personKey: string): boolean {+ for (const keys of this.batchEntryKeys.values()) {+ if (keys.has(personKey)) {+ return true+ }}- return memo+ return false}- private personStateMemo(batchId: number): Map<string, InternalPerson> {- let memo = this.personState.get(batchId)- if (!memo) {- memo = new Map()- this.personState.set(batchId, memo)+ shutdown(): Promise<void> {+ // The data is redelivery-safe; the drain-order bug must be loud.+ const unwritten = [...this.entries.values()].filter((entry) => entry.segments.length > 0).length+ if (unwritten > 0) {+ return Promise.reject(+ new Error(`PersonhogPersonsStore shut down with ${unwritten} lanes holding unwritten ops`)+ )}- return memo+ return Promise.resolve()}}diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.tsindex ac5df774aac2..5c7e26a5cec0 100644--- a/nodejs/src/ingestion/common/persons/persons-store.ts+++ b/nodejs/src/ingestion/common/persons/persons-store.ts@@ -24,10 +24,9 @@ export interface MergePersonsSource {}/**- * Per-source verdicts a merge can answer. Both backends share the- * vocabulary; 'skipped_race' and the 'failed_*' verdicts come only- * from the Postgres merge's retrying transaction, and 'error' only- * from the saga.+ * Per-source merge verdicts. Both backends share the vocabulary;+ * 'skipped_race' and 'failed_*' come only from Postgres, 'error' in+ * practice only from the saga.*/export type MergePersonsOutcome =| 'merged'@@ -37,24 +36,40 @@ export type MergePersonsOutcome =| 'skipped_already_identified'| 'skipped_conflict'| 'skipped_move_limit'+ /**+ * Definitively refused before destroying anything; the recorded+ * verdict replays on every retry, so the pair settles as a lost merge.+ */+ | 'skipped_refused'| 'skipped_race'| 'failed_source_not_found'| 'failed_target_not_found'| 'failed_source_has_distinct_ids'| 'error'+ /**+ * A verdict this build cannot name, from a backend running ahead;+ * distinct from 'error' because the merge may well have happened.+ */+ | 'unknown'export interface MergePersonsSourceResult {sourceDistinctId: stringoutcome: MergePersonsOutcome- /** The source person the verdict speaks about, when the backend resolved one. */+ /**+ * The backend's durability statement: false means a retry under the+ * same op id may change the answer. Personhog only; absent is settled.+ */+ settled?: boolean+ /** The source person the verdict speaks about. Postgres only; the saga reports ids. */sourcePersonUuid?: string/*** The source person this verdict destroyed, present only on a merged* source. Merging away is permanent, so a caller may reconcile cached* state against it without re-reading, including entries cached under- * distinct ids the request never named.+ * distinct ids the request never named. Absent or null on every other+ * verdict.*/- sourcePersonId?: string+ sourcePersonId?: string | null}export interface MergePersonsRequest {@@ -84,17 +99,18 @@ export interface MergePersonsRequest {allowIdentifiedSources: boolean/*** The caller's move policy, from the same config the processor's- * over-limit handling reads. The Postgres merge bounds its- * distinct-id moves by it; the saga backend uses LIMIT/ASYNC's limit- * as its move-limit guard and falls back to its own configured- * guard for SYNC, which the saga cannot run unbounded.+ * over-limit handling reads; both backends bound their moves by it.*/mergeMode: MergeMode- /** Merge event created_at, epoch millis; becomes the survivor's when older. */+ /**+ * Merge event created_at, epoch millis; consulted only where a person+ * is born from the request. Otherwise the survivor keeps the earliest+ * created_at among the merged persons.+ */createdAtMs: number}-export type MergeFoldAbortReason = 'limit' | 'conflict' | 'deadlock' | 'error'+export type MergeFoldAbortReason = 'limit' | 'conflict' | 'refused' | 'deadlock' | 'error'export interface MergePersonsResult {/** The surviving person; null when the merge settled without one. */@@ -103,12 +119,17 @@ export interface MergePersonsResult {/** Post-commit ClickHouse production the caller may chain on; absent when the backend produced before returning. */kafkaAck?: Promise<void>/**- * Whether the caller still needs its follow-up property update;- * false when person creation already applied the event's properties.- * Absent means true.+ * Whether the caller still needs its follow-up property update; absent+ * means true. Postgres reports false when its own creation applied the+ * event's properties; personhog never claims it.*/survivorNeedsUpdate?: boolean- /** Multi-source only: the folded transaction rolled back untouched; the caller falls back to per-event merges. */+ /**+ * Multi-source only: the folded transaction rolled back and the caller+ * falls back to per-event merges. Not always untouched — a bootstrap+ * creation can commit before the fold begins, and its `kafkaAck` travels+ * on this result for the caller to await.+ */foldAborted?: MergeFoldAbortReason}@@ -141,9 +162,7 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {/*** 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.+ * mean against this store's own state.*/applyEventOps(person: InternalPerson,diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.tsindex cc37e9d3b1d7..9f8ec42165be 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts@@ -1,4 +1,13 @@-import { personhogStoreShadowErrorsCounter, personhogStoreShadowSkipsCounter } from '~/common/persons/metrics'+import { Code, ConnectError } from '@connectrpc/connect'+import { DateTime } from 'luxon'++import {+ personhogStoreShadowCompareFailedCounter,+ personhogStoreShadowComparedCounter,+ personhogStoreShadowDivergenceCounter,+ personhogStoreShadowErrorsCounter,+ personhogStoreShadowSkipsCounter,+} from '~/common/persons/metrics'import { InternalPerson } from '~/types'import { EventOps } from './person-update'@@ -9,6 +18,10 @@ import { RoutingPersonsStore, assertPersonsStoreModeConfig, parsePersonsStoreModjest.mock('~/common/persons/metrics', () => ({personhogStoreShadowErrorsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },personhogStoreShadowSkipsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },+ personhogStoreShadowDivergenceCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },+ personhogStoreShadowComparedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },+ personhogStoreShadowCompareFailedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },+ personhogStoreShadowFoldRedriveCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },}))const emptyMergeResult = (): MergePersonsResult => ({ survivor: null, results: [] })@@ -73,7 +86,7 @@ describe('RoutingPersonsStore', () => {// The personhog store implements PersonsStore, so the same// compile-checked factory serves; the cast to the concrete class// is the constructor's requirement, not an escape from checking.- const personhogMock = mockStore()+ const personhogMock = Object.assign(mockStore(), { abandonBatch: jest.fn() })const personhog = personhogMock as unknown as PersonhogPersonsStorereturn { pg, personhogMock, personhog }}@@ -81,6 +94,366 @@ describe('RoutingPersonsStore', () => {const makeStore = (stores: ReturnType<typeof makeStores>, mode: 'personhog' | 'shadow') =>new RoutingPersonsStore(stores.pg, stores.personhog, mode)+ describe('shadow divergence detection', () => {+ const divergences = (): Record<string, string>[] =>+ (personhogStoreShadowDivergenceCounter.labels as jest.Mock).mock.calls.map(([labels]) => labels)+ const counted = (): boolean =>+ (personhogStoreShadowDivergenceCounter.labels as jest.Mock).mock.results.every(+ (call) => (call.value.inc as jest.Mock).mock.calls.length > 0+ )++ it.each([+ ['a different person', { uuid: 'other-uuid' }, 'uuid'],+ ['a different identified flag', { is_identified: true }, 'is_identified'],+ ['different properties', { properties: { plan: 'pro' } }, 'properties'],+ ])('records a read answering %s', async (_case, shadowDiff, field) => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockResolvedValue({ ...person(1, '1'), ...shadowDiff })+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ // The error counter says personhog fell over. Nothing said it+ // answered a different person, which is the failure shadow mode+ // exists to find.+ expect(divergences()).toContainEqual({ verb: 'fetchForUpdate', field })+ expect(counted()).toBe(true)+ })++ it('records a read that found nobody where the authoritative one found somebody', async () => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockResolvedValue(null)+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ expect(divergences()).toContainEqual({ verb: 'fetchForUpdate', field: 'missing_shadow' })+ })++ it('records nothing when the two agree', async () => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockResolvedValue(person(1, '1'))+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ expect(divergences()).toEqual([])+ expect(personhogStoreShadowComparedCounter.labels).toHaveBeenCalledWith({ verb: 'fetchForUpdate' })+ })++ it.each([+ ['a nested object whose keys arrived in another order', { a: 1, b: 2 }, { b: 2, a: 1 }, false],+ ['an array whose order actually differs', [1, 2], [2, 1], true],+ ])('reads %s correctly', async (_case, pgValue, shadowValue, diverges) => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue({ ...person(1, '1'), properties: { nested: pgValue } })+ stores.personhogMock.fetchForUpdate.mockResolvedValue({+ ...person(1, '1'),+ properties: { nested: shadowValue },+ })+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ // Postgres stores jsonb in its own key order while the personhog+ // side arrives in the order it was written, so comparing+ // serialised forms would call every nested object a difference+ // and bury the ones that are real. Array order is the customer's.+ expect(divergences().some((labels) => labels.field === 'properties')).toBe(diverges)+ })++ it('records a merge that picked a different survivor', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({ survivor: person(1, '1'), results: [] })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: { ...person(1, '1'), uuid: 'other-uuid' },+ results: [],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons({} as never, 0)++ // Which person survives decides where every later event in the+ // batch lands, and a row diff cannot see it: both sides end with+ // a person that looks plausible on its own.+ expect(divergences()).toContainEqual({ verb: 'mergePersons', field: 'survivor' })+ })++ it('records a source the two backends settled differently', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_already_identified' }],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons({} as never, 0)++ expect(divergences()).toContainEqual({ verb: 'mergePersons', field: 'outcome' })+ })++ it('a verdict only the shadow produced records an outcome divergence', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons({} as never, 0)++ expect(divergences()).toContainEqual({ verb: 'mergePersons', field: 'outcome' })+ })++ it('a fold only one backend aborted records the disposition, without per-source noise', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: null,+ results: [],+ foldAborted: 'conflict',+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons({} as never, 0)++ expect(divergences()).toEqual([{ verb: 'mergePersons', field: 'fold_disposition' }])+ })++ const foldRequest = () => ({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [+ { distinctId: 'anon-1', eventUuid: 'uuid-1' },+ { distinctId: 'anon-2', eventUuid: 'uuid-2' },+ ],+ triggerSourceDistinctId: 'anon-1',+ eventUuid: 'uuid-1',+ eventOps: {+ set: { plan: 'pro' },+ setOnce: {},+ unset: [],+ denied: false,+ shouldForceUpdate: false,+ eventName: '$identify',+ },+ allowIdentifiedSources: false,+ mergeMode: { type: 'SYNC' as const },+ createdAtMs: 1_000,+ })++ it('a fold only the shadow aborted re-drives each pair as a sequential shadow merge', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ stores.personhogMock.mergePersons+ .mockResolvedValueOnce({ survivor: null, results: [], foldAborted: 'conflict' })+ .mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons(foldRequest() as never, 7)++ // The fold call, then one plain merge per pair: the pair's own+ // event uuid roots the op id, no trigger marks it fold-shaped,+ // and the ops are empty.+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)+ const pairCalls = stores.personhogMock.mergePersons.mock.calls.slice(1)+ expect(pairCalls.map((call: any[]) => call[0].sources)).toEqual([+ [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],+ [{ distinctId: 'anon-2', eventUuid: 'uuid-2' }],+ ])+ expect(pairCalls.map((call: any[]) => call[0].eventUuid)).toEqual(['uuid-1', 'uuid-2'])+ for (const call of pairCalls) {+ expect(call[0].triggerSourceDistinctId).toBeUndefined()+ expect(call[0].eventOps.set).toEqual({})+ }+ })++ it('a fold both backends executed re-drives nothing', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-1', outcome: 'merged' }],+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons(foldRequest() as never, 7)++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(1)+ })++ it('a failing re-drive pair does not stop the remaining pairs', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({+ survivor: person(1, '1'),+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ stores.personhogMock.mergePersons+ .mockResolvedValueOnce({ survivor: null, results: [], foldAborted: 'conflict' })+ .mockRejectedValueOnce(new Error('redrive transport failure'))+ .mockResolvedValue({+ survivor: person(1, '1'),+ results: [{ sourceDistinctId: 'anon-2', outcome: 'merged' }],+ })+ const store = makeStore(stores, 'shadow')++ await expect(store.mergePersons(foldRequest() as never, 7)).resolves.toBeDefined()++ expect(stores.personhogMock.mergePersons).toHaveBeenCalledTimes(3)+ })++ it('a fold both backends aborted records nothing', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue({ survivor: null, results: [], foldAborted: 'limit' })+ stores.personhogMock.mergePersons.mockResolvedValue({+ survivor: null,+ results: [],+ foldAborted: 'conflict',+ })+ const store = makeStore(stores, 'shadow')++ await store.mergePersons({} as never, 0)++ expect(divergences()).toEqual([])+ })++ it('tells shadow failures apart by class, not just by verb', async () => {+ class PersonhogFenceTimeoutError extends Error {}+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockRejectedValue(new PersonhogFenceTimeoutError('held'))+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb: 'fetchForUpdate',+ error: 'PersonhogFenceTimeoutError',+ })+ })++ it.each([+ ['unreachable', Code.Unavailable, 'Unavailable'],+ ['timed out', Code.DeadlineExceeded, 'DeadlineExceeded'],+ ['refusing', Code.FailedPrecondition, 'FailedPrecondition'],+ ])('separates an identity service that is %s', async (_case, code, label) => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockRejectedValue(new ConnectError('rpc failed', code))+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ // Every gRPC fault is the same ConnectError class, so labelling+ // by class puts unreachable, timed out, and refusing in one+ // number — the distinction a rollout most needs.+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb: 'fetchForUpdate',+ error: label,+ })+ })++ it('says which side was empty when only one found a person', async () => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(null)+ stores.personhogMock.fetchForUpdate.mockResolvedValue(person(1, '1'))+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'd1', 0)++ // personhog not having seen a person yet is expected early in a+ // rollout and fades; personhog holding one Postgres lost never is.+ expect(divergences()).toContainEqual({ verb: 'fetchForUpdate', field: 'missing_authoritative' })+ })++ it.each([+ ['shutdown', async (store: RoutingPersonsStore) => await store.shutdown()],+ ['releaseBatch', (store: RoutingPersonsStore) => store.releaseBatch(0)],+ ])('a shadow %s failure does not reach the caller', async (verb, act) => {+ const stores = makeStores()+ stores.personhogMock.shutdown.mockRejectedValue(new Error('lanes still hold ops'))+ stores.personhogMock.abandonBatch.mockImplementation(() => {+ throw new Error('release blew up')+ })+ const store = makeStore(stores, 'shadow')++ // Shadow's contract is that the non-authoritative backend+ // cannot fail the caller; release and shutdown were the two+ // paths that still could.+ await expect(Promise.resolve(act(store))).resolves.not.toThrow()+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb,+ error: 'Error',+ })+ })++ it('reads a shadow answer of undefined as absence, not as a comparator fault', async () => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ stores.personhogMock.fetchForUpdate.mockResolvedValue(undefined as never)+ const store = makeStore(stores, 'shadow')++ await expect(store.fetchForUpdate(1, 'd1', 0)).resolves.toEqual(person(1, '1'))++ // Dereferencing it would blame the backend for the comparator's+ // own crash, during the rollout the comparator exists to inform.+ expect(divergences()).toContainEqual({ verb: 'fetchForUpdate', field: 'missing_shadow' })+ expect(personhogStoreShadowErrorsCounter.labels).not.toHaveBeenCalled()+ expect(personhogStoreShadowCompareFailedCounter.labels).not.toHaveBeenCalled()+ })++ it('counts a comparator fault as its own, never as the backend failing', async () => {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '1'))+ // A person-shaped answer whose properties getter throws: the+ // comparison cannot complete, but the backend answered fine.+ stores.personhogMock.fetchForUpdate.mockResolvedValue({+ ...person(1, '1'),+ get properties(): never {+ throw new Error('exploding properties')+ },+ } as never)+ const store = makeStore(stores, 'shadow')++ await expect(store.fetchForUpdate(1, 'd1', 0)).resolves.toEqual(person(1, '1'))++ expect(personhogStoreShadowCompareFailedCounter.labels).toHaveBeenCalledWith({ verb: 'fetchForUpdate' })+ expect(personhogStoreShadowErrorsCounter.labels).not.toHaveBeenCalled()+ })+ })+it('rejects an unknown mode at parse time', () => {expect(() => parsePersonsStoreMode('both')).toThrow('PERSONS_STORE_MODE')expect(parsePersonsStoreMode('shadow')).toBe('shadow')@@ -156,7 +529,39 @@ describe('RoutingPersonsStore', () => {const result = await store.fetchForUpdate(1, 'a', 0)expect(result?.id).toBe('7')- expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'fetchForUpdate' })+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb: 'fetchForUpdate',+ error: 'Error',+ })+ })++ it('a shadow verb that outruns its ceiling is abandoned, not waited out', async () => {+ // The shadow leg is awaited, so an unbounded one spends the+ // consumer's poll budget and costs the group its membership.+ jest.useFakeTimers()+ try {+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '7'))+ stores.personhogMock.fetchForUpdate.mockReturnValue(new Promise(() => {}))+ const store = makeStore(stores, 'shadow')++ const pending = store.fetchForUpdate(1, 'a', 0)+ let settled = false+ void pending.then(() => (settled = true))+ await Promise.resolve()+ expect(settled).toBe(false)++ jest.advanceTimersByTime(60_000)+ const result = await pending++ expect(result?.id).toBe('7')+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb: 'fetchForUpdate',+ error: 'ShadowVerbTimeoutError',+ })+ } finally {+ jest.useRealTimers()+ }})it('a shadow flush failure is swallowed', async () => {@@ -166,6 +571,61 @@ describe('RoutingPersonsStore', () => {await expect(store.flush()).resolves.toEqual([])})+ it('the shadow leg completes before the routed call returns', async () => {+ // The swallow-and-count tests observe failures synchronously, so+ // a shadow leg degraded to fire-and-forget would pass them as+ // timing flakes rather than failing red. This pins the await:+ // the routed call must not return while the shadow is running.+ const stores = makeStores()+ stores.pg.fetchForUpdate.mockResolvedValue(person(1, '7'))+ let shadowDone = false+ stores.personhogMock.fetchForUpdate.mockImplementation(async () => {+ await new Promise((resolve) => setImmediate(resolve))+ shadowDone = true+ return null+ })+ const store = makeStore(stores, 'shadow')++ await store.fetchForUpdate(1, 'a', 0)++ expect(shadowDone).toBe(true)+ })++ it('shadow createPerson hands both backends the same uuid and answers pg', async () => {+ // Creation is the one write where the caller supplies identity;+ // both backends must receive it unchanged or the shadow's rows+ // diverge on the key downstream data is joined by.+ const stores = makeStores()+ const pgResult = { success: true as const, person: person(1, '7'), messages: [], created: true }+ stores.pg.createPerson.mockResolvedValue(pgResult as never)+ stores.personhogMock.createPerson.mockResolvedValue({+ success: true,+ person: person(1, '99'),+ messages: [],+ created: true,+ } as never)+ const store = makeStore(stores, 'shadow')++ const result = await store.createPerson(+ DateTime.fromMillis(3_600_000, { zone: 'utc' }),+ {},+ {},+ {},+ 1,+ null,+ false,+ 'caller-supplied-uuid',+ { distinctId: 'd1' },+ undefined,+ undefined,+ 0+ )++ expect(result).toBe(pgResult)+ expect(stores.pg.createPerson.mock.calls[0][7]).toBe('caller-supplied-uuid')+ expect(stores.personhogMock.createPerson.mock.calls[0][7]).toBe('caller-supplied-uuid')+ })+it('mergePersons replays the same request against the personhog backend, pg staying authoritative', async () => {const stores = makeStores()const pgResult = { survivor: person(1, '7'), results: [] }@@ -186,7 +646,10 @@ describe('RoutingPersonsStore', () => {const store = makeStore(stores, 'shadow')await expect(store.mergePersons({} as never, 0)).resolves.toEqual(emptyMergeResult())- expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'mergePersons' })+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({+ verb: 'mergePersons',+ error: 'Error',+ })})it('prefetch warms both worlds', async () => {@@ -223,7 +686,7 @@ describe('RoutingPersonsStore', () => {store.updatePersonWithPropertiesDiffForUpdate(person(1, '7'), { a: '1' }, [], {}, 'd1', 0),(m: jest.Mocked<PersonsStore>) => m.updatePersonWithPropertiesDiffForUpdate,],- ] as const)('%s ships the shadow backend id, not the pg id', async (_verb, call, member) => {+ ] as const)('%s writes the shadow backend id, not the pg id', async (_verb, call, member) => {const stores = makeStores()stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])stores.pg.updatePersonWithPropertiesDiffForUpdate.mockResolvedValue([person(1, '7'), [], true])@@ -261,11 +724,24 @@ describe('RoutingPersonsStore', () => {expect(stores.personhogMock.shutdown).toHaveBeenCalled()})- it('releaseBatch releases both worlds', () => {+ it('a shadow release abandons the personhog batch rather than keeping it', () => {+ // A shadow flush failure already acked the batch on the pg side, so+ // a plain release would retain the unwritten lanes forever; hours+ // of identity outage would grow them without bound inside the+ // authoritative process.const stores = makeStores()const store = makeStore(stores, 'shadow')store.releaseBatch(4)expect(stores.pg.releaseBatch).toHaveBeenCalledWith(4)+ expect(stores.personhogMock.abandonBatch).toHaveBeenCalledWith(4)+ expect(stores.personhogMock.releaseBatch).not.toHaveBeenCalled()+ })++ it('a personhog-mode release keeps unwritten lanes for the next flush', () => {+ const stores = makeStores()+ const store = makeStore(stores, 'personhog')+ store.releaseBatch(4)expect(stores.personhogMock.releaseBatch).toHaveBeenCalledWith(4)+ expect(stores.personhogMock.abandonBatch).not.toHaveBeenCalled()})})diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.tsindex 77ecb4b5265f..befaa6962393 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts@@ -1,6 +1,14 @@import { DateTime } from 'luxon'-import { personhogStoreShadowErrorsCounter, personhogStoreShadowSkipsCounter } from '~/common/persons/metrics'+import { errorClassLabel } from '~/common/personhog/metrics'+import {+ personhogStoreShadowCompareFailedCounter,+ personhogStoreShadowComparedCounter,+ personhogStoreShadowDivergenceCounter,+ personhogStoreShadowErrorsCounter,+ personhogStoreShadowFoldRedriveCounter,+ personhogStoreShadowSkipsCounter,+} from '~/common/persons/metrics'import { PersonMessage } from '~/common/persons/person-message'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'import { CreatePersonResult } from '~/common/utils/db/db'@@ -24,9 +32,8 @@ export function parsePersonsStoreMode(raw: string): PersonsStoreMode {}/**- * Fails startup when a non-pg mode is missing the endpoints it dials,- * so a misconfiguration is one loud boot error instead of every write- * failing at its first RPC.+ * Fails startup when a non-pg mode is missing the endpoints it dials:+ * one loud boot error instead of every write failing.*/export function assertPersonsStoreModeConfig(mode: PersonsStoreMode,@@ -44,6 +51,73 @@ export function assertPersonsStoreModeConfig(}}+/**+ * Whether two property maps say the same thing, compared by value so a+ * rebuilt nested object does not read as a difference.+ */+function propertiesMatch(left: Properties, right: Properties): boolean {+ const leftKeys = Object.keys(left ?? {})+ const rightKeys = Object.keys(right ?? {})+ if (leftKeys.length !== rightKeys.length) {+ return false+ }+ return leftKeys.every((key) => key in (right ?? {}) && stableEqual(left[key], right[key]))+}++/**+ * Key-order-insensitive equality, because Postgres jsonb reorders object+ * keys while personhog answers in write order. Array order stays+ * significant because it is significant to the customer's data.+ */+function stableEqual(left: unknown, right: unknown): boolean {+ if (left === right) {+ return true+ }+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((entry, index) => stableEqual(entry, right[index]))+ )+ }+ if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {+ return false+ }+ const leftKeys = Object.keys(left)+ const rightKeys = Object.keys(right)+ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every(+ (key) =>+ Object.prototype.hasOwnProperty.call(right, key) &&+ stableEqual((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key])+ )+ )+}++/** The property names that differ, for a log that must not carry their values. */+function differingKeys(left: Properties, right: Properties): string[] {+ const names = new Set([...Object.keys(left ?? {}), ...Object.keys(right ?? {})])+ return [...names].filter((key) => !stableEqual((left ?? {})[key], (right ?? {})[key])).sort()+}++/**+ * How long one shadow verb may run before the batch stops waiting on it.+ * Above the personhog merge deadline so a first attempt is never cut+ * short, and far enough under the consumer's poll interval that one+ * degraded verb cannot cost the group its membership.+ */+const SHADOW_VERB_TIMEOUT_MS = 60_000++/** Raised when a shadow verb outruns its ceiling and the batch abandons it. */+class ShadowVerbTimeoutError extends Error {+ constructor(verb: string) {+ super(`personhog shadow ${verb} exceeded ${SHADOW_VERB_TIMEOUT_MS}ms and was abandoned`)+ this.name = 'ShadowVerbTimeoutError'+ }+}+/*** Routes person-store verbs between the Postgres backend and the personhog* one. The mode applies to the whole deployment: personhog sends every@@ -53,7 +127,8 @@ export function assertPersonsStoreModeConfig(* `mergePersons` like any other verb: each backend runs its own whole* merge (the identity service's saga, or the Postgres store's own), so* shadow mode rehearses every merge, folds included, against the- * personhog backend's own graph.+ * personhog backend's own graph; a fold only the shadow aborted is+ * re-driven per pair.*/export class RoutingPersonsStore implements PersonsStore {constructor(@@ -69,15 +144,32 @@ export class RoutingPersonsStore implements PersonsStore {}/**- * Run the personhog side of a shadowed verb: sequential, awaited, and- * never allowed to fail the batch.+ * Runs the personhog side of a shadowed verb: sequential, awaited,+ * never allowed to fail the batch. Awaited means its wall clock spends+ * the consumer's poll budget, so a verb that outruns the ceiling is+ * abandoned and counted as lost fidelity; the bound is per verb.*/private async shadowed(verb: string, run: () => Promise<unknown>): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined+ const running = run()+ // The abandoned leg keeps running against the personhog side; its+ // settlement is swallowed here so a rejection arriving after the+ // ceiling cannot surface as an unhandled one.+ void running.catch(() => {})try {- await run()+ await Promise.race([+ running,+ new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => reject(new ShadowVerbTimeoutError(verb)), SHADOW_VERB_TIMEOUT_MS)+ }),+ ])} catch (error) {- personhogStoreShadowErrorsCounter.labels({ verb }).inc()+ // Labelled by class as well as verb: the failures a rollout+ // must tell apart read identically under one number.+ personhogStoreShadowErrorsCounter.labels({ verb, error: errorClassLabel(error) }).inc()logger.warn('personhog shadow verb failed', { verb, error: String(error) })+ } finally {+ clearTimeout(timer)}}@@ -90,23 +182,94 @@ export class RoutingPersonsStore implements PersonsStore {verb: string,pg: () => Promise<T>,personhog: () => Promise<T>,- opts?: { shadow?: () => Promise<unknown> }+ opts?: {+ shadow?: () => Promise<unknown>+ compare?: (authoritative: T, shadow: unknown) => void+ after?: (authoritative: T, shadow: unknown) => Promise<void>+ }): Promise<T> {if (this.mode === 'personhog') {return personhog()}const result = await pg()- await this.shadowed(verb, opts?.shadow ?? personhog)+ await this.shadowed(verb, async () => {+ const shadow = await (opts?.shadow ?? personhog)()+ this.compared(verb, () => opts?.compare?.(result, shadow))+ await opts?.after?.(result, shadow)+ })return result}/**- * Resolve the personhog backend's own person for a shadowed write. The- * caller holds the Postgres row, whose numeric id means nothing in- * the personhog backend — the two id sequences are independent — so a- * shadow write must re-resolve by distinct id and skip, counted,- * when the person does not exist there yet. The fetch memoizes per- * batch, so repeated writes to one person cost one resolution.+ * A comparator that throws is a bug in the comparator; counting it+ * among shadow failures would blame the thing under judgment.+ */+ private compared(verb: string, run: () => void): void {+ try {+ run()+ } catch (error) {+ personhogStoreShadowCompareFailedCounter.labels({ verb }).inc()+ logger.warn('personhog shadow comparison failed', { verb, error: String(error) })+ }+ }++ /**+ * Records whether the shadow backend answered the same person. Row ids+ * are not compared because the backends allocate independently; the+ * uuid is derived the same way on both.+ */+ private comparePerson(verb: string, authoritative: unknown, shadow: unknown): void {+ // Absence arrives as null from either backend, and as undefined from+ // a caller that answered nothing at all; both mean the same thing+ // here and neither may be dereferenced.+ const left = (authoritative ?? null) as InternalPerson | null+ const right = (shadow ?? null) as InternalPerson | null+ personhogStoreShadowComparedCounter.labels({ verb }).inc()+ if (left === null || right === null) {+ if (left !== right) {+ // Which side is empty is the whole question: personhog+ // missing a person fades; losing one never does.+ this.recordDivergence(verb, left === null ? 'missing_authoritative' : 'missing_shadow', {+ authoritative: left?.uuid ?? null,+ shadow: right?.uuid ?? null,+ })+ }+ return+ }+ if (left.uuid !== right.uuid) {+ this.recordDivergence(verb, 'uuid', { authoritative: left.uuid, shadow: right.uuid })+ }+ if (left.is_identified !== right.is_identified) {+ this.recordDivergence(verb, 'is_identified', {+ authoritative: left.is_identified,+ shadow: right.is_identified,+ })+ }+ if (!propertiesMatch(left.properties, right.properties)) {+ this.recordDivergence(verb, 'properties', {+ uuid: left.uuid,+ // Key names only. Values are customer data and this log is+ // not the place for it; the names are enough to find the+ // event that wrote them.+ differing: differingKeys(left.properties, right.properties),+ })+ }+ }++ private recordDivergence(verb: string, field: string, details: Record<string, unknown>): void {+ personhogStoreShadowDivergenceCounter.labels({ verb, field }).inc()+ logger.warn('personhog shadow answered differently from the authoritative backend', {+ verb,+ field,+ ...details,+ })+ }++ /**+ * The caller holds the Postgres row, whose numeric id means nothing+ * here (independent sequences), so a shadow write re-resolves by+ * distinct id and skips, counted, when the person does not exist yet.+ * Memoized per batch.*/private async withShadowPerson(verb: string,@@ -131,7 +294,8 @@ export class RoutingPersonsStore implements PersonsStore {return this.route('fetchForChecking',() => this.pg.fetchForChecking(teamId, distinctId, batchId),- () => this.personhog.fetchForChecking(teamId, distinctId, batchId)+ () => this.personhog.fetchForChecking(teamId, distinctId, batchId),+ { compare: (authoritative, shadow) => this.comparePerson('fetchForChecking', authoritative, shadow) })}@@ -139,7 +303,8 @@ export class RoutingPersonsStore implements PersonsStore {return this.route('fetchForUpdate',() => this.pg.fetchForUpdate(teamId, distinctId, batchId),- () => this.personhog.fetchForUpdate(teamId, distinctId, batchId)+ () => this.personhog.fetchForUpdate(teamId, distinctId, batchId),+ { compare: (authoritative, shadow) => this.comparePerson('fetchForUpdate', authoritative, shadow) })}@@ -268,19 +433,129 @@ export class RoutingPersonsStore implements PersonsStore {}/**- * Merges are distinct-id addressed, so the personhog side needs no- * person re-resolution: the same request replays the whole merge- * against that backend's saga, keeping the shadow graph's topology in- * step with the Postgres one.+ * Merges are distinct-id addressed, so no re-resolution: the same+ * request replays the whole merge against this backend's own graph.*/mergePersons(request: MergePersonsRequest, batchId: number): Promise<MergePersonsResult> {return this.route('mergePersons',() => this.pg.mergePersons(request, batchId),- () => this.personhog.mergePersons(request, batchId)+ () => this.personhog.mergePersons(request, batchId),+ {+ compare: (authoritative, shadow) => this.compareMerge(authoritative, shadow),+ after: (authoritative, shadow) => this.redriveShadowFoldPairs(request, batchId, authoritative, shadow),+ })}+ /**+ * A fold only the shadow aborted gets its pairs re-driven, single+ * shot, as the fallback merges the service cannot issue (it sees only+ * the executed authoritative result). Per-pair op ids let the pair's+ * own event attach on redelivery; ops stay empty because plan events+ * route theirs through the shadowed update path regardless.+ */+ private async redriveShadowFoldPairs(+ request: MergePersonsRequest,+ batchId: number,+ authoritative: MergePersonsResult,+ shadow: unknown+ ): Promise<void> {+ const shadowResult = shadow as MergePersonsResult+ if (authoritative.foldAborted !== undefined || shadowResult?.foldAborted === undefined) {+ return+ }+ for (const source of request.sources) {+ try {+ const result = await this.personhog.mergePersons(+ {+ teamId: request.teamId,+ targetDistinctId: request.targetDistinctId,+ sources: [source],+ eventUuid: source.eventUuid,+ eventOps: {+ set: {},+ setOnce: {},+ unset: [],+ denied: false,+ shouldForceUpdate: false,+ eventName: request.eventOps.eventName,+ },+ allowIdentifiedSources: request.allowIdentifiedSources,+ mergeMode: request.mergeMode,+ createdAtMs: request.createdAtMs,+ },+ batchId+ )+ const outcome = result.results[0]?.outcome ?? 'error'+ personhogStoreShadowFoldRedriveCounter.labels({ outcome }).inc()+ if (outcome !== 'merged' && outcome !== 'attached' && outcome !== 'noop_same_person') {+ // Named so a row comparison can exclude exactly these+ // pairs; the pair's next event re-attempts organically.+ logger.warn('shadow fold re-drive left the pair unmerged', {+ team_id: request.teamId,+ source_distinct_id: source.distinctId,+ target_distinct_id: request.targetDistinctId,+ outcome,+ })+ }+ } catch (error) {+ personhogStoreShadowFoldRedriveCounter.labels({ outcome: errorClassLabel(error) }).inc()+ logger.warn('shadow fold re-drive left the pair unmerged', {+ team_id: request.teamId,+ source_distinct_id: source.distinctId,+ target_distinct_id: request.targetDistinctId,+ outcome: errorClassLabel(error),+ })+ }+ }+ }++ /**+ * The survivor decides where every later event lands, so a verdict+ * disagreement is the most consequential divergence; the vocabularies+ * differ between backends, so a difference is a finding, not an alarm.+ */+ private compareMerge(authoritative: unknown, shadow: unknown): void {+ const left = authoritative as MergePersonsResult+ const right = shadow as MergePersonsResult+ personhogStoreShadowComparedCounter.labels({ verb: 'mergePersons' }).inc()+ // An aborted fold carries no verdicts, so the disposition itself is+ // what the backends can disagree on: one record when only one side+ // aborted, nothing when both did.+ if (left.foldAborted || right.foldAborted) {+ const onlyOneAborted = (left.foldAborted === undefined) !== (right.foldAborted === undefined)+ if (onlyOneAborted) {+ this.recordDivergence('mergePersons', 'fold_disposition', {+ authoritative: left.foldAborted ?? 'executed',+ shadow: right.foldAborted ?? 'executed',+ })+ }+ return+ }+ if ((left.survivor?.uuid ?? null) !== (right.survivor?.uuid ?? null)) {+ this.recordDivergence('mergePersons', 'survivor', {+ authoritative: left.survivor?.uuid ?? null,+ shadow: right.survivor?.uuid ?? null,+ })+ }+ const shadowOutcomes = new Map(right.results.map((source) => [source.sourceDistinctId, source.outcome]))+ for (const source of left.results) {+ const other = shadowOutcomes.get(source.sourceDistinctId)+ if (other !== source.outcome) {+ this.recordDivergence('mergePersons', 'outcome', {+ authoritative: source.outcome,+ shadow: other ?? null,+ })+ }+ shadowOutcomes.delete(source.sourceDistinctId)+ }+ // A verdict for a source Postgres never reported is a divergence too.+ for (const [, outcome] of shadowOutcomes) {+ this.recordDivergence('mergePersons', 'outcome', { authoritative: null, shadow: outcome })+ }+ }+personPropertiesSize(personId: string, teamId: number): Promise<number> {return this.route('personPropertiesSize',@@ -320,14 +595,33 @@ export class RoutingPersonsStore implements PersonsStore {releaseBatch(batchId: number): void {this.pg.releaseBatch(batchId)- this.personhog.releaseBatch(batchId)+ if (this.mode === 'personhog') {+ this.personhog.releaseBatch(batchId)+ return+ }+ // Release runs in the pipeline's finally, where shadow must not+ // throw; the batch is already acked, so kept segments would+ // accumulate without bound through an outage.+ try {+ this.personhog.abandonBatch(batchId)+ } catch (error) {+ personhogStoreShadowErrorsCounter.labels({ verb: 'releaseBatch', error: errorClassLabel(error) }).inc()+ logger.warn('personhog shadow release failed', { batchId, error: String(error) })+ }}async shutdown(): Promise<void> {try {await this.pg.shutdown()} finally {- await this.personhog.shutdown()+ if (this.mode === 'personhog') {+ await this.personhog.shutdown()+ } else {+ // The store's unwritten-lanes rejection is the right alarm+ // only when it owns the data; a shadow-only fault must not+ // stop shutdown.+ await this.shadowed('shutdown', () => this.personhog.shutdown())+ }}}}diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 4a627aff6dc7..b1f8926279c1 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -168,6 +168,9 @@ export type IngestionConsumerConfig = {PERSON_MERGE_ASYNC_TOPIC: stringPERSON_MERGE_ASYNC_ENABLED: booleanPERSON_MERGE_SYNC_BATCH_SIZE: number+ // The saga's per-source move guard in SYNC mode; an over-limit source+ // comes back skipped_move_limit for the merge-mode policy.+ PERSONHOG_SYNC_MERGE_MOVE_LIMIT: number// Kill switch for emitting person_merge_events to the cohort-stream-processor.// Enable ordering: (1) create the topic, (2) set INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC// (startup topic verification is then fatal by design), (3) flip this on. Flipping this on before@@ -365,6 +368,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {PERSON_MERGE_ASYNC_TOPIC: '',PERSON_MERGE_ASYNC_ENABLED: false,PERSON_MERGE_SYNC_BATCH_SIZE: 0,+ PERSONHOG_SYNC_MERGE_MOVE_LIMIT: 10_000,PERSON_MERGE_EVENTS_ENABLED: false,PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 4cf7109c5c1f..a889955d4291 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -149,7 +149,12 @@ export class IngestionApiServer implements NodeServer {private cookielessManager?: CookielessManagerprivate pubsub?: PubSubprivate personsStore?: BatchWritingPersonsStore- private personhogStore?: PersonhogPersonsStore+ /**+ * The store the pipeline was handed. Shutdown goes through this so the+ * routing store's own lifecycle rules run: in shadow, a personhog+ * fault must not fail process cleanup.+ */+ private pipelinePersonsStore?: PersonsStoreprivate personhogClientClosers: Array<() => void> = []private groupStore?: BatchWritingGroupStore// Held so shutdown cleanup can produce ClickHouse messages returned by a@@ -367,24 +372,30 @@ export class IngestionApiServer implements NodeServer {writeMaxBytes: this.config.PERSONHOG_WRITE_MAX_BYTES,clientName: 'ingestion-persons-store',})- const identityClients = createIdentityClients({- addr: this.config.PERSONHOG_IDENTITY_ADDR,- useTls: this.config.PERSONHOG_TLS,- timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,- clientName: 'ingestion-persons-store',- })+ const identityClients = createIdentityClients(+ {+ addr: this.config.PERSONHOG_IDENTITY_ADDR,+ useTls: this.config.PERSONHOG_TLS,+ timeoutMs: this.config.PERSONHOG_TIMEOUT_MS,+ clientName: 'ingestion-persons-store',+ },+ { mergeTimeoutMs: this.config.PERSONHOG_MERGE_TIMEOUT_MS }+ )this.personhogClientClosers = [() => routerClient.close(), identityClients.close]const writeRepository = new PersonHogPersonWriteRepository(routerClient,identityClients.identity,'ingestion-persons-store')- this.personhogStore = new PersonhogPersonsStore(writeRepository, {+ const personhogStore = new PersonhogPersonsStore(writeRepository, {maxConcurrentUpdates: this.config.PERSONHOG_STORE_MAX_CONCURRENT_UPDATES,updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,+ syncMergeMoveLimit: this.config.PERSONHOG_SYNC_MERGE_MOVE_LIMIT,+ requestTimeoutMs: this.config.PERSONHOG_TIMEOUT_MS,})- personsStore = new RoutingPersonsStore(this.personsStore, this.personhogStore, personsStoreMode)+ personsStore = new RoutingPersonsStore(this.personsStore, personhogStore, personsStoreMode)}+ this.pipelinePersonsStore = personsStorethis.groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,@@ -529,10 +540,11 @@ export class IngestionApiServer implements NodeServer {// shutdown so shutdown() can assert a clean cache.if (this.personsStore) {await this.personsStore.flushAndProduceMessages()- await this.personsStore.shutdown()}- if (this.personhogStore) {- await this.personhogStore.shutdown()+ if (this.pipelinePersonsStore) {+ await this.pipelinePersonsStore.shutdown()+ } else if (this.personsStore) {+ await this.personsStore.shutdown()}this.personhogClientClosers.forEach((close) => close())if (this.groupStore) {diff --git a/nodejs/tests/helpers/mocks/producer.spy.ts b/nodejs/tests/helpers/mocks/producer.spy.tsindex 05965e8b58e8..01aee9d46e12 100644--- a/nodejs/tests/helpers/mocks/producer.spy.ts+++ b/nodejs/tests/helpers/mocks/producer.spy.ts@@ -34,10 +34,7 @@ const tryDecompress = (value: string | Buffer): string => {}export class KafkaProducerObserver {- public readonly produceSpy: jest.SpyInstance<- Promise<void>,- Parameters<typeof KafkaProducerWrapper.prototype.produce>- >+ public produceSpy: jest.SpyInstance<Promise<void>, Parameters<typeof KafkaProducerWrapper.prototype.produce>>constructor(private producer: KafkaProducerWrapper) {// Spy on the methods we need@@ -121,7 +118,13 @@ export class KafkaProducerObserver {return result}+ /**+ * Re-arms the observer for the next test. Reinstalls the spy rather than+ * clearing it, because `jest.restoreAllMocks()` in an `afterEach`+ * uninstalls it and an uninstalled spy passes every assertion vacuously.+ */public resetKafkaProducer() {- this.produceSpy.mockClear()+ this.produceSpy.mockRestore()+ this.produceSpy = jest.spyOn(this.producer, 'produce')}}diff --git a/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.tsnew file mode 100644index 000000000000..11e0499e7f63--- /dev/null+++ b/nodejs/tests/service-e2e/personhog-shadow-parity.serial.test.ts@@ -0,0 +1,675 @@+// Serial e2e: drives the Postgres and personhog person backends against real+// infrastructure and compares them through the routing store's own shadow+// machinery. The personhog half is the real stack (identity, leader-mode+// router, leader), not a model, so this catches contract drift a Jest mock+// cannot: proto encoding, uuid derivation, the saga's verdict vocabulary,+// and the identity repointing a merge leaves behind.+//+// Requires the personhog services on top of the usual serial-test infra:+// `docker compose -f docker-compose.dev.yml --profile ingestion up`, or a+// `hogli start` dev stack (the `personhog` capability). Addresses override+// via PERSONHOG_E2E_ROUTER_ADDR / PERSONHOG_E2E_IDENTITY_ADDR.+import { DateTime } from 'luxon'+import { isDeepStrictEqual } from 'node:util'+import { Pool } from 'pg'++import {+ KAFKA_INGESTION_WARNINGS,+ KAFKA_PERSON,+ KAFKA_PERSON_DISTINCT_ID,+ KAFKA_PERSON_MERGE_EVENTS,+} from '~/common/config/kafka-topics'+import { KafkaProducerWrapper } from '~/common/kafka/producer'+import {+ INGESTION_WARNINGS_OUTPUT,+ PERSONS_OUTPUT,+ PERSON_DISTINCT_IDS_OUTPUT,+ PERSON_MERGE_EVENTS_OUTPUT,+} from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'+import { PersonHogClient } from '~/common/personhog/client'+import { createIdentityClients } from '~/common/personhog/identity-clients'+import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'+import {+ personhogStoreShadowComparedCounter,+ personhogStoreShadowDivergenceCounter,+ personhogStoreShadowErrorsCounter,+} from '~/common/persons/metrics'+import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'+import { closeHub, createHub } from '~/common/utils/db/hub'+import { PostgresUse } from '~/common/utils/db/postgres'+import { UUIDT } from '~/common/utils/utils'+import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'+import { PersonOutputs } from '~/ingestion/common/persons/person-context'+import { MergeMode, createDefaultSyncMergeMode } from '~/ingestion/common/persons/person-merge-types'+import { extractEventOps } from '~/ingestion/common/persons/person-update'+import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'+import { PersonhogPersonsStore } from '~/ingestion/common/persons/personhog-persons-store'+import { MergePersonsRequest, MergePersonsResult } from '~/ingestion/common/persons/persons-store'+import { RoutingPersonsStore } from '~/ingestion/common/persons/routing-persons-store'+import { Hub } from '~/types'++import { createOrganization, createTeam } from '../helpers/sql'++jest.setTimeout(60000)++const ROUTER_ADDR = process.env.PERSONHOG_E2E_ROUTER_ADDR ?? '127.0.0.1:50054'+const IDENTITY_ADDR = process.env.PERSONHOG_E2E_IDENTITY_ADDR ?? '127.0.0.1:50055'+// Where the personhog services keep their validation tables; the writer+// applies the leader's changelog here. The compose services default to+// the `posthog` database, so a compose-launched stack needs+// POSTHOG_PERSONS_DB_NAME=posthog_persons exported (hogli sets it).+const PERSONS_DATABASE_URL =+ process.env.PERSONHOG_E2E_PERSONS_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/posthog_persons'++const counterTotal = async (counter: { get: () => Promise<{ values: { value: number }[] }> }): Promise<number> =>+ (await counter.get()).values.reduce((sum, entry) => sum + entry.value, 0)++describe('personhog shadow parity (e2e)', () => {+ let hub: Hub+ let kafkaProducer: KafkaProducerWrapper+ let routerClient: PersonHogClient+ let closeIdentity: () => void+ let personhogStore: PersonhogPersonsStore+ let pgStore: BatchWritingPersonsStore+ let routing: RoutingPersonsStore+ let personsDb: Pool = undefined as unknown as Pool+ let organizationId: string+ let teamId: number+ let batchId = 0++ // Distinct ids are unique per run: the personhog side writes shared+ // dev tables, so a fixed id would meet a person a previous run made.+ const runTag = new UUIDT().toString().slice(0, 13)+ const id = (name: string) => `e2e-${runTag}-${name}`++ const outputs = (): PersonOutputs =>+ new IngestionOutputs({+ [PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, kafkaProducer, 'test'),+ [PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(+ PERSON_DISTINCT_IDS_OUTPUT,+ KAFKA_PERSON_DISTINCT_ID,+ kafkaProducer,+ 'test'+ ),+ [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(+ INGESTION_WARNINGS_OUTPUT,+ KAFKA_INGESTION_WARNINGS,+ kafkaProducer,+ 'test'+ ),+ [PERSON_MERGE_EVENTS_OUTPUT]: new SingleIngestionOutput(+ PERSON_MERGE_EVENTS_OUTPUT,+ KAFKA_PERSON_MERGE_EVENTS,+ kafkaProducer,+ 'test'+ ),+ })++ const ops = (properties: Record<string, unknown>, event = '$set') =>+ extractEventOps({+ event,+ distinct_id: 'e2e',+ properties,+ team_id: teamId,+ uuid: new UUIDT().toString(),+ ip: null,+ now: new Date().toISOString(),+ site_url: '',+ } as any)++ const createThroughBoth = async (+ distinctId: string,+ properties: Record<string, unknown>,+ batch: number,+ extraDistinctIds?: string[],+ isIdentified = false+ ) => {+ const result = await routing.createPerson(+ DateTime.utc(),+ properties,+ {},+ {},+ teamId,+ null,+ isIdentified,+ uuidFromDistinctId(teamId, distinctId),+ { distinctId },+ extraDistinctIds?.map((extra) => ({ distinctId: extra })),+ undefined,+ batch+ )+ if (!result.success) {+ throw new Error('creation failed')+ }+ return result.person+ }++ /** One merge through both backends, with the ack awaited. */+ const runMerge = async (+ targetDistinctId: string,+ sourceDistinctIds: string[],+ opts: {+ allowIdentifiedSources?: boolean+ mergeMode?: MergeMode+ eventUuid?: string+ sourceEventUuids?: string[]+ set?: Record<string, unknown>+ } = {}+ ) => {+ const mergeOps = ops({ $set: opts.set ?? {} }, '$identify')+ // The processor marks the caller identified on every merge-shaped+ // event and applies it on the follow-up update; the saga stamps the+ // survivor itself, so without this the Postgres row lags behind.+ mergeOps.isIdentified = true+ const result = await routing.mergePersons(+ {+ teamId,+ targetDistinctId,+ sources: sourceDistinctIds.map((distinctId, i) => ({+ distinctId,+ eventUuid: opts.sourceEventUuids?.[i] ?? new UUIDT().toString(),+ })),+ eventOps: mergeOps,+ eventUuid: opts.eventUuid ?? new UUIDT().toString(),+ allowIdentifiedSources: opts.allowIdentifiedSources ?? false,+ mergeMode: opts.mergeMode ?? createDefaultSyncMergeMode(),+ createdAtMs: Date.now(),+ },+ batchId+ )+ await result.kafkaAck+ return { result, mergeOps }+ }++ /**+ * The follow-up property update the processor runs after a merge:+ * Postgres leaves the event ops to it, the saga already applied them,+ * and the idempotent re-fold converges the two.+ */+ const applyMergeFollowUp = async (+ result: MergePersonsResult,+ mergeOps: ReturnType<typeof ops>,+ targetDistinctId: string+ ) => {+ if ((result.survivorNeedsUpdate ?? true) && result.survivor) {+ await routing.applyEventOps(result.survivor, mergeOps, targetDistinctId, batchId)+ }+ }++ const divergences = () => counterTotal(personhogStoreShadowDivergenceCounter)+ const shadowErrors = () => counterTotal(personhogStoreShadowErrorsCounter)+ const divergencesByField = async (field: string): Promise<number> =>+ (await personhogStoreShadowDivergenceCounter.get()).values+ .filter((entry) => entry.labels.field === field)+ .reduce((sum, entry) => sum + entry.value, 0)++ interface DurableRow {+ uuid: string+ properties: Record<string, unknown>+ is_identified: boolean+ created_at: string+ }++ const mainRowByDistinctId = async (distinctId: string): Promise<DurableRow | null> => {+ const { rows } = await hub.postgres.query<DurableRow>(+ PostgresUse.PERSONS_WRITE,+ `SELECT p.uuid, p.properties, p.is_identified,+ (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at+ FROM posthog_persondistinctid d+ JOIN posthog_person p ON p.id = d.person_id+ WHERE d.team_id = $1 AND d.distinct_id = $2`,+ [teamId, distinctId],+ 'personhog-shadow-parity-main-row'+ )+ return rows[0] ?? null+ }++ const tmpRowByDistinctId = async (distinctId: string): Promise<DurableRow | null> => {+ const { rows } = await personsDb.query<DurableRow>(+ `SELECT p.uuid, p.properties, p.is_identified,+ (extract(epoch from p.created_at) * 1000)::bigint::text AS created_at+ FROM personhog_persondistinctid_tmp d+ JOIN personhog_person_tmp p ON p.id = d.person_id AND p.team_id = d.team_id+ WHERE d.team_id = $1 AND d.distinct_id = $2+ AND d.is_deleted = false AND p.is_deleted = false`,+ [teamId, distinctId]+ )+ return rows[0] ?? null+ }++ /**+ * Asserts the durable rows behind one distinct id agree between the+ * main tables (the Postgres backend's writes) and the personhog+ * validation tables (identity's mappings plus the writer applying the+ * leader's changelog). The writer is asynchronous, so this polls until+ * the validation row converges or the deadline passes; the final+ * expectations then print whatever it last held.+ */+ const expectDurableRowParity = async (distinctId: string): Promise<void> => {+ const main = await mainRowByDistinctId(distinctId)+ expect(main).not.toBeNull()+ const deadline = Date.now() + 20_000+ let tmp: DurableRow | null = null+ for (;;) {+ tmp = await tmpRowByDistinctId(distinctId)+ if (+ tmp !== null &&+ tmp.uuid === main!.uuid &&+ tmp.is_identified === main!.is_identified &&+ tmp.created_at === main!.created_at &&+ isDeepStrictEqual(tmp.properties, main!.properties)+ ) {+ break+ }+ if (Date.now() > deadline) {+ break+ }+ await new Promise((resolve) => setTimeout(resolve, 250))+ }+ expect(tmp).not.toBeNull()+ expect(tmp!.uuid).toBe(main!.uuid)+ expect(tmp!.is_identified).toBe(main!.is_identified)+ expect(tmp!.created_at).toBe(main!.created_at)+ expect(tmp!.properties).toEqual(main!.properties)+ }++ beforeAll(async () => {+ hub = await createHub({})+ kafkaProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ routerClient = PersonHogClient.fromConfig({+ addr: ROUTER_ADDR,+ clientName: 'personhog-shadow-parity-e2e',+ timeoutMs: 10_000,+ })+ const identityClients = createIdentityClients(+ { addr: IDENTITY_ADDR, clientName: 'personhog-shadow-parity-e2e', timeoutMs: 10_000 },+ { mergeTimeoutMs: 35_000 }+ )+ closeIdentity = identityClients.close+ const writeRepository = new PersonHogPersonWriteRepository(+ routerClient,+ identityClients.identity,+ 'personhog-shadow-parity-e2e'+ )+ try {+ await writeRepository.resolvePersonsByDistinctIds([{ teamId: 1, distinctId: id('ping') }], 'e2e-ping')+ } catch (error) {+ throw new Error(+ `personhog stack not reachable (router ${ROUTER_ADDR}, identity ${IDENTITY_ADDR}); ` ++ `start it with \`docker compose -f docker-compose.dev.yml --profile ingestion up\` ` ++ `or a hogli dev stack. Cause: ${error instanceof Error ? error.message : String(error)}`+ )+ }+ personhogStore = new PersonhogPersonsStore(writeRepository, {+ maxConcurrentUpdates: 10,+ updateAllProperties: false,+ syncMergeMoveLimit: 10_000,+ })+ pgStore = new BatchWritingPersonsStore(new PostgresPersonRepository(hub.postgres), outputs(), {+ metricEmissionIntervalMs: 0,+ })+ routing = new RoutingPersonsStore(pgStore, personhogStore, 'shadow')+ personsDb = new Pool({ connectionString: PERSONS_DATABASE_URL, max: 2 })+ organizationId = await createOrganization(hub.postgres)+ teamId = await createTeam(hub.postgres, organizationId)+ })++ afterAll(async () => {+ routerClient?.close()+ closeIdentity?.()+ await personsDb?.end()+ await kafkaProducer?.disconnect()+ if (hub) {+ await closeHub(hub)+ }+ })++ beforeEach(() => {+ batchId += 1+ personhogStoreShadowDivergenceCounter.reset()+ personhogStoreShadowComparedCounter.reset()+ personhogStoreShadowErrorsCounter.reset()+ })++ afterEach(() => {+ routing.releaseBatch(batchId)+ })++ it('creation and updates read back identically through both backends', async () => {+ const distinctId = id('reader')+ await createThroughBoth(distinctId, { plan: 'free' }, batchId)+ const person = await routing.fetchForUpdate(teamId, distinctId, batchId)+ expect(person).not.toBeNull()+ const [afterSet] = await routing.applyEventOps(+ person!,+ ops({ $set: { plan: 'pro', level: 3 } }),+ distinctId,+ batchId+ )+ // $set_once must not beat the standing value and $unset must land:+ // Postgres refines these client-side, the leader server-side, and+ // this is where the two refinements could drift. Chained on the+ // returned person, as the processor chains events: Postgres refines+ // against the caller's snapshot, so a stale one hides the unset.+ await routing.applyEventOps(+ afterSet,+ ops({ $set_once: { plan: 'ignored', fresh: 'kept' }, $unset: ['level'] }),+ distinctId,+ batchId+ )+ await routing.flush()+ routing.releaseBatch(batchId)++ // The durable rows first: waiting for the writer here also makes the+ // checking read below deterministic, since the identity resolve+ // serves writer-applied state.+ await expectDurableRowParity(distinctId)++ // A fresh batch, so both sides read their backend rather than a+ // cached answer; the shadow comparison is the assertion surface.+ // The checking read exercises the other personhog read path, the+ // identity resolve without a leader hop.+ batchId += 1+ const checked = await routing.fetchForChecking(teamId, distinctId, batchId)+ expect(checked?.uuid).toBe(uuidFromDistinctId(teamId, distinctId))+ const reread = await routing.fetchForUpdate(teamId, distinctId, batchId)++ expect(reread?.uuid).toBe(uuidFromDistinctId(teamId, distinctId))+ expect(reread?.properties).toEqual({ plan: 'pro', fresh: 'kept' })+ expect(await counterTotal(personhogStoreShadowComparedCounter)).toBeGreaterThan(0)+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it('a merge of two unseen ids births the person with both, identically', async () => {+ const target = id('birth-target')+ const source = id('birth-source')+ const { result, mergeOps } = await runMerge(target, [source], { set: { born: 'yes' } })++ expect(result.results[0]?.outcome).toBe('attached')+ expect(result.survivor?.uuid).toBe(uuidFromDistinctId(teamId, target))+ await applyMergeFollowUp(result, mergeOps, target)+ await routing.flush()+ routing.releaseBatch(batchId)+ await expectDurableRowParity(target)+ await expectDurableRowParity(source)++ batchId += 1+ const viaSource = await routing.fetchForUpdate(teamId, source, batchId)+ expect(viaSource?.uuid).toBe(uuidFromDistinctId(teamId, target))+ expect(viaSource?.properties).toMatchObject({ born: 'yes' })+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it('an unseen target attaches to the one existing person, with the verdict-name divergence pinned', async () => {+ const source = id('attach-source')+ const target = id('attach-target')+ await createThroughBoth(source, { origin: 'source' }, batchId)++ const { result, mergeOps } = await runMerge(target, [source])++ // The existing person keeps surviving on both backends and only its+ // id set grows, but the verdict names differ by design: the saga+ // establishes the unresolved target first, so by execution both ids+ // share one person and it answers noop_same_person where Postgres's+ // one-exists branch says attached.+ expect(result.results[0]?.outcome).toBe('attached')+ expect(result.survivor?.uuid).toBe(uuidFromDistinctId(teamId, source))+ expect(await divergencesByField('outcome')).toBe(1)+ expect(await divergencesByField('survivor')).toBe(0)+ await applyMergeFollowUp(result, mergeOps, target)+ await routing.flush()+ routing.releaseBatch(batchId)+ await expectDurableRowParity(source)+ await expectDurableRowParity(target)++ batchId += 1+ const viaTarget = await routing.fetchForUpdate(teamId, target, batchId)+ expect(viaTarget?.uuid).toBe(uuidFromDistinctId(teamId, source))+ expect(await shadowErrors()).toBe(0)+ })++ it('a merge of two ids already on one person answers noop identically', async () => {+ const target = id('same-target')+ const source = id('same-source')+ await createThroughBoth(target, {}, batchId, [source])++ const { result } = await runMerge(target, [source])++ expect(result.results[0]?.outcome).toBe('noop_same_person')+ expect(result.survivor?.uuid).toBe(uuidFromDistinctId(teamId, target))+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it.each([+ [false, 'skipped_already_identified'],+ [true, 'merged'],+ ])(+ 'an identified source with allowIdentifiedSources=%p answers %s on both backends',+ async (allowIdentifiedSources, expected) => {+ const target = id(`ident-${allowIdentifiedSources}-target`)+ const source = id(`ident-${allowIdentifiedSources}-source`)+ await createThroughBoth(target, {}, batchId)+ await createThroughBoth(source, {}, batchId, undefined, true)++ const { result, mergeOps } = await runMerge(target, [source], { allowIdentifiedSources })++ expect(result.results[0]?.outcome).toBe(expected)+ if (expected === 'merged') {+ await applyMergeFollowUp(result, mergeOps, target)+ await routing.flush()+ routing.releaseBatch(batchId)+ await expectDurableRowParity(target)+ await expectDurableRowParity(source)+ }+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ }+ )++ it('a two-source fold settles every verdict identically', async () => {+ const target = id('fold-target')+ const first = id('fold-first')+ const second = id('fold-second')+ await createThroughBoth(target, { origin: 'target' }, batchId)+ await createThroughBoth(first, { fromFirst: 'yes' }, batchId)+ await createThroughBoth(second, { fromSecond: 'yes' }, batchId)++ const { result, mergeOps } = await runMerge(target, [first, second], { set: { folded: 'yes' } })++ expect(result.foldAborted).toBeUndefined()+ expect(result.results.map((source) => source.outcome)).toEqual(['merged', 'merged'])+ expect(result.survivor?.uuid).toBe(uuidFromDistinctId(teamId, target))+ await applyMergeFollowUp(result, mergeOps, target)+ await routing.flush()+ routing.releaseBatch(batchId)+ await expectDurableRowParity(target)+ await expectDurableRowParity(first)+ await expectDurableRowParity(second)++ batchId += 1+ const viaFirst = await routing.fetchForUpdate(teamId, first, batchId)+ expect(viaFirst?.properties).toMatchObject({+ origin: 'target',+ fromFirst: 'yes',+ fromSecond: 'yes',+ folded: 'yes',+ })+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it('a replayed merge pins the one documented verdict divergence', async () => {+ const target = id('replay-target')+ const source = id('replay-source')+ await createThroughBoth(target, {}, batchId)+ await createThroughBoth(source, {}, batchId)+ const eventUuid = new UUIDT().toString()+ const sourceEventUuids = [new UUIDT().toString()]+ const { result: firstRun, mergeOps } = await runMerge(target, [source], { eventUuid, sourceEventUuids })+ expect(firstRun.results[0]?.outcome).toBe('merged')+ await applyMergeFollowUp(firstRun, mergeOps, target)+ await routing.flush()+ routing.releaseBatch(batchId)++ personhogStoreShadowDivergenceCounter.reset()+ batchId += 1+ // A redelivery of the same event: Postgres re-runs against moved+ // rows and lands on noop_same_person; the saga replays the recorded+ // 'merged' verdict per op id. Same survivor, different verdict+ // name — the one divergence this shape is allowed.+ const { result: replay } = await runMerge(target, [source], { eventUuid, sourceEventUuids })++ expect(replay.results[0]?.outcome).toBe('noop_same_person')+ expect(replay.survivor?.uuid).toBe(uuidFromDistinctId(teamId, target))+ expect(await divergencesByField('outcome')).toBe(1)+ expect(await divergencesByField('survivor')).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it('an over-limit source skips the merge in LIMIT mode, with the survivor divergence pinned', async () => {+ const target = id('limit-target')+ const source = id('limit-source')+ await createThroughBoth(target, {}, batchId)+ await createThroughBoth(source, {}, batchId, [id('limit-source-extra')])++ const { result } = await runMerge(target, [source], { mergeMode: { type: 'LIMIT', limit: 1 } })++ // Both backends skip on the same verdict; only the survivor field+ // differs by design — Postgres answers none on the skip, the saga+ // answers the target it resolved. The service maps the verdict to+ // an error either way, so nothing reads the survivor.+ expect(result.results[0]?.outcome).toBe('skipped_move_limit')+ expect(await divergencesByField('outcome')).toBe(0)+ expect(await divergencesByField('survivor')).toBe(1)+ expect(await shadowErrors()).toBe(0)+ })++ it('a single-source merge settles the same survivor and verdict on both backends', async () => {+ const target = id('merge-target')+ const source = id('merge-source')+ await createThroughBoth(target, { origin: 'target' }, batchId)+ await createThroughBoth(source, { origin: 'source' }, batchId)++ const request: MergePersonsRequest = {+ teamId,+ targetDistinctId: target,+ sources: [{ distinctId: source, eventUuid: new UUIDT().toString() }],+ eventOps: ops({ $set: { merged: 'yes' } }, '$identify'),+ eventUuid: new UUIDT().toString(),+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: Date.now(),+ }+ const result = await routing.mergePersons(request, batchId)+ await result.kafkaAck++ expect(result.survivor?.uuid).toBe(uuidFromDistinctId(teamId, target))+ expect(result.results[0]?.outcome).toBe('merged')+ // compareMerge checked the shadow's survivor uuid and per-source+ // verdict against these; a saga whose vocabulary or op-id handling+ // drifted from the client mapping lands here as a divergence.+ expect(await counterTotal(personhogStoreShadowComparedCounter)).toBeGreaterThan(0)+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })++ it('updates and a merge interleaved in one batch settle identically', async () => {+ const target = id('weave-target')+ const source = id('weave-source')+ await createThroughBoth(target, { shared: 'target', origin: 'target' }, batchId)+ await createThroughBoth(source, { shared: 'source', extra: 'source' }, batchId)++ // A buffered update on the source before the merge: Postgres folds+ // it through its cache, personhog drains the lane to the leader+ // before the saga runs; either way it must reach the survivor with+ // source precedence, so `shared` still settles to the target's value.+ const sourcePerson = await routing.fetchForUpdate(teamId, source, batchId)+ await routing.applyEventOps(sourcePerson!, ops({ $set: { updated: 'pre-merge' } }), source, batchId)++ const mergeOps = ops({ $set: { mergedBy: 'event' } }, '$identify')+ const merged = await routing.mergePersons(+ {+ teamId,+ targetDistinctId: target,+ sources: [{ distinctId: source, eventUuid: new UUIDT().toString() }],+ eventOps: mergeOps,+ eventUuid: new UUIDT().toString(),+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: Date.now(),+ },+ batchId+ )+ await merged.kafkaAck+ expect(merged.results[0]?.outcome).toBe('merged')+ // The follow-up property update the processor runs after a merge:+ // Postgres leaves the event ops to it, the saga already applied+ // them, and the idempotent re-fold converges the two.+ if (merged.survivorNeedsUpdate ?? true) {+ await routing.applyEventOps(merged.survivor!, mergeOps, target, batchId)+ }++ // A post-merge update addressed by the merged-away id, still in the+ // same batch: both backends must land it on the survivor.+ const viaOldId = await routing.fetchForUpdate(teamId, source, batchId)+ expect(viaOldId?.uuid).toBe(uuidFromDistinctId(teamId, target))+ await routing.applyEventOps(viaOldId!, ops({ $set: { postMerge: 'yes' } }), source, batchId)++ await routing.flush()+ routing.releaseBatch(batchId)++ batchId += 1+ const finalState = await routing.fetchForUpdate(teamId, target, batchId)+ expect(finalState?.properties).toMatchObject({+ shared: 'target',+ origin: 'target',+ extra: 'source',+ updated: 'pre-merge',+ mergedBy: 'event',+ postMerge: 'yes',+ })+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ // The durable rows behind both ids: the main tables against the+ // validation tables the identity service and the writer maintain.+ await expectDurableRowParity(target)+ await expectDurableRowParity(source)+ })++ it('a merged-away id reads the survivor on both backends', async () => {+ const target = id('heal-target')+ const source = id('heal-source')+ await createThroughBoth(target, {}, batchId)+ await createThroughBoth(source, {}, batchId)+ const merged = await routing.mergePersons(+ {+ teamId,+ targetDistinctId: target,+ sources: [{ distinctId: source, eventUuid: new UUIDT().toString() }],+ eventOps: ops({}, '$identify'),+ eventUuid: new UUIDT().toString(),+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: Date.now(),+ },+ batchId+ )+ await merged.kafkaAck+ routing.releaseBatch(batchId)++ // The purge dropped the personhog side's cache for both ids, so this+ // read re-resolves through the real identity service, whose mappings+ // the saga repointed; Postgres reads its own moved rows.+ batchId += 1+ const viaSource = await routing.fetchForUpdate(teamId, source, batchId)++ expect(viaSource?.uuid).toBe(uuidFromDistinctId(teamId, target))+ expect(await divergences()).toBe(0)+ expect(await shadowErrors()).toBe(0)+ })+})diff --git a/rust/.gitignore b/rust/.gitignoreindex ea8c4bf7f35f..8580ac69c8ca 100644--- a/rust/.gitignore+++ b/rust/.gitignore@@ -1 +1,2 @@/target+proto/