: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): extend the merge protocol for ingestion callers (#91105)
Zach Brown30a63043a3c7
diff --git a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.tsindex 590e19a430af..1528d1fe3c2c 100644--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts@@ -13,7 +13,7 @@ import { file_personhog_types_v1_person } from '../../types/v1/person_pb'export const file_personhog_identity_v1_identity: GenFile =/*@__PURE__*/fileDesc(- 'CiRwZXJzb25ob2cvaWRlbnRpdHkvdjEvaWRlbnRpdHkucHJvdG8SFXBlcnNvbmhvZy5pZGVudGl0eS52MSLOAQoWR2V0T3JDcmVhdGVQZXJzb25FbnRyeRIPCgd0ZWFtX2lkGAEgASgDEhMKC2Rpc3RpbmN0X2lkGAIgASgJEhoKEmV4dHJhX2Rpc3RpbmN0X2lkcxgDIAMoCRISCgpldmVudF9uYW1lGAQgASgJEhYKDnNldF9wcm9wZXJ0aWVzGAUgASgMEhsKE3NldF9vbmNlX3Byb3BlcnRpZXMYBiABKAwSEgoKY3JlYXRlZF9hdBgHIAEoAxIVCg1pc19pZGVudGlmaWVkGAggASgIImQKJEdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVxdWVzdBI8CgVlbnRyeRgBIAEoCzItLnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRPckNyZWF0ZVBlcnNvbkVudHJ5ImQKJUdldE9yQ3JlYXRlUGVyc29uQnlEaXN0aW5jdElkUmVzcG9uc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cnNvbnNCeURpc3RpbmN0SWRzUmVzcG9uc2USiAEKF0dldFBlcnNvbnNCeURpc3RpbmN0SWRzEjUucGVyc29uaG9nLmlkZW50aXR5LnYxLkdldFBlcnNvbnNCeURpc3RpbmN0SWRzUmVxdWVzdBo2LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXRQZXJzb25zQnlEaXN0aW5jdElkc1Jlc3BvbnNlEosBChhHZXREaXN0aW5jdElkc0ZvclBlcnNvbnMSNi5wZXJzb25ob2cuaWRlbnRpdHkudjEuR2V0RGlzdGluY3RJZHNGb3JQZXJzb25zUmVxdWVzdBo3LnBlcnNvbmhvZy5pZGVudGl0eS52MS5HZXREaXN0aW5jdElkc0ZvclBlcnNvbnNSZXNwb25zZRJnCgxNZXJnZVBlcnNvbnMSKi5wZXJzb25ob2cuaWRlbnRpdHkudjEuTWVyZ2VQZXJzb25zUmVxdWVzdBorLnBlcnNvbmhvZy5pZGVudGl0eS52MS5NZXJnZVBlcnNvbnNSZXNwb25zZWIGcHJvdG8z',[file_personhog_types_v1_person])@@ -486,12 +486,22 @@ export type MergePersonsRequest = Message<'personhog.identity.v1.MergePersonsReqmoveLimit?: bigint/**- * Merge event created_at, epoch millis. Used as the survivor's- * created_at when it predates the current value.+ * Merge event created_at, epoch millis. Consulted only when the establish+ * path births a fresh person; a resolved survivor keeps the min of the+ * target's and the sealed sources' own values.** @generated from field: int64 created_at = 9;*/createdAt: bigint++ /**+ * The uuid of the event that asked for this merge; op_id derives from it+ * one-way, so it is not recoverable. Recorded as $creator_event_uuid on+ * a person the establish path births. Send the same value on every retry.+ *+ * @generated from field: string creator_event_uuid = 10;+ */+ creatorEventUuid: string}/**@@ -515,6 +525,23 @@ export type MergeSourceResult = Message<'personhog.identity.v1.MergeSourceResult* @generated from field: personhog.identity.v1.MergeSourceOutcome outcome = 2;*/outcome: MergeSourceOutcome++ /**+ * The destroyed source person; set only on MERGED, where the person is+ * permanently gone and safe to reconcile against without re-reading.+ *+ * @generated from field: optional int64 source_person_id = 3;+ */+ sourcePersonId?: bigint++ /**+ * Whether any retry can change this source's outcome. True acks the+ * event, false lets redelivery try again. Outcome names are warning+ * labels, never durability inputs, so unknown values stay handled.+ *+ * @generated from field: bool settled = 4;+ */+ settled: boolean}/**@@ -612,7 +639,8 @@ export enum MergeSourceOutcome {/*** Another live lifecycle operation holds this person (or the source- * resolved differently between classification and claim). Retryable.+ * resolved differently between classification and claim). Retryable+ * only while unsettled; settled means this op's answer is frozen.** @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_CONFLICT = 6;*/@@ -631,6 +659,15 @@ export enum MergeSourceOutcome {* @generated from enum value: MERGE_SOURCE_OUTCOME_ERROR = 8;*/ERROR = 8,++ /**+ * Definitively refused before anything was destroyed; every retry meets+ * the same refusal, so the caller settles the pair as lost. ERROR is a+ * completed operation whose source ended indeterminate.+ *+ * @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_REFUSED = 9;+ */+ SKIPPED_REFUSED = 9,}/**@@ -709,7 +746,8 @@ export const PersonHogIdentity: GenService<{}/*** Merge source persons into the target distinct id's person. The- * service resolves and classifies every pair: same-person pairs settle+ * service resolves and classifies every pair: unresolved sources attach+ * to the target with plain mapping inserts, same-person pairs settle* inline, distinct-person pairs run the durable merge saga (fence the* sources, fold their sealed documents into the target, repoint distinct* ids, tombstone the sources, produce death documents). An unresolveddiff --git a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.tsindex bde3b671f423..9b843884d10f 100644--- a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts@@ -13,7 +13,7 @@ import { file_personhog_types_v1_common } from './common_pb'export const file_personhog_types_v1_person: GenFile =/*@__PURE__*/fileDesc(- 'Ch9wZXJzb25ob2cvdHlwZXMvdjEvcGVyc29uLnByb3RvEhJwZXJzb25ob2cudHlwZXMudjEisgIKBlBlc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aG9nLnR5cGVzLnYxLlJlbGVhc2VPdXRjb21lEhsKDnNlYWxlZF92ZXJzaW9uGAYgASgDSACIAQESEgoKY3JlYXRlZF9hdBgHIAEoA0IRCg9fc2VhbGVkX3ZlcnNpb24iFgoUUmVsZWFzZUZlbmNlUmVzcG9uc2UiUwoUU2VhbGVkU291cmNlU25hcHNob3QSKgoGcGVyc29uGAEgASgLMhoucGVyc29uaG9nLnR5cGVzLnYxLlBlcnNvbhIPCgdvcmRpbmFsGAIgASgFIr0BChlGb2xkUGVyc29uRG9jdW1lbnRSZXF1ZXN0Eg8KB3RlYW1faWQYASABKAMSEQoJcGVyc29uX2lkGAIgASgDEkIKEHNlYWxlZF9zbmFwc2hvdHMYAyADKAsyKC5wZXJzb25ob2cudHlwZXMudjEuU2VhbGVkU291cmNlU25hcHNob3QSEQoJZXZlbnRfc2V0GAQgASgMEhYKDmV2ZW50X3NldF9vbmNlGAUgASgMEg0KBW9wX2lkGAYgASgJIkgKGkZvbGRQZXJzb25Eb2N1bWVudFJlc3BvbnNlEioKBnBlcnNvbhgBIAEoCzIaLnBlcnNvbmhvZy50eXBlcy52MS5QZXJzb24qbwoPTGlmZWN5Y2xlT3BUeXBlEiEKHUxJRkVDWUNMRV9PUF9UWVBFX1VOU1BFQ0lGSUVEEAASHAoYTElGRUNZQ0xFX09QX1RZUEVfREVMRVRFEAESGwoXTElGRUNZQ0xFX09QX1RZUEVfTUVSR0UQAiptCg5SZWxlYXNlT3V0Y29tZRIfChtSRUxFQVNFX09VVENPTUVfVU5TUEVDSUZJRUQQABIdChlSRUxFQVNFX09VVENPTUVfQ09NTUlUVEVEEAESGwoXUkVMRUFTRV9PVVRDT01FX0FCT1JURUQQAmIGcHJvdG8z',[file_personhog_types_v1_common])@@ -660,6 +660,15 @@ export type UpdatePersonPropertiesRequest = Message<'personhog.types.v1.UpdatePe* @generated from field: optional int64 last_seen_at = 8;*/lastSeenAt?: bigint++ /**+ * The event kind warrants a write regardless of which properties changed.+ * Computed by the caller from the event alone; when false, filtered-only+ * changes answer updated=false and write nothing.+ *+ * @generated from field: bool force_update = 9;+ */+ forceUpdate: boolean}/**diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyindex 26a49e2d4f14..1e4f2254b5d3 100644--- a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.py@@ -15,17 +15,17 @@ _sym_db = _symbol_database.Default()from ....personhog.types.v1 import common_pb2 as personhog_dot_types_dot_v1_dot_common__pb2DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(- b'\n\x1fpersonhog/types/v1/person.proto\x12\x12personhog.types.v1\x1a\x1fpersonhog/types/v1/common.proto"\xb2\x02\n\x06Person\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x12\x0f\n\x07team_id\x18\x03 \x01(\x03\x12\x12\n\nproperties\x18\x04 \x01(\x0c\x12"\n\x1aproperties_last_updated_at\x18\x05 \x01(\x0c\x12!\n\x19properties_last_operation\x18\x06 \x01(\x0c\x12\x12\n\ncreated_at\x18\x07 \x01(\x03\x12\x0f\n\x07version\x18\x08 \x01(\x03\x12\x15\n\ris_identified\x18\t \x01(\x08\x12\x17\n\nis_user_id\x18\n \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x0b \x01(\x03H\x01\x88\x01\x01\x12\x12\n\nis_deleted\x18\x0c \x01(\x08B\r\n\x0b_is_user_idB\x0f\n\r_last_seen_at"N\n\x15DistinctIdWithVersion\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x14\n\x07version\x18\x02 \x01(\x03H\x00\x88\x01\x01B\n\n\x08_version"h\n\x15PersonWithDistinctIds\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"g\n\x11PersonDistinctIds\x12\x11\n\tperson_id\x18\x01 \x01(\x03\x12?\n\x0cdistinct_ids\x18\x02 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\x87\x01\n\x18PersonWithTeamDistinctId\x12/\n\x03key\x18\x01 \x01(\x0b2".personhog.types.v1.TeamDistinctId\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"m\n\x10GetPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"O\n\x11GetPersonResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"o\n\x11GetPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"S\n\x0fPersonsResponse\x12+\n\x07persons\x18\x01 \x03(\x0b2\x1a.personhog.types.v1.Person\x12\x13\n\x0bmissing_ids\x18\x02 \x03(\x03"n\n\x16GetPersonByUuidRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"q\n\x18GetPersonsByUuidsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\r\n\x05uuids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"{\n\x1cGetPersonByDistinctIdRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"\x84\x01\n$GetPersonsByDistinctIdsInTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cdistinct_ids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"`\n"PersonsByDistinctIdsInTeamResponse\x12:\n\x07results\x18\x01 \x03(\x0b2).personhog.types.v1.PersonWithDistinctIds"\x96\x01\n\x1eGetPersonsByDistinctIdsRequest\x12=\n\x11team_distinct_ids\x18\x01 \x03(\x0b2".personhog.types.v1.TeamDistinctId\x125\n\x0cread_options\x18\x02 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"]\n\x1cPersonsByDistinctIdsResponse\x12=\n\x07results\x18\x01 \x03(\x0b2,.personhog.types.v1.PersonWithTeamDistinctId"\x99\x01\n\x1eGetDistinctIdsForPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x12\n\x05limit\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x08\n\x06_limit"b\n\x1fGetDistinctIdsForPersonResponse\x12?\n\x0cdistinct_ids\x18\x01 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\xb1\x01\n\x1fGetDistinctIdsForPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x1d\n\x10limit_per_person\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x13\n\x11_limit_per_person"f\n GetDistinctIdsForPersonsResponse\x12B\n\x13person_distinct_ids\x18\x01 \x03(\x0b2%.personhog.types.v1.PersonDistinctIds"\x80\x02\n\x1dUpdatePersonPropertiesRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x12\n\nevent_name\x18\x03 \x01(\t\x12\x16\n\x0eset_properties\x18\x04 \x01(\x0c\x12\x1b\n\x13set_once_properties\x18\x05 \x01(\x0c\x12\x18\n\x10unset_properties\x18\x06 \x03(\t\x12\x1a\n\ris_identified\x18\x07 \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x08 \x01(\x03H\x01\x88\x01\x01B\x10\n\x0e_is_identifiedB\x0f\n\r_last_seen_at"m\n\x1eUpdatePersonPropertiesResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01\x12\x0f\n\x07updated\x18\x02 \x01(\x08B\t\n\x07_person"=\n\x14DeletePersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cperson_uuids\x18\x02 \x03(\t".\n\x15DeletePersonsResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"G\n DeletePersonsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03":\n!DeletePersonsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"W\n\x12SplitPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x1d\n\x15distinct_ids_to_split\x18\x03 \x03(\t"\x8e\x01\n\x0bSplitResult\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x17\n\x0fnew_person_uuid\x18\x02 \x01(\t\x12\x1a\n\x12new_person_version\x18\x03 \x01(\x03\x12\x13\n\x0bpdi_version\x18\x04 \x01(\x03\x12 \n\x18new_person_created_at_ms\x18\x05 \x01(\x03"F\n\x13SplitPersonResponse\x12/\n\x06splits\x18\x01 \x03(\x0b2\x1f.personhog.types.v1.SplitResult"c\n&SetPersonDistinctIdVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"e\n\'SetPersonDistinctIdVersionFloorResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"W\n\x1cSetPersonVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"0\n\x1dSetPersonVersionFloorResponse\x12\x0f\n\x07updated\x18\x01 \x01(\x08"}\n\x12FencePersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\r\n\x05op_id\x18\x03 \x01(\t\x124\n\x07op_type\x18\x04 \x01(\x0e2#.personhog.types.v1.LifecycleOpType"A\n\x13FencePersonResponse\x12*\n\x06sealed\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person"\xd6\x01\n\x13ReleaseFenceRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bperson_uuid\x18\x03 \x01(\t\x12\r\n\x05op_id\x18\x04 \x01(\t\x123\n\x07outcome\x18\x05 \x01(\x0e2".personhog.types.v1.ReleaseOutcome\x12\x1b\n\x0esealed_version\x18\x06 \x01(\x03H\x00\x88\x01\x01\x12\x12\n\ncreated_at\x18\x07 \x01(\x03B\x11\n\x0f_sealed_version"\x16\n\x14ReleaseFenceResponse"S\n\x14SealedSourceSnapshot\x12*\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person\x12\x0f\n\x07ordinal\x18\x02 \x01(\x05"\xbd\x01\n\x19FoldPersonDocumentRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12B\n\x10sealed_snapshots\x18\x03 \x03(\x0b2(.personhog.types.v1.SealedSourceSnapshot\x12\x11\n\tevent_set\x18\x04 \x01(\x0c\x12\x16\n\x0eevent_set_once\x18\x05 \x01(\x0c\x12\r\n\x05op_id\x18\x06 \x01(\t"H\n\x1aFoldPersonDocumentResponse\x12*\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person*o\n\x0fLifecycleOpType\x12!\n\x1dLIFECYCLE_OP_TYPE_UNSPECIFIED\x10\x00\x12\x1c\n\x18LIFECYCLE_OP_TYPE_DELETE\x10\x01\x12\x1b\n\x17LIFECYCLE_OP_TYPE_MERGE\x10\x02*m\n\x0eReleaseOutcome\x12\x1f\n\x1bRELEASE_OUTCOME_UNSPECIFIED\x10\x00\x12\x1d\n\x19RELEASE_OUTCOME_COMMITTED\x10\x01\x12\x1b\n\x17RELEASE_OUTCOME_ABORTED\x10\x02b\x06proto3'+ b'\n\x1fpersonhog/types/v1/person.proto\x12\x12personhog.types.v1\x1a\x1fpersonhog/types/v1/common.proto"\xb2\x02\n\x06Person\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x12\x0f\n\x07team_id\x18\x03 \x01(\x03\x12\x12\n\nproperties\x18\x04 \x01(\x0c\x12"\n\x1aproperties_last_updated_at\x18\x05 \x01(\x0c\x12!\n\x19properties_last_operation\x18\x06 \x01(\x0c\x12\x12\n\ncreated_at\x18\x07 \x01(\x03\x12\x0f\n\x07version\x18\x08 \x01(\x03\x12\x15\n\ris_identified\x18\t \x01(\x08\x12\x17\n\nis_user_id\x18\n \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x0b \x01(\x03H\x01\x88\x01\x01\x12\x12\n\nis_deleted\x18\x0c \x01(\x08B\r\n\x0b_is_user_idB\x0f\n\r_last_seen_at"N\n\x15DistinctIdWithVersion\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x14\n\x07version\x18\x02 \x01(\x03H\x00\x88\x01\x01B\n\n\x08_version"h\n\x15PersonWithDistinctIds\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"g\n\x11PersonDistinctIds\x12\x11\n\tperson_id\x18\x01 \x01(\x03\x12?\n\x0cdistinct_ids\x18\x02 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\x87\x01\n\x18PersonWithTeamDistinctId\x12/\n\x03key\x18\x01 \x01(\x0b2".personhog.types.v1.TeamDistinctId\x12/\n\x06person\x18\x02 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"m\n\x10GetPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"O\n\x11GetPersonResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"o\n\x11GetPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"S\n\x0fPersonsResponse\x12+\n\x07persons\x18\x01 \x03(\x0b2\x1a.personhog.types.v1.Person\x12\x13\n\x0bmissing_ids\x18\x02 \x03(\x03"n\n\x16GetPersonByUuidRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"q\n\x18GetPersonsByUuidsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\r\n\x05uuids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"{\n\x1cGetPersonByDistinctIdRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"\x84\x01\n$GetPersonsByDistinctIdsInTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cdistinct_ids\x18\x02 \x03(\t\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"`\n"PersonsByDistinctIdsInTeamResponse\x12:\n\x07results\x18\x01 \x03(\x0b2).personhog.types.v1.PersonWithDistinctIds"\x96\x01\n\x1eGetPersonsByDistinctIdsRequest\x12=\n\x11team_distinct_ids\x18\x01 \x03(\x0b2".personhog.types.v1.TeamDistinctId\x125\n\x0cread_options\x18\x02 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions"]\n\x1cPersonsByDistinctIdsResponse\x12=\n\x07results\x18\x01 \x03(\x0b2,.personhog.types.v1.PersonWithTeamDistinctId"\x99\x01\n\x1eGetDistinctIdsForPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x12\n\x05limit\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x08\n\x06_limit"b\n\x1fGetDistinctIdsForPersonResponse\x12?\n\x0cdistinct_ids\x18\x01 \x03(\x0b2).personhog.types.v1.DistinctIdWithVersion"\xb1\x01\n\x1fGetDistinctIdsForPersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nperson_ids\x18\x02 \x03(\x03\x125\n\x0cread_options\x18\x03 \x01(\x0b2\x1f.personhog.types.v1.ReadOptions\x12\x1d\n\x10limit_per_person\x18\x04 \x01(\x03H\x00\x88\x01\x01B\x13\n\x11_limit_per_person"f\n GetDistinctIdsForPersonsResponse\x12B\n\x13person_distinct_ids\x18\x01 \x03(\x0b2%.personhog.types.v1.PersonDistinctIds"\x96\x02\n\x1dUpdatePersonPropertiesRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x12\n\nevent_name\x18\x03 \x01(\t\x12\x16\n\x0eset_properties\x18\x04 \x01(\x0c\x12\x1b\n\x13set_once_properties\x18\x05 \x01(\x0c\x12\x18\n\x10unset_properties\x18\x06 \x03(\t\x12\x1a\n\ris_identified\x18\x07 \x01(\x08H\x00\x88\x01\x01\x12\x19\n\x0clast_seen_at\x18\x08 \x01(\x03H\x01\x88\x01\x01\x12\x14\n\x0cforce_update\x18\t \x01(\x08B\x10\n\x0e_is_identifiedB\x0f\n\r_last_seen_at"m\n\x1eUpdatePersonPropertiesResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01\x12\x0f\n\x07updated\x18\x02 \x01(\x08B\t\n\x07_person"=\n\x14DeletePersonsRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0cperson_uuids\x18\x02 \x03(\t".\n\x15DeletePersonsResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"G\n DeletePersonsBatchForTeamRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x12\n\nbatch_size\x18\x02 \x01(\x03":\n!DeletePersonsBatchForTeamResponse\x12\x15\n\rdeleted_count\x18\x01 \x01(\x03"W\n\x12SplitPersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x1d\n\x15distinct_ids_to_split\x18\x03 \x03(\t"\x8e\x01\n\x0bSplitResult\x12\x13\n\x0bdistinct_id\x18\x01 \x01(\t\x12\x17\n\x0fnew_person_uuid\x18\x02 \x01(\t\x12\x1a\n\x12new_person_version\x18\x03 \x01(\x03\x12\x13\n\x0bpdi_version\x18\x04 \x01(\x03\x12 \n\x18new_person_created_at_ms\x18\x05 \x01(\x03"F\n\x13SplitPersonResponse\x12/\n\x06splits\x18\x01 \x03(\x0b2\x1f.personhog.types.v1.SplitResult"c\n&SetPersonDistinctIdVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x13\n\x0bdistinct_id\x18\x02 \x01(\t\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"e\n\'SetPersonDistinctIdVersionFloorResponse\x12/\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.PersonH\x00\x88\x01\x01B\t\n\x07_person"W\n\x1cSetPersonVersionFloorRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bmin_version\x18\x03 \x01(\x03"0\n\x1dSetPersonVersionFloorResponse\x12\x0f\n\x07updated\x18\x01 \x01(\x08"}\n\x12FencePersonRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\r\n\x05op_id\x18\x03 \x01(\t\x124\n\x07op_type\x18\x04 \x01(\x0e2#.personhog.types.v1.LifecycleOpType"A\n\x13FencePersonResponse\x12*\n\x06sealed\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person"\xd6\x01\n\x13ReleaseFenceRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12\x13\n\x0bperson_uuid\x18\x03 \x01(\t\x12\r\n\x05op_id\x18\x04 \x01(\t\x123\n\x07outcome\x18\x05 \x01(\x0e2".personhog.types.v1.ReleaseOutcome\x12\x1b\n\x0esealed_version\x18\x06 \x01(\x03H\x00\x88\x01\x01\x12\x12\n\ncreated_at\x18\x07 \x01(\x03B\x11\n\x0f_sealed_version"\x16\n\x14ReleaseFenceResponse"S\n\x14SealedSourceSnapshot\x12*\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person\x12\x0f\n\x07ordinal\x18\x02 \x01(\x05"\xbd\x01\n\x19FoldPersonDocumentRequest\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x11\n\tperson_id\x18\x02 \x01(\x03\x12B\n\x10sealed_snapshots\x18\x03 \x03(\x0b2(.personhog.types.v1.SealedSourceSnapshot\x12\x11\n\tevent_set\x18\x04 \x01(\x0c\x12\x16\n\x0eevent_set_once\x18\x05 \x01(\x0c\x12\r\n\x05op_id\x18\x06 \x01(\t"H\n\x1aFoldPersonDocumentResponse\x12*\n\x06person\x18\x01 \x01(\x0b2\x1a.personhog.types.v1.Person*o\n\x0fLifecycleOpType\x12!\n\x1dLIFECYCLE_OP_TYPE_UNSPECIFIED\x10\x00\x12\x1c\n\x18LIFECYCLE_OP_TYPE_DELETE\x10\x01\x12\x1b\n\x17LIFECYCLE_OP_TYPE_MERGE\x10\x02*m\n\x0eReleaseOutcome\x12\x1f\n\x1bRELEASE_OUTCOME_UNSPECIFIED\x10\x00\x12\x1d\n\x19RELEASE_OUTCOME_COMMITTED\x10\x01\x12\x1b\n\x17RELEASE_OUTCOME_ABORTED\x10\x02b\x06proto3')_globals = globals()_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "personhog.types.v1.person_pb2", _globals)if not _descriptor._USE_C_DESCRIPTORS:DESCRIPTOR._loaded_options = None- _globals["_LIFECYCLEOPTYPE"]._serialized_start = 4638- _globals["_LIFECYCLEOPTYPE"]._serialized_end = 4749- _globals["_RELEASEOUTCOME"]._serialized_start = 4751- _globals["_RELEASEOUTCOME"]._serialized_end = 4860+ _globals["_LIFECYCLEOPTYPE"]._serialized_start = 4660+ _globals["_LIFECYCLEOPTYPE"]._serialized_end = 4771+ _globals["_RELEASEOUTCOME"]._serialized_start = 4773+ _globals["_RELEASEOUTCOME"]._serialized_end = 4882_globals["_PERSON"]._serialized_start = 89_globals["_PERSON"]._serialized_end = 395_globals["_DISTINCTIDWITHVERSION"]._serialized_start = 397@@ -67,42 +67,42 @@ if not _descriptor._USE_C_DESCRIPTORS:_globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_start = 2485_globals["_GETDISTINCTIDSFORPERSONSRESPONSE"]._serialized_end = 2587_globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_start = 2590- _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2846- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2848- _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2957- _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2959- _globals["_DELETEPERSONSREQUEST"]._serialized_end = 3020- _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 3022- _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 3068- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 3070- _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3141- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3143- _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3201- _globals["_SPLITPERSONREQUEST"]._serialized_start = 3203- _globals["_SPLITPERSONREQUEST"]._serialized_end = 3290- _globals["_SPLITRESULT"]._serialized_start = 3293- _globals["_SPLITRESULT"]._serialized_end = 3435- _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3437- _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3507- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3509- _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3608- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3610- _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3711- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3713- _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3800- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3802- _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 3850- _globals["_FENCEPERSONREQUEST"]._serialized_start = 3852- _globals["_FENCEPERSONREQUEST"]._serialized_end = 3977- _globals["_FENCEPERSONRESPONSE"]._serialized_start = 3979- _globals["_FENCEPERSONRESPONSE"]._serialized_end = 4044- _globals["_RELEASEFENCEREQUEST"]._serialized_start = 4047- _globals["_RELEASEFENCEREQUEST"]._serialized_end = 4261- _globals["_RELEASEFENCERESPONSE"]._serialized_start = 4263- _globals["_RELEASEFENCERESPONSE"]._serialized_end = 4285- _globals["_SEALEDSOURCESNAPSHOT"]._serialized_start = 4287- _globals["_SEALEDSOURCESNAPSHOT"]._serialized_end = 4370- _globals["_FOLDPERSONDOCUMENTREQUEST"]._serialized_start = 4373- _globals["_FOLDPERSONDOCUMENTREQUEST"]._serialized_end = 4562- _globals["_FOLDPERSONDOCUMENTRESPONSE"]._serialized_start = 4564- _globals["_FOLDPERSONDOCUMENTRESPONSE"]._serialized_end = 4636+ _globals["_UPDATEPERSONPROPERTIESREQUEST"]._serialized_end = 2868+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_start = 2870+ _globals["_UPDATEPERSONPROPERTIESRESPONSE"]._serialized_end = 2979+ _globals["_DELETEPERSONSREQUEST"]._serialized_start = 2981+ _globals["_DELETEPERSONSREQUEST"]._serialized_end = 3042+ _globals["_DELETEPERSONSRESPONSE"]._serialized_start = 3044+ _globals["_DELETEPERSONSRESPONSE"]._serialized_end = 3090+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_start = 3092+ _globals["_DELETEPERSONSBATCHFORTEAMREQUEST"]._serialized_end = 3163+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_start = 3165+ _globals["_DELETEPERSONSBATCHFORTEAMRESPONSE"]._serialized_end = 3223+ _globals["_SPLITPERSONREQUEST"]._serialized_start = 3225+ _globals["_SPLITPERSONREQUEST"]._serialized_end = 3312+ _globals["_SPLITRESULT"]._serialized_start = 3315+ _globals["_SPLITRESULT"]._serialized_end = 3457+ _globals["_SPLITPERSONRESPONSE"]._serialized_start = 3459+ _globals["_SPLITPERSONRESPONSE"]._serialized_end = 3529+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_start = 3531+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORREQUEST"]._serialized_end = 3630+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_start = 3632+ _globals["_SETPERSONDISTINCTIDVERSIONFLOORRESPONSE"]._serialized_end = 3733+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_start = 3735+ _globals["_SETPERSONVERSIONFLOORREQUEST"]._serialized_end = 3822+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_start = 3824+ _globals["_SETPERSONVERSIONFLOORRESPONSE"]._serialized_end = 3872+ _globals["_FENCEPERSONREQUEST"]._serialized_start = 3874+ _globals["_FENCEPERSONREQUEST"]._serialized_end = 3999+ _globals["_FENCEPERSONRESPONSE"]._serialized_start = 4001+ _globals["_FENCEPERSONRESPONSE"]._serialized_end = 4066+ _globals["_RELEASEFENCEREQUEST"]._serialized_start = 4069+ _globals["_RELEASEFENCEREQUEST"]._serialized_end = 4283+ _globals["_RELEASEFENCERESPONSE"]._serialized_start = 4285+ _globals["_RELEASEFENCERESPONSE"]._serialized_end = 4307+ _globals["_SEALEDSOURCESNAPSHOT"]._serialized_start = 4309+ _globals["_SEALEDSOURCESNAPSHOT"]._serialized_end = 4392+ _globals["_FOLDPERSONDOCUMENTREQUEST"]._serialized_start = 4395+ _globals["_FOLDPERSONDOCUMENTREQUEST"]._serialized_end = 4584+ _globals["_FOLDPERSONDOCUMENTRESPONSE"]._serialized_start = 4586+ _globals["_FOLDPERSONDOCUMENTRESPONSE"]._serialized_end = 4658diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyiindex 170e94630f31..b49cc9727dfd 100644--- a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi@@ -348,6 +348,7 @@ class UpdatePersonPropertiesRequest(_message.Message):"unset_properties","is_identified","last_seen_at",+ "force_update",)TEAM_ID_FIELD_NUMBER: _ClassVar[int]PERSON_ID_FIELD_NUMBER: _ClassVar[int]@@ -357,6 +358,7 @@ class UpdatePersonPropertiesRequest(_message.Message):UNSET_PROPERTIES_FIELD_NUMBER: _ClassVar[int]IS_IDENTIFIED_FIELD_NUMBER: _ClassVar[int]LAST_SEEN_AT_FIELD_NUMBER: _ClassVar[int]+ FORCE_UPDATE_FIELD_NUMBER: _ClassVar[int]team_id: intperson_id: intevent_name: str@@ -365,6 +367,7 @@ class UpdatePersonPropertiesRequest(_message.Message):unset_properties: _containers.RepeatedScalarFieldContainer[str]is_identified: boollast_seen_at: int+ force_update: booldef __init__(self,@@ -376,6 +379,7 @@ class UpdatePersonPropertiesRequest(_message.Message):unset_properties: _Optional[_Iterable[str]] = ...,is_identified: bool = ...,last_seen_at: _Optional[int] = ...,+ force_update: bool = ...,) -> None: ...class UpdatePersonPropertiesResponse(_message.Message):diff --git a/products/dashboards/backend/models/dashboard_tile.py b/products/dashboards/backend/models/dashboard_tile.pyindex 54dffa6ab3b7..7686e1b63e8c 100644--- a/products/dashboards/backend/models/dashboard_tile.py+++ b/products/dashboards/backend/models/dashboard_tile.py@@ -269,12 +269,17 @@ class DashboardTile(models.Model):def sort_tiles_by_layout(tiles: list["DashboardTile"] | QuerySet["DashboardTile"], layout_size: str = "sm") -> list["DashboardTile"]:- """Sort tiles by their layout position (y, then x)."""+ """Sort tiles by their layout position (y, then x), then by id.++ Tiles without a layout all fall back to the same position, so without the id+ tiebreak their order would be whatever the database happened to return.+ """return sorted(tiles,key=lambda tile: (tile.layouts.get(layout_size, {}).get("y", 100),tile.layouts.get(layout_size, {}).get("x", 100),+ tile.pk or 0,),)diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.protoindex 6e6b28ff4c61..0589532548f1 100644--- a/proto/personhog/identity/v1/identity.proto+++ b/proto/personhog/identity/v1/identity.proto@@ -151,9 +151,14 @@ message MergePersonsRequest {// merge-mode policy to handle. Required, at least 1; unlimited is not a// supported mode.optional int64 move_limit = 8;- // Merge event created_at, epoch millis. Used as the survivor's- // created_at when it predates the current value.+ // Merge event created_at, epoch millis. Consulted only when the establish+ // path births a fresh person; a resolved survivor keeps the min of the+ // target's and the sealed sources' own values.int64 created_at = 9;+ // The uuid of the event that asked for this merge; op_id derives from it+ // one-way, so it is not recoverable. Recorded as $creator_event_uuid on+ // a person the establish path births. Send the same value on every retry.+ string creator_event_uuid = 10;}enum MergeSourceOutcome {@@ -173,17 +178,29 @@ enum MergeSourceOutcome {// allow_identified_sources.MERGE_SOURCE_OUTCOME_SKIPPED_ALREADY_IDENTIFIED = 5;// Another live lifecycle operation holds this person (or the source- // resolved differently between classification and claim). Retryable.+ // resolved differently between classification and claim). Retryable+ // only while unsettled; settled means this op's answer is frozen.MERGE_SOURCE_OUTCOME_SKIPPED_CONFLICT = 6;// The source person has more distinct ids than the request's move_limit.MERGE_SOURCE_OUTCOME_SKIPPED_MOVE_LIMIT = 7;// The pair could not be handled; details in server logs.MERGE_SOURCE_OUTCOME_ERROR = 8;+ // Definitively refused before anything was destroyed; every retry meets+ // the same refusal, so the caller settles the pair as lost. ERROR is a+ // completed operation whose source ended indeterminate.+ MERGE_SOURCE_OUTCOME_SKIPPED_REFUSED = 9;}message MergeSourceResult {string source_distinct_id = 1;MergeSourceOutcome outcome = 2;+ // The destroyed source person; set only on MERGED, where the person is+ // permanently gone and safe to reconcile against without re-reading.+ optional int64 source_person_id = 3;+ // Whether any retry can change this source's outcome. True acks the+ // event, false lets redelivery try again. Outcome names are warning+ // labels, never durability inputs, so unknown values stay handled.+ bool settled = 4;}message MergePersonsResponse {@@ -232,7 +249,8 @@ service PersonHogIdentity {// of the router RPC of the same name (which reads the replica).rpc GetDistinctIdsForPersons(GetDistinctIdsForPersonsRequest) returns (GetDistinctIdsForPersonsResponse);// Merge source persons into the target distinct id's person. The- // service resolves and classifies every pair: same-person pairs settle+ // service resolves and classifies every pair: unresolved sources attach+ // to the target with plain mapping inserts, same-person pairs settle// inline, distinct-person pairs run the durable merge saga (fence the// sources, fold their sealed documents into the target, repoint distinct// ids, tombstone the sources, produce death documents). An unresolveddiff --git a/proto/personhog/leader/v1/leader.proto b/proto/personhog/leader/v1/leader.protoindex 7feb4afe5493..0c1c68a4aeac 100644--- a/proto/personhog/leader/v1/leader.proto+++ b/proto/personhog/leader/v1/leader.proto@@ -25,9 +25,12 @@ service PersonHogLeader {// this RPC is ever called; a leader taking partition ownership rebuilds// its map from the live marks before accepting writes. Fencing produces// nothing to the changelog and does not advance the version — the- // sealed version is the person's current one. While fenced, writes fail+ // sealed version is the person's current one raised to the leader's+ // emitted-version floor, covering a pre-fence write whose outcome is+ // still indeterminate. While fenced, writes fail// FAILED_PRECONDITION with an `x-person-fenced` metadata key carrying- // the op type; reads are unaffected. Re-fencing with the same op_id+ // the op type and `x-person-fenced-op-id` carrying the holder's op id;+ // reads are unaffected. Re-fencing with the same op_id// re-seals with fresh state (what makes the saga's seal step safe to// repeat); a different op_id is rejected — at most one lifecycle op// holds a person. The fence never lapses on a timer: only ReleaseFencediff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.protoindex 9977f702263f..2ba739675fc1 100644--- a/proto/personhog/types/v1/person.proto+++ b/proto/personhog/types/v1/person.proto@@ -170,6 +170,10 @@ message UpdatePersonPropertiesRequest {// flooring bounds record volume at one per person-hour regardless of// the caller's precision.optional int64 last_seen_at = 8;+ // The event kind warrants a write regardless of which properties changed.+ // Computed by the caller from the event alone; when false, filtered-only+ // changes answer updated=false and write nothing.+ bool force_update = 9;}message UpdatePersonPropertiesResponse {diff --git a/rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json b/rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.jsonnew file mode 100644index 000000000000..6c68dc034190--- /dev/null+++ b/rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "step",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "completed_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd"+}diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rsindex a2918a1852ad..11c3c816406f 100644--- a/rust/personhog-common/src/client.rs+++ b/rust/personhog-common/src/client.rs@@ -267,6 +267,7 @@ mod tests {#[tokio::test]async fn update_request_carries_the_routing_headers() {let request = client().build_update_request(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 7,person_id: 42,..Default::default()diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rsindex ceb213c23201..f8cef71a9b62 100644--- a/rust/personhog-common/src/grpc.rs+++ b/rust/personhog-common/src/grpc.rs@@ -63,6 +63,19 @@ pub fn semantic_refusal_reason(status: &tonic::Status) -> Option<&str> {.and_then(|v| v.to_str().ok())}+/// The refusal reason as a metric label: bounded and character-safe, so a+/// misbehaving peer cannot mint unbounded label cardinality or break the+/// metric encoding. Falls back to "unknown".+pub fn refusal_reason_label(status: &tonic::Status) -> &str {+ semantic_refusal_reason(status)+ .filter(|r| {+ r.len() <= 64+ && r.chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))+ })+ .unwrap_or("unknown")+}+/// Header name for caller-tag attribution in gRPC metadata./// Identifies the code path / feature area within a service that/// triggered the request (e.g., "api/feature-flags", "celery/cohort-calculation").diff --git a/rust/personhog-identity/.sqlx/query-1cab216d81775fa045fb1a9d8bd50ff9b3b0a014c35ebc97c07eff5577541a6b.json b/rust/personhog-identity/.sqlx/query-1cab216d81775fa045fb1a9d8bd50ff9b3b0a014c35ebc97c07eff5577541a6b.jsonnew file mode 100644index 000000000000..7a38ef79d4ae--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-1cab216d81775fa045fb1a9d8bd50ff9b3b0a014c35ebc97c07eff5577541a6b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM lifecycle_op\n WHERE op_id IN (\n SELECT op_id FROM lifecycle_op\n WHERE completed_at IS NOT NULL\n AND completed_at < now() - make_interval(secs => $1)\n LIMIT $2\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Float8",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "1cab216d81775fa045fb1a9d8bd50ff9b3b0a014c35ebc97c07eff5577541a6b"+}diff --git a/rust/personhog-identity/.sqlx/query-2291c5f5ecbd8c3254413064ba987ed11445da486366938c04c43c7b2b3756e1.json b/rust/personhog-identity/.sqlx/query-2291c5f5ecbd8c3254413064ba987ed11445da486366938c04c43c7b2b3756e1.jsonnew file mode 100644index 000000000000..6963ad486395--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-2291c5f5ecbd8c3254413064ba987ed11445da486366938c04c43c7b2b3756e1.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT person_id, person_uuid FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "person_uuid",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "2291c5f5ecbd8c3254413064ba987ed11445da486366938c04c43c7b2b3756e1"+}diff --git a/rust/personhog-identity/.sqlx/query-2bc0abfc06c474ebe9f698a73bb9dbaf0a83a50433ca1417580a5fd16cd1e7f2.json b/rust/personhog-identity/.sqlx/query-2bc0abfc06c474ebe9f698a73bb9dbaf0a83a50433ca1417580a5fd16cd1e7f2.jsonnew file mode 100644index 000000000000..6eae6f0ddbe7--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-2bc0abfc06c474ebe9f698a73bb9dbaf0a83a50433ca1417580a5fd16cd1e7f2.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM lifecycle_op\n WHERE op_id = $1\n AND completed_at IS NOT NULL\n AND (outcome->>'claim_abort')::boolean IS TRUE\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "2bc0abfc06c474ebe9f698a73bb9dbaf0a83a50433ca1417580a5fd16cd1e7f2"+}diff --git a/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.json b/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.jsondeleted file mode 100644index 04282525f4fd..000000000000--- a/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM lifecycle_op\n WHERE completed_at IS NOT NULL\n AND completed_at < now() - make_interval(secs => $1)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Float8"- ]- },- "nullable": []- },- "hash": "3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48"-}diff --git a/rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json b/rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.jsonnew file mode 100644index 000000000000..6c68dc034190--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "step",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "completed_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd"+}diff --git a/rust/personhog-identity/.sqlx/query-98224085819d17f751847d04069037c8f9affc8d667c855a262b456c5dbc127f.json b/rust/personhog-identity/.sqlx/query-98224085819d17f751847d04069037c8f9affc8d667c855a262b456c5dbc127f.jsonnew file mode 100644index 000000000000..28e9063e4892--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-98224085819d17f751847d04069037c8f9affc8d667c855a262b456c5dbc127f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM lifecycle_op_person WHERE op_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "98224085819d17f751847d04069037c8f9affc8d667c855a262b456c5dbc127f"+}diff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.mdindex af56159b2fd5..47f3b4a6676f 100644--- a/rust/personhog-identity/README.md+++ b/rust/personhog-identity/README.md@@ -35,3 +35,11 @@ Tests need the persons database (`posthog_persons`) with `rust/persons_migration```bashcargo test -p personhog-identity```++## Parked lifecycle ops++A lifecycle op parks when the leader answers a semantic refusal after the point of no return: retrying a definitive refusal cannot succeed, so the op holds its fences and only an explicit retry under the same op id resumes it (the sweeper is barred). Refusals before the point of no return abort instead, recording `skipped_refused` for their sources and releasing fences in the same settlement. The sweeper re-drives interrupted sagas to a terminal state and defaults on; a fleet that disables it converts every orphaned saga into fences an operator must clear. The surface is the `personhog_lifecycle_ops_parked` gauge and the park's ERROR log carrying the op id and reason; resolution is a retry with the recorded op id.++## Delete retries must present a byte-stable request++A same-op-id delete retry is compared byte-for-byte against the frozen request, so the caller must present the identical `person_ids` list (same order, same duplicates) on every retry; a mismatch is refused `op_id_reused` and the deletion must be reissued under a fresh op id.diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rsindex 6bc7ced779d2..7faa5784c632 100644--- a/rust/personhog-identity/src/config.rs+++ b/rust/personhog-identity/src/config.rs@@ -119,8 +119,8 @@ pub struct Config {#[envconfig(default = "15")]pub lifecycle_lease_secs: u64,- /// How long a DeletePersons call keeps driving (or waiting on another- /// driver's lease) before returning UNAVAILABLE (seconds).+ /// Seconds one lifecycle call drives (or waits on another driver's+ /// lease) before returning UNAVAILABLE; callers need a larger deadline.#[envconfig(default = "30")]pub lifecycle_execute_timeout_secs: u64,@@ -132,21 +132,23 @@ pub struct Config {#[envconfig(default = "5")]pub lifecycle_attempt_alert_threshold: i32,- /// Run the background sweeper + GC loop for abandoned lifecycle ops.- /// One sweeper per fleet is enough; every instance running it is also- /// fine (the lease arbitrates), so this is a plain per-pod toggle.- #[envconfig(default = "false")]+ /// Run the sweeper + GC loop for abandoned lifecycle ops; the lease+ /// arbitrates, so any number of instances may run it.+ #[envconfig(default = "true")]pub lifecycle_sweeper_enabled: bool,/// Interval between sweeper passes (seconds).#[envconfig(default = "30")]pub lifecycle_sweep_interval_secs: u64,- /// How long completed op rows are retained for op_id idempotency before- /// GC (hours). The durable deletion shield is the person tombstone row,- /// not the op row.+ /// Hours completed op rows are kept for op_id idempotency before GC.#[envconfig(default = "24")]pub lifecycle_op_retention_hours: u64,++ /// Rows one GC pass may delete, so a post-backlog sweep never holds+ /// locks for long; the next pass continues.+ #[envconfig(default = "10000")]+ pub lifecycle_gc_batch_limit: i64,}/// The paired table set identity operates on: the person table plus the@@ -264,6 +266,7 @@ impl Config {execute_timeout: Duration::from_secs(self.lifecycle_execute_timeout_secs),poll_interval: Duration::from_millis(self.lifecycle_poll_interval_ms),attempt_alert_threshold: self.lifecycle_attempt_alert_threshold,+ gc_batch_limit: self.lifecycle_gc_batch_limit,}}diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rsindex 447650022bbc..46e2db406c00 100644--- a/rust/personhog-identity/src/lifecycle/delete.rs+++ b/rust/personhog-identity/src/lifecycle/delete.rs@@ -425,6 +425,8 @@ async fn seal(pool: &PgPool, leader: &dyn LifecycleLeader, op: &OpRow) -> Result);vanished.push(person_id);}+ // FencePerson mints no semantic refusal today; adding one+ // needs an abort path first (see the merge driver's).Err(status) => return Err(SagaError::leader(status)),}}diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rsindex 705873eccfab..8b6d0be85efc 100644--- a/rust/personhog-identity/src/lifecycle/engine.rs+++ b/rust/personhog-identity/src/lifecycle/engine.rs@@ -58,6 +58,10 @@ pub enum SagaError {/// Another instance held the lease past our deadline.#[error("another instance is driving this operation")]Busy,+ /// The drive's own execute deadline elapsed; a same-op-id retry+ /// resumes it. `Busy` instead means contention.+ #[error("execute deadline elapsed")]+ DeadlineElapsed,/// A leader RPC (fence, release, fold) failed transiently. The step made/// no durable progress; a retry with the same op_id re-drives it. Boxed/// so the rare failure does not widen every step's Result.@@ -123,6 +127,9 @@ impl From<SagaError> for Status {SagaError::Busy => Status::unavailable("another instance is driving this operation; retry with the same op_id",),+ SagaError::DeadlineElapsed => Status::unavailable(+ "execute deadline elapsed while the operation was still being driven; retry with the same op_id",+ ),SagaError::Leader(status) => Status::unavailable(format!("leader call failed ({}: {}); retry with the same op_id",status.code(),@@ -183,6 +190,9 @@ pub struct EngineConfig {pub poll_interval: Duration,/// Log a warning when an op's attempt counter reaches this value.pub attempt_alert_threshold: i32,+ /// Rows one GC pass may delete, so a post-backlog sweep never holds+ /// locks for long; the next pass continues.+ pub gc_batch_limit: i64,}pub struct Engine {@@ -327,8 +337,8 @@ impl Engine {};if let Some(completed_at) = row.completed_at {if claim_attempt.is_some() {- // We drove it over the line (vs attaching to an op that- // was already done).+ // A stolen lease double-counts alongside the stealer;+ // exact attribution would cost a query per completion.common_metrics::inc(OPS_COMPLETED_TOTAL,&[@@ -348,8 +358,11 @@ impl Engine {return Ok(row);}if tokio::time::Instant::now() >= deadline {+ // With the claim in hand the drive was simply slow, not+ // contended.if let Some(attempt) = claim_attempt {self.release_lease(op_id, attempt).await.ok();+ return Err(SagaError::DeadlineElapsed);}return Err(SagaError::Busy);}@@ -412,9 +425,10 @@ impl Engine {SagaError::Leader(_) => "leader",SagaError::LeaderRefused(_) => "leader_refused",SagaError::CorruptState(_) => "corrupt_state",- // Not constructed by drivers; collapsed so dashboards- // never chase dead labels.- SagaError::RequestMismatch(_) | SagaError::Busy => "other",+ // Collapsed: these carry no attribution worth a label.+ SagaError::RequestMismatch(_)+ | SagaError::Busy+ | SagaError::DeadlineElapsed => "other",};common_metrics::inc(STEP_FAILURES_TOTAL,@@ -547,16 +561,7 @@ impl Engine {row: &OpRow,status: &Status,) -> Result<bool, sqlx::Error> {- // The reason becomes a metric label; cap it so a misbehaving- // peer cannot mint unbounded label cardinality.- let reason = personhog_common::grpc::semantic_refusal_reason(status)- .filter(|r| {- r.len() <= 64- && r.chars()- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))- })- .unwrap_or("unknown")- .to_string();+ let reason = personhog_common::grpc::refusal_reason_label(status).to_string();let parked = sqlx::query!(r#"UPDATE lifecycle_op@@ -692,10 +697,15 @@ impl Engine {let result = sqlx::query!(r#"DELETE FROM lifecycle_op- WHERE completed_at IS NOT NULL- AND completed_at < now() - make_interval(secs => $1)+ WHERE op_id IN (+ SELECT op_id FROM lifecycle_op+ WHERE completed_at IS NOT NULL+ AND completed_at < now() - make_interval(secs => $1)+ LIMIT $2+ )"#,retention.as_secs_f64(),+ self.config.gc_batch_limit,).execute(&self.pool).await?;diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsindex 13e651c0e329..6ac1c1232b17 100644--- a/rust/personhog-identity/src/lifecycle/merge.rs+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -36,6 +36,7 @@ use std::sync::Arc;use async_trait::async_trait;use futures::stream::{self, StreamExt};+use personhog_common::persons::person_uuid;use serde::{Deserialize, Serialize};use serde_json::Value;use sqlx::postgres::PgPool;@@ -110,6 +111,15 @@ pub struct MergeRequest {/// Per-source distinct-id count guard. Required: an unlimited merge/// would make the flip's repoint an unbounded statement.pub move_limit: i64,+ /// The event that asked for this merge, recorded as $creator_event_uuid+ /// on a person this call's establishment births. Skipped when empty so+ /// older frozen rows compare equal.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub creator_event_uuid: String,+ /// Establishment birthed the target, so the fold and the abort delivery+ /// stamp its creating event (a recycled source can complete a born fold).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub target_born: bool,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -121,6 +131,21 @@ pub struct MergeSourceEntry {pub event_uuid: String,}+/// Whether another driver advanced or settled the op past our step.+async fn op_moved_on(pool: &PgPool, op: &OpRow) -> Result<bool, SagaError> {+ let current = sqlx::query!(+ r#"SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1"#,+ op.op_id+ )+ .fetch_optional(pool)+ .await?;+ Ok(match current {+ // A vanished row was completed and garbage-collected.+ None => true,+ Some(row) => row.completed_at.is_some() || row.step != op.step,+ })+}+/// The recorded `lifecycle_op.outcome` payload: one entry per requested/// source distinct id, in request order, plus the survivor document when/// the merge committed.@@ -137,6 +162,9 @@ pub struct MergeOutcome {pub struct MergeSourceRecord {pub distinct_id: String,pub outcome: String,+ /// Defaulted so rows written before the field existed replay as `None`.+ #[serde(default)]+ pub person_id: Option<i64>,}pub const OUTCOME_MERGED: &str = "merged";@@ -144,6 +172,24 @@ pub const OUTCOME_NOOP_SAME_PERSON: &str = "noop_same_person";pub const OUTCOME_SKIPPED_ALREADY_IDENTIFIED: &str = "skipped_already_identified";pub const OUTCOME_SKIPPED_CONFLICT: &str = "skipped_conflict";pub const OUTCOME_SKIPPED_MOVE_LIMIT: &str = "skipped_move_limit";+pub const OUTCOME_SKIPPED_REFUSED: &str = "skipped_refused";++#[derive(Clone, Copy)]+enum AbortOutcome {+ /// Claim contention: another live op held a person. Unsettled.+ Conflict,+ /// A definitive leader refusal: retrying meets the same answer.+ Refused,+}++impl AbortOutcome {+ fn as_str(self) -> &'static str {+ match self {+ AbortOutcome::Conflict => OUTCOME_SKIPPED_CONFLICT,+ AbortOutcome::Refused => OUTCOME_SKIPPED_REFUSED,+ }+ }+}pub const OUTCOME_ERROR: &str = "error";/// Per-person row statuses this driver writes. `marked`/`sealed` are the@@ -168,6 +214,8 @@ const LEADER_CALL_CONCURRENCY: usize = 8;const STEPS_TOTAL: &str = "personhog_lifecycle_merge_steps_total";const OUTCOMES_TOTAL: &str = "personhog_lifecycle_merge_outcomes_total";+/// Pre-flip aborts by refusal slug.+const ABORTS_TOTAL: &str = "personhog_lifecycle_merge_aborts_total";fn record_transition(from: &str, to: &str) {common_metrics::inc(@@ -201,6 +249,7 @@ fn record_outcomes(outcome: &Value) {OUTCOME_SKIPPED_ALREADY_IDENTIFIED,OUTCOME_SKIPPED_CONFLICT,OUTCOME_SKIPPED_MOVE_LIMIT,+ OUTCOME_SKIPPED_REFUSED,OUTCOME_ERROR,] {let count = parsed.results.iter().filter(|r| r.outcome == label).count();@@ -295,6 +344,51 @@ impl MergeOpExecutor {.map_err(|e| Status::internal(format!("database error: {e}")))}+ /// Whether this terminal row is a disposable claim abort.+ pub fn is_claim_abort(row: &OpRow) -> bool {+ row.completed_at.is_some()+ && row+ .outcome+ .as_ref()+ .and_then(|o| o.get("claim_abort"))+ .and_then(Value::as_bool)+ == Some(true)+ }++ /// Delete a claim-aborted op; the flag is re-checked in SQL.+ // See `find` for why result_large_err is allowed.+ #[allow(clippy::result_large_err)]+ pub async fn discard_claim_abort(&self, op_id: Uuid) -> Result<(), Status> {+ let mut tx = self+ .engine+ .pool()+ .begin()+ .await+ .map_err(|e| Status::internal(format!("discard begin failed: {e}")))?;+ let deleted = sqlx::query!(+ r#"+ DELETE FROM lifecycle_op+ WHERE op_id = $1+ AND completed_at IS NOT NULL+ AND (outcome->>'claim_abort')::boolean IS TRUE+ "#,+ op_id+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| Status::internal(format!("discard failed: {e}")))?;+ if deleted.rows_affected() > 0 {+ sqlx::query!("DELETE FROM lifecycle_op_person WHERE op_id = $1", op_id)+ .execute(&mut *tx)+ .await+ .map_err(|e| Status::internal(format!("discard marks failed: {e}")))?;+ }+ tx.commit()+ .await+ .map_err(|e| Status::internal(format!("discard commit failed: {e}")))?;+ Ok(())+ }+/// Drive the op to terminal with the given frozen request (a resumed/// row's own request, or a freshly frozen one) and return the row.// See `find` for why result_large_err is allowed.@@ -781,7 +875,15 @@ async fn abort_in_claim_tx(op: &OpRow,dispositions: Vec<Disposition>,) -> Result<(), SagaError> {- let outcome = outcome_from_dispositions(&dispositions, true, None, &HashMap::new())?;+ let mut outcome = outcome_from_dispositions(+ &dispositions,+ Some(AbortOutcome::Conflict),+ None,+ &HashMap::new(),+ )?;+ // The entrance discards flagged rows on the next presentation of the+ // op id, so a plain retry re-runs where a recorded conflict replays.+ outcome["claim_abort"] = Value::Bool(true);if !complete_op_in_tx(&mut tx,op.op_id,@@ -935,7 +1037,7 @@ impl MergeDriver {).execute(&mut *tx).await?;- let outcome = build_outcome(&mut tx, op, true).await?;+ let outcome = build_outcome(&mut tx, op, Some(AbortOutcome::Conflict)).await?;if !complete_op_in_tx(&mut tx,op.op_id,@@ -997,11 +1099,8 @@ impl MergeDriver {Ok(())}- /// Back the op out after a pre-flip refusal: release the live- /// sources' fences (an aborted release cannot itself be refused),- /// settle the marks, and complete as aborted. Nothing irreversible- /// has happened before the flip, so unwinding is safe; a refusal- /// after the flip has no undo and parks instead.+ /// Back the op out after a pre-flip refusal. Nothing is destroyed+ /// before the flip, so unwinding is safe; post-flip refusals park.async fn abort_refused(&self,pool: &PgPool,@@ -1020,7 +1119,6 @@ impl MergeDriver {.fetch_all(pool).await?;let pairs: Vec<(i64, Uuid)> = live.iter().map(|s| (s.person_id, s.person_uuid)).collect();- self.release_fences(op, &pairs).await?;let mut tx = pool.begin().await?;sqlx::query!(@@ -1042,7 +1140,8 @@ impl MergeDriver {).execute(&mut *tx).await?;- let outcome = build_outcome(&mut tx, op, true).await?;+ // Fence contention never reaches this abort; it retries at the step.+ let outcome = build_outcome(&mut tx, op, Some(AbortOutcome::Refused)).await?;if !complete_op_in_tx(&mut tx,op.op_id,@@ -1056,15 +1155,28 @@ impl MergeDriver {return Ok(());}tx.commit().await?;+ // Attribute the abort before the releases: a failed release+ // leaves the op terminal with nothing retrying it.tracing::error!(op_id = %op.op_id,step = %from_step.as_str(),- reason = %personhog_common::grpc::semantic_refusal_reason(status).unwrap_or("unknown"),+ reason = %personhog_common::grpc::refusal_reason_label(status),message = %status.message(),- "leader definitively refused a pre-flip merge step; op aborted and fences released"+ "leader definitively refused a pre-flip merge step; op aborted, releasing its fences");record_transition(from_step.as_str(), STEP_ABORTED);+ common_metrics::inc(+ ABORTS_TOTAL,+ &[(+ "reason".to_string(),+ personhog_common::grpc::refusal_reason_label(status).to_string(),+ )],+ 1,+ );record_outcomes(&outcome);+ // Releases only after the completing CAS proves we still owned the+ // op; ghosts left by a crash here are healed lazily by the leader.+ self.release_fences(op, &pairs).await?;Ok(())}@@ -1150,6 +1262,8 @@ async fn settle_drops(continue;};if vanished.contains(&person_id) {+ // error-without-merged reads as an abort to the caller's fold+ // guard, so this shape cannot read as executed.disposition.decision = OUTCOME_ERROR.to_string();} else if identified.contains(&person_id) {disposition.decision = OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string();@@ -1223,13 +1337,32 @@ impl MergeDriver {});}+ // The stub never reached the changelog, so the born stamp rides the+ // fold's $set; the uuid check keeps it off a person the claim+ // resolved after a rival settled the newborn away.+ let mut event_set = request.event_set.clone();+ if request.target_born+ && !request.creator_event_uuid.is_empty()+ && target.person_uuid == person_uuid(op.team_id, &request.target_distinct_id)+ {+ if event_set.is_null() {+ event_set = Value::Object(Default::default());+ }+ let map = event_set.as_object_mut().ok_or_else(|| {+ SagaError::CorruptState(format!("merge op {} event_set is not a map", op.op_id))+ })?;+ map.insert(+ "$creator_event_uuid".to_string(),+ Value::String(request.creator_event_uuid.clone()),+ );+ }let response = match self.leader.fold_person_document(FoldPersonDocumentRequest {team_id: op.team_id,person_id: target.person_id,sealed_snapshots: snapshots,- event_set: encode_json_map(&request.event_set)?,+ event_set: encode_json_map(&event_set)?,event_set_once: encode_json_map(&request.event_set_once)?,op_id: op.op_id.to_string(),})@@ -1239,8 +1372,22 @@ impl MergeDriver {Err(status) => {return match SagaError::leader(status) {SagaError::LeaderRefused(status) => {- self.abort_refused(pool, op, MergeStep::SourcesSealed, &status)- .await+ // Under a stale claim the advancing driver still+ // needs the fences, so Busy re-attaches the retry;+ // under a live claim the pre-flip abort is safe.+ if personhog_common::grpc::semantic_refusal_reason(&status)+ == Some("fold-unverified")+ && op_moved_on(pool, op).await?+ {+ tracing::info!(+ op_id = %op.op_id,+ "stale drive's fold refusal deferred to the op row; the caller's retry attaches to it"+ );+ Err(SagaError::Busy)+ } else {+ self.abort_refused(pool, op, MergeStep::SourcesSealed, &status)+ .await+ }}err => Err(err),};@@ -1258,6 +1405,7 @@ impl MergeDriver {"properties": serde_json::from_slice::<Value>(&folded.properties).unwrap_or_else(|_| Value::Object(serde_json::Map::new())),"created_at": folded.created_at,+ "last_seen_at": folded.last_seen_at,"is_identified": folded.is_identified,"version": folded.version,});@@ -1293,11 +1441,12 @@ impl MergeDriver {struct TargetRow {person_id: i64,+ person_uuid: Uuid,}async fn target_row(pool: &PgPool, op: &OpRow) -> Result<TargetRow, SagaError> {let row = sqlx::query!(- "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "SELECT person_id, person_uuid FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",op.op_id,ROLE_TARGET,)@@ -1305,6 +1454,7 @@ async fn target_row(pool: &PgPool, op: &OpRow) -> Result<TargetRow, SagaError> {.await?;Ok(TargetRow {person_id: row.person_id,+ person_uuid: row.person_uuid,})}@@ -1349,6 +1499,31 @@ async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),.await?;sources.sort_unstable();+ // Lock every row up front in id order; the writer's flush does the+ // same, so a deadlock cycle is impossible. Including the target keeps+ // the lock set a superset of any partner's.+ let mut lock_ids = sources.clone();+ lock_ids.push(target);+ lock_ids.sort_unstable();+ let lock_persons_sql = format!(+ "SELECT id FROM {person_table} WHERE team_id = $1 AND id = ANY($2) ORDER BY id FOR UPDATE",+ person_table = tables.person,+ );+ sqlx::query(&lock_persons_sql)+ .bind(team_id)+ .bind(&lock_ids)+ .execute(&mut *tx)+ .await?;+ let lock_pdi_sql = format!(+ "SELECT id FROM {pdi_table} WHERE team_id = $1 AND person_id = ANY($2) ORDER BY id FOR UPDATE",+ pdi_table = tables.person_distinct_id,+ );+ sqlx::query(&lock_pdi_sql)+ .bind(team_id)+ .bind(&sources)+ .execute(&mut *tx)+ .await?;+let repointed = repoint_distinct_ids(&mut tx, tables, team_id, &sources, target).await?;record_moved_mappings(&mut tx, op, &sources, &repointed).await?;move_cohort_membership(&mut tx, tables, &sources, target).await?;@@ -1521,11 +1696,8 @@ async fn move_hash_key_overrides(}/// Scrub and tombstone the sealed source person rows at the death version-/// the leader derives from the same seal (sealed + 1; the leader-/// max-merges with its current version as defense in depth), so a reused-/// key revives above it. Exact PG/CH agreement additionally assumes no-/// spent-but-unconfirmed version sits above the seal — the fence path-/// does not consult the leader's emitted-version floor today.+/// the leader derives from the same seal (sealed + 1), so a reused key+/// revives above it.async fn tombstone_sealed_sources(tx: &mut Tx<'_>,tables: &IdentityTables,@@ -1653,7 +1825,7 @@ impl MergeDriver {).execute(&mut *tx).await?;- let outcome = build_outcome(&mut tx, op, false).await?;+ let outcome = build_outcome(&mut tx, op, None).await?;if !complete_op_in_tx(&mut tx,op.op_id,@@ -1697,7 +1869,11 @@ async fn claim_record(tx: &mut Tx<'_>, op: &OpRow) -> Result<ClaimRecord, SagaEr/// their row's status: `deleted` means the merge committed for that/// person; anything else on a non-aborted path is an anomaly reported as/// `error`.-async fn build_outcome(tx: &mut Tx<'_>, op: &OpRow, aborted: bool) -> Result<Value, SagaError> {+async fn build_outcome(+ tx: &mut Tx<'_>,+ op: &OpRow,+ abort_outcome: Option<AbortOutcome>,+) -> Result<Value, SagaError> {let record = claim_record(tx, op).await?;let statuses: HashMap<i64, String> = sqlx::query!("SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",@@ -1710,7 +1886,7 @@ async fn build_outcome(tx: &mut Tx<'_>, op: &OpRow, aborted: bool) -> Result<Val.map(|r| (r.person_id, r.status)).collect();- let survivor = if aborted {+ let survivor = if abort_outcome.is_some() {None} else {let row = sqlx::query!(@@ -1723,12 +1899,12 @@ async fn build_outcome(tx: &mut Tx<'_>, op: &OpRow, aborted: bool) -> Result<Valrow.sealed};- outcome_from_dispositions(&record.dispositions, aborted, survivor, &statuses)+ outcome_from_dispositions(&record.dispositions, abort_outcome, survivor, &statuses)}fn outcome_from_dispositions(dispositions: &[Disposition],- aborted: bool,+ abort_outcome: Option<AbortOutcome>,survivor: Option<Value>,statuses: &HashMap<i64, String>,) -> Result<Value, SagaError> {@@ -1740,10 +1916,10 @@ fn outcome_from_dispositions(.person_id.and_then(|id| statuses.get(&id)).map(String::as_str);- match (aborted, status) {- (true, _) => OUTCOME_SKIPPED_CONFLICT,- (false, Some(STATUS_DELETED)) => OUTCOME_MERGED,- (false, _) => OUTCOME_ERROR,+ match (abort_outcome, status) {+ (Some(abort), _) => abort.as_str(),+ (None, Some(STATUS_DELETED)) => OUTCOME_MERGED,+ (None, _) => OUTCOME_ERROR,}} else {d.decision.as_str()@@ -1751,11 +1927,12 @@ fn outcome_from_dispositions(MergeSourceRecord {distinct_id: d.distinct_id.clone(),outcome: outcome.to_string(),+ person_id: d.person_id,}}).collect();serde_json::to_value(MergeOutcome {- aborted,+ aborted: abort_outcome.is_some(),survivor,results,})diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rsindex b1293b678cc6..76d7ce3ac303 100644--- a/rust/personhog-identity/src/lifecycle/validation.rs+++ b/rust/personhog-identity/src/lifecycle/validation.rs@@ -65,8 +65,26 @@ static CASE_INSENSITIVE_ILLEGAL_IDS: LazyLock<HashSet<String>> =static CASE_SENSITIVE_ILLEGAL_IDS: LazyLock<HashSet<String>> =LazyLock::new(|| with_quoted(BARE_CASE_SENSITIVE_ILLEGAL_IDS));+/// Whether JavaScript's `String.prototype.trim` would strip this char.+/// Deliberately not Rust's `str::trim`, which also strips U+0085: the+/// two sides must agree on which ids are illegal.+fn is_js_whitespace(c: char) -> bool {+ matches!(+ c,+ '\t' | '\u{000B}' | '\u{000C}' | ' ' | '\u{00A0}' | '\u{FEFF}' | '\u{1680}' | '\u{2000}'+ ..='\u{200A}'+ | '\u{202F}'+ | '\u{205F}'+ | '\u{3000}'+ | '\n'+ | '\r'+ | '\u{2028}'+ | '\u{2029}'+ )+}+pub fn is_distinct_id_illegal(id: &str) -> bool {- id.trim().is_empty()+ id.trim_matches(is_js_whitespace).is_empty()|| CASE_INSENSITIVE_ILLEGAL_IDS.contains(&id.to_lowercase())|| CASE_SENSITIVE_ILLEGAL_IDS.contains(id)}diff --git a/rust/personhog-identity/src/service/get_or_create.rs b/rust/personhog-identity/src/service/get_or_create.rsindex b1694e963d6f..799b26e0b1b0 100644--- a/rust/personhog-identity/src/service/get_or_create.rs+++ b/rust/personhog-identity/src/service/get_or_create.rs@@ -210,6 +210,8 @@ impl PersonHogIdentityService {}let request = UpdatePersonPropertiesRequest {+ // Creation properties persist regardless of the filtered list.+ force_update: true,team_id: person.team_id,person_id: person.id,event_name: entry.event_name.clone(),@@ -243,6 +245,8 @@ impl PersonHogIdentityService {return Err(status);}let retry = UpdatePersonPropertiesRequest {+ // Creation properties persist regardless of the filtered list.+ force_update: true,team_id: current.team_id,person_id: current.id,..requestdiff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rsindex 15132dead98d..885211c87c32 100644--- a/rust/personhog-identity/src/service/merge.rs+++ b/rust/personhog-identity/src/service/merge.rs@@ -9,6 +9,7 @@ use std::collections::HashMap;use std::sync::Arc;use chrono::{DateTime, Utc};+use personhog_common::persons::person_uuid;use personhog_common::properties::sanitize_for_jsonb;use serde_json::Value;use tonic::Status;@@ -22,8 +23,9 @@ use crate::leader::PropertyWriter;use crate::lifecycle::engine::OpRow;use crate::lifecycle::merge::{record_outcome_count, MergeOpExecutor, MergeOutcome, MergeRequest, MergeSourceEntry,- OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON,+ MergeSourceRecord, OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON,OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_MOVE_LIMIT,+ OUTCOME_SKIPPED_REFUSED,};use crate::lifecycle::validation::{is_distinct_id_illegal, is_distinct_id_oversized, validate_merge_persons,@@ -38,7 +40,6 @@ const MERGE_SOURCES_PER_CALL: &str = "personhog_identity_merge_sources_per_call"const PAYLOAD_NUL_SANITIZED_TOTAL: &str = "personhog_identity_merge_payload_nul_sanitized_total";const PAYLOAD_NUMBERS_CLAMPED_TOTAL: &str ="personhog_identity_merge_payload_numbers_clamped_total";-/// The full MergePersons flow, owned by the identity side of the crate.pub struct MergeEntrance {storage: Arc<dyn IdentityStorage>,@@ -97,10 +98,19 @@ impl MergeEntrance {// classify divergently and the insert loser then sees the engine's// full-request mismatch; that surfaces as retryable UNAVAILABLE// (see MergeOpExecutor::execute) and the retry attaches here.- if let Some(row) = self.ops.find(op_id).await? {+ let mut existing = self.ops.find(op_id).await?;+ // A claim abort is disposable; checked before the request+ // comparison so any request may reuse the id once it is gone.+ if let Some(row) = &existing {+ if MergeOpExecutor::is_claim_abort(row) {+ self.ops.discard_claim_abort(op_id).await?;+ existing = None;+ }+ }+ if let Some(row) = existing {if row.op_type != OP_TYPE_MERGE|| row.team_id != request.team_id- || row.request.get("original") != Some(&original)+ || !same_merge(row.request.get("original"), &original){return Err(personhog_common::grpc::semantic_refusal(format!("op_id {op_id} was already used for a different request"),@@ -110,6 +120,8 @@ impl MergeEntrance {let frozen = row.request.clone();let row = self.ops.execute(op_id, row.team_id, &frozen).await?;let delivered = self.deliver_aborted_writes(&request, &row).await?;+ // Drives the recorded op with its own frozen request, never+ // reclassified; properties apply only where the op aborted.return merge_response(&row, delivered);}@@ -117,14 +129,20 @@ impl MergeEntrance {// never needs the saga, collect the two-person set (the only// destructive shape). The saga re-resolves// authoritatively at claim time; this pass only decides shape.+ //+ // Illegal and oversized sources settle before resolution, so a+ // caller cannot pump arbitrarily large ids through the primary.+ let mut inline_results: HashMap<String, String> = HashMap::new();let mut keys: Vec<(i64, String)> =vec![(request.team_id, request.target_distinct_id.clone())];- keys.extend(- request- .sources- .iter()- .map(|s| (request.team_id, s.source_distinct_id.clone())),- );+ for source in &request.sources {+ let did = &source.source_distinct_id;+ if is_distinct_id_illegal(did) || is_distinct_id_oversized(did) {+ inline_results.insert(did.clone(), OUTCOME_SKIPPED_ILLEGAL.to_string());+ } else {+ keys.push((request.team_id, did.clone()));+ }+ }let resolved = self.storage.resolve_distinct_ids(&keys)@@ -132,21 +150,17 @@ impl MergeEntrance {.map_err(|e| Status::internal(format!("resolution failed: {e}")))?;let target_key = (request.team_id, request.target_distinct_id.clone());- let target_person = match resolved.get(&target_key) {- Some(target) => target.clone(),+ let (target_person, target_was_born) = match resolved.get(&target_key) {+ Some(target) => (target.clone(), false),None => self.establish_target(&request, &resolved).await?,};- let mut inline_results: HashMap<String, String> = HashMap::new();let mut attach: Vec<String> = Vec::new();let mut saga_sources: Vec<MergeSourceEntry> = Vec::new();for source in &request.sources {let did = &source.source_distinct_id;- // Oversized ids share the illegal settlement: they cannot- // exist in the varchar(400) column, so they can never resolve- // — and attaching one would fail the insert.- if is_distinct_id_illegal(did) || is_distinct_id_oversized(did) {- inline_results.insert(did.clone(), OUTCOME_SKIPPED_ILLEGAL.to_string());+ // Illegal and oversized sources settled before resolution.+ if inline_results.contains_key(did.as_str()) {continue;}match resolved.get(&(request.team_id, did.clone())) {@@ -215,20 +229,23 @@ impl MergeEntrance {.values().any(|o| o == OUTCOME_ATTACHED || o == OUTCOME_NOOP_SAME_PERSON);let pushed = self- .push_event_properties(&request, &target_person, flip_identified)+ .push_event_properties(&request, &target_person, flip_identified, target_was_born).await?;let results = request.sources.iter()- .map(|s| MergeSourceResult {- source_distinct_id: s.source_distinct_id.clone(),- outcome: outcome_enum(- inline_results- .get(&s.source_distinct_id)- .map(String::as_str)- .unwrap_or(OUTCOME_ERROR),- )- .into(),+ .map(|s| {+ let outcome = inline_results+ .get(&s.source_distinct_id)+ .map(String::as_str)+ .unwrap_or(OUTCOME_ERROR);+ MergeSourceResult {+ source_distinct_id: s.source_distinct_id.clone(),+ outcome: outcome_enum(outcome).into(),+ // Nothing was destroyed, so there is no id to report.+ source_person_id: None,+ settled: outcome_settled(outcome),+ }}).collect();return Ok(MergePersonsResponse {@@ -248,6 +265,8 @@ impl MergeEntrance {event_set_once,allow_identified_sources: request.allow_identified_sources,move_limit,+ creator_event_uuid: request.creator_event_uuid.clone(),+ target_born: target_was_born,};let mut frozen = serde_json::to_value(&merge_request).map_err(|e| Status::internal(format!("failed to freeze request: {e}")))?;@@ -269,7 +288,8 @@ impl MergeEntrance {/// is not consulted for the person, because the op that caused the/// abort may have settled the target away since. A push failure errors/// the call rather than answering OK with lost writes; the retry- /// attaches to the aborted op and re-drives this delivery.+ /// re-drives this delivery (a discarded claim abort re-runs the whole+ /// call instead).async fn deliver_aborted_writes(&self,request: &MergePersonsRequest,@@ -298,34 +318,56 @@ impl MergeEntrance {};// A saga only exists for legal resolved pairs, and ingestion marks// the target identified for any legal pair regardless of the merge- // outcome, so the flip always accompanies the delivery.- let pushed = self.push_event_properties(request, &survivor, true).await?;+ // outcome, so the flip always accompanies the delivery. The uuid+ // check keeps the born stamp off a person the newborn was settled+ // into before this resolve.+ let was_born = row+ .request+ .get("target_born")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ && survivor.uuid == person_uuid(request.team_id, &request.target_distinct_id);+ let pushed = self+ .push_event_properties(request, &survivor, true, was_born)+ .await?;Ok(Some(pushed.unwrap_or_else(|| survivor.into())))}/// Apply the merge event's $set/$set_once and the identified flip to- /// the survivor when no saga runs (the fold carries both when one- /// does). The ack means the changes are durable in the changelog.- /// Skipped entirely when there is nothing to change — a repeat- /// identify of an already-identified survivor with no new properties- /// costs no leader round trip.+ /// the survivor; a completing saga carries both through the fold+ /// instead. The ack means durability in the changelog.async fn push_event_properties(&self,request: &MergePersonsRequest,survivor: &Person,flip_identified: bool,+ was_born: bool,) -> Result<Option<ProtoPerson>, Status> {let flip = flip_identified && !survivor.is_identified;- if request.event_set.is_empty() && request.event_set_once.is_empty() && !flip {+ // Only a just-birthed person records its creating event. It+ // travels in $set because a stub never reaches the changelog.+ let stamp_creator = was_born && !request.creator_event_uuid.is_empty();+ if request.event_set.is_empty()+ && request.event_set_once.is_empty()+ && !flip+ && !stamp_creator+ {return Ok(None);}+ let set = if stamp_creator {+ with_creator_event_uuid(&request.event_set, &request.creator_event_uuid)?+ } else {+ request.event_set.clone()+ };let response = self.property_writer.update_person_properties(UpdatePersonPropertiesRequest {+ // Forced: the Postgres backend applies these inside the merge.+ force_update: true,team_id: request.team_id,person_id: survivor.id,event_name: "$identify".to_string(),- set_properties: request.event_set.clone(),+ set_properties: set,set_once_properties: request.event_set_once.clone(),unset_properties: Vec::new(),is_identified: flip.then_some(true),@@ -349,7 +391,7 @@ impl MergeEntrance {&self,request: &MergePersonsRequest,resolved: &HashMap<(i64, String), Person>,- ) -> Result<Person, Status> {+ ) -> Result<(Person, bool), Status> {let target_did = &request.target_distinct_id;// Eligibility applies the identified-source policy here, not just@@ -376,11 +418,11 @@ impl MergeEntrance {.await.map_err(|e| Status::internal(format!("target attach failed: {e}")))?;return match attached.get(target_did) {- Some(AttachOutcome::Attached { .. }) => Ok(survivor.clone()),+ Some(AttachOutcome::Attached { .. }) => Ok((survivor.clone(), false)),// The target distinct id got mapped concurrently; that// mapping wins and its person is the survivor.Some(AttachOutcome::AlreadyMapped { .. }) => {- self.resolve_target_after_race(request).await+ Ok((self.resolve_target_after_race(request).await?, false))}// The survivor row vanished under the attach (a racing// lifecycle op committed). Nothing durable happened for@@ -418,8 +460,12 @@ impl MergeEntrance {.await.map_err(|e| Status::internal(format!("target creation failed: {e}")))?;match outcomes.into_iter().next() {- Some(StubOutcome::Committed { person, .. }) => Ok(person),- Some(StubOutcome::LostRace) | None => self.resolve_target_after_race(request).await,+ // A rival's insert winning the row makes this call not the creator.+ Some(StubOutcome::Committed { person, created }) => Ok((person, created)),+ // The race winner's person keeps its own establishment's creator.+ Some(StubOutcome::LostRace) | None => {+ Ok((self.resolve_target_after_race(request).await?, false))+ }}}@@ -443,6 +489,23 @@ impl MergeEntrance {}}+/// The event's `$set` map with `$creator_event_uuid` added for a+/// just-birthed person. It overwrites: the event does not name its own creator.+// See `MergeEntrance::handle` for why result_large_err is allowed.+#[allow(clippy::result_large_err)]+fn with_creator_event_uuid(set: &[u8], creator_event_uuid: &str) -> Result<Vec<u8>, Status> {+ let mut value = parse_json_map(set, "event_set")?;+ let map = value+ .as_object_mut()+ .expect("parse_json_map returns an object");+ map.insert(+ "$creator_event_uuid".to_string(),+ Value::String(creator_event_uuid.to_string()),+ );+ serde_json::to_vec(&value)+ .map_err(|e| Status::internal(format!("failed to serialize event_set: {e}")))+}+/// Decode a JSON-map wire field (empty bytes mean an empty map).// See `MergeEntrance::handle` for why result_large_err is allowed.#[allow(clippy::result_large_err)]@@ -470,9 +533,9 @@ fn merge_original(event_set: &Value,event_set_once: &Value,) -> Value {- // event_uuid is deliberately absent: the proto documents it as- // advisory data the merge never reads, so a retry that regenerated- // its event uuids must still match the recorded request.+ // event_uuid and creator_event_uuid are advisory: a retry that+ // regenerated either must still match, and a mismatch here would be+ // a terminal refusal. Ownership keys on the op id.serde_json::json!({"target_distinct_id": request.target_distinct_id,"sources": request@@ -488,6 +551,35 @@ fn merge_original(})}+/// Fields that describe how a merge runs, not which merge it is; they+/// drift between deliveries, so they are excluded from the comparison+/// (a replay still delivers them). `move_limit` is folded into the op id.+const MERGE_PARAMETERS: [&str; 3] = ["created_at", "event_set", "event_set_once"];++/// Whether a retry describes the recorded merge; see MERGE_PARAMETERS.+fn same_merge(recorded: Option<&Value>, incoming: &Value) -> bool {+ let strip = |value: &Value| {+ let mut copy = value.clone();+ if let Some(map) = copy.as_object_mut() {+ for key in MERGE_PARAMETERS {+ map.remove(key);+ }+ }+ copy+ };+ match recorded {+ Some(recorded) => strip(recorded) == strip(incoming),+ None => false,+ }+}++/// The caller's durability decision: every outcome is final under retry+/// except a claim conflict, and only where a retry actually re-runs it+/// (a discarded claim abort, or an inline answer with no op row).+fn outcome_settled(outcome: &str) -> bool {+ outcome != OUTCOME_SKIPPED_CONFLICT+}+fn outcome_enum(outcome: &str) -> MergeSourceOutcome {match outcome {OUTCOME_MERGED => MergeSourceOutcome::Merged,@@ -497,6 +589,7 @@ fn outcome_enum(outcome: &str) -> MergeSourceOutcome {OUTCOME_SKIPPED_ALREADY_IDENTIFIED => MergeSourceOutcome::SkippedAlreadyIdentified,OUTCOME_SKIPPED_CONFLICT => MergeSourceOutcome::SkippedConflict,OUTCOME_SKIPPED_MOVE_LIMIT => MergeSourceOutcome::SkippedMoveLimit,+ OUTCOME_SKIPPED_REFUSED => MergeSourceOutcome::SkippedRefused,OUTCOME_ERROR => MergeSourceOutcome::Error,_ => MergeSourceOutcome::Unspecified,}@@ -512,6 +605,8 @@ fn survivor_to_proto(survivor: &Value, team_id: i64) -> ProtoPerson {team_id,properties: serde_json::to_vec(&survivor["properties"]).unwrap_or_default(),created_at: survivor["created_at"].as_i64().unwrap_or_default(),+ // Older records and creator-less folds both read as unset.+ last_seen_at: survivor["last_seen_at"].as_i64(),version: survivor["version"].as_i64().unwrap_or_default(),is_identified: survivor["is_identified"].as_bool().unwrap_or(true),..Default::default()@@ -537,10 +632,10 @@ fn merge_response(};let outcome: MergeOutcome = serde_json::from_value(outcome.clone()).map_err(|e| Status::internal(format!("op {} outcome is malformed: {e}", row.op_id)))?;- let saga_results: HashMap<&str, &str> = outcome+ let saga_results: HashMap<&str, &MergeSourceRecord> = outcome.results.iter()- .map(|r| (r.distinct_id.as_str(), r.outcome.as_str()))+ .map(|r| (r.distinct_id.as_str(), r)).collect();let inline_results: HashMap<String, String> = row.request@@ -574,17 +669,28 @@ fn merge_response(Status::internal(format!("op {} original sources are malformed", row.op_id))})?;+ // Only a claim-aborted row is discarded on re-presentation; any other+ // terminal row replays verbatim, so its every answer is settled.+ let redrivable = MergeOpExecutor::is_claim_abort(row);let results = original_sources.iter().map(|did| {+ let record = saga_results.get(did.as_str());let outcome = inline_results.get(did).map(String::as_str)- .or_else(|| saga_results.get(did.as_str()).copied())+ .or_else(|| record.map(|r| r.outcome.as_str())).unwrap_or(OUTCOME_ERROR);MergeSourceResult {source_distinct_id: did.clone(),outcome: outcome_enum(outcome).into(),+ settled: outcome_settled(outcome) || !redrivable,+ // Only a merged source names a person, because only that+ // person is permanently gone.+ source_person_id: match outcome {+ OUTCOME_MERGED => record.and_then(|r| r.person_id),+ _ => None,+ },}}).collect();diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rsindex 5fa876052e98..1732988694b0 100644--- a/rust/personhog-identity/src/storage/postgres/attach.rs+++ b/rust/personhog-identity/src/storage/postgres/attach.rs@@ -17,13 +17,9 @@ use crate::storage::types::AttachOutcome;/// Callers dedupe; sorted insert order keeps row locks deadlock-free.////// Two guards keep a racing lifecycle op from acquiring a mapping it can-/// no longer sweep. The join on a live person row rejects committed-/// deletions. The mark check rejects persons held by a live op: the-/// destructive transaction sweeps the person's distinct ids before it-/// tombstones the person, so an attach overlapping it would insert a row-/// the sweep already missed — a live mapping onto a tombstoned person.-/// The saga commits its mark before any destructive statement, so an-/// attach that could land in that window always observes the mark.+/// no longer sweep: the join rejects committed deletions, and the mark+/// check rejects persons held by a live op. The rare statement that slips+/// both leaves an orphaned mapping the next resolve treats as absent.pub(super) async fn attach_distinct_ids(pool: &PgPool,tables: &IdentityTables,diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex e8d92b0e5648..7f513ddd6e59 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -103,6 +103,7 @@ impl TestContext {execute_timeout: std::time::Duration::from_secs(10),poll_interval: std::time::Duration::from_millis(25),attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,},)}@@ -312,6 +313,9 @@ pub struct RacingStorage {/// create_person_stubs: commit the stub as a concurrent winner and/// answer LostRace.pub lose_create_race: std::sync::Mutex<bool>,+ /// Every key passed to resolve_distinct_ids, for tests that pin what+ /// does and does not reach the resolution query.+ pub resolved_keys: std::sync::Mutex<Vec<(i64, String)>>,}impl RacingStorage {@@ -321,6 +325,7 @@ impl RacingStorage {hijack_attach_to: std::sync::Mutex::new(None),vanish_attach: std::sync::Mutex::new(false),lose_create_race: std::sync::Mutex::new(false),+ resolved_keys: std::sync::Mutex::new(Vec::new()),}}}@@ -333,6 +338,10 @@ impl personhog_identity::storage::IdentityStorage for RacingStorage {) -> personhog_identity::storage::StorageResult<std::collections::HashMap<(i64, String), personhog_identity::storage::Person>,> {+ self.resolved_keys+ .lock()+ .unwrap()+ .extend(keys.iter().cloned());self.inner.resolve_distinct_ids(keys).await}diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rsindex 7bbafe3bf143..c22eb2c04fa9 100644--- a/rust/personhog-identity/tests/common/sim_leader.rs+++ b/rust/personhog-identity/tests/common/sim_leader.rs@@ -164,6 +164,16 @@ impl SimLeader {.push_back(status);}+ /// Whether every scripted failure for this key has been consumed. Lets a+ /// test tell a rejected call from a call that never happened.+ pub fn scripted_drained(&self, rpc: Rpc, person_id: i64) -> bool {+ self.scripted+ .lock()+ .unwrap()+ .get(&(rpc, person_id))+ .is_none_or(|queue| queue.is_empty())+ }+pub fn set_sealed_identified(&self, person_id: i64, identified: bool) {self.sealed_identified.lock()@@ -549,9 +559,54 @@ impl PropertyWriter for SimLeader {.live_person(request.team_id, request.person_id).await.ok_or_else(|| Status::not_found("person is destroyed"))?;- // The real leader OR-merges the flip and answers with the updated- // person; the flip reaches Postgres through the changelog, not here.- person.is_identified = person.is_identified || request.is_identified == Some(true);+ // Properties are applied and persisted, because the seal reads them+ // back out of Postgres: without this the sim cannot tell a write+ // that landed from one that was never sent, which is exactly what+ // the carried-operation path needs to prove.+ let decode = |bytes: &[u8]| {+ serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(bytes)+ .unwrap_or_default()+ };+ let mut properties = decode(&person.properties);+ // The real leader's $unset removes only keys present BEFORE the op,+ // so a pair (set/set_once and unset of one key in one op) keeps the+ // written value where the key was absent. Mirrored here or a+ // carried-pair test would certify the wrong semantics.+ let present_before: std::collections::HashSet<String> =+ properties.keys().cloned().collect();+ for (key, value) in decode(&request.set_once_properties) {+ properties.entry(key).or_insert(value);+ }+ for (key, value) in decode(&request.set_properties) {+ properties.insert(key, value);+ }+ for key in &request.unset_properties {+ if present_before.contains(key) {+ properties.remove(key);+ }+ }+ let encoded = serde_json::Value::Object(properties);+ // The identity flip persists too, because the seal reads the row:+ // a carried is_identified that the real leader would surface at+ // fence time has to be visible to the saga's identified re-check,+ // or the one interaction the flip exists for goes unmodeled.+ let flip = request.is_identified == Some(true);+ let update_sql = format!(+ "UPDATE {person_table} SET properties = $3::jsonb, is_identified = is_identified OR $4 \+ WHERE team_id = $1 AND id = $2",+ person_table = self.person_table,+ );+ sqlx::query(&update_sql)+ .bind(request.team_id as i32)+ .bind(request.person_id)+ .bind(&encoded)+ .bind(flip)+ .execute(&self.pool)+ .await+ .expect("property write");+ person.properties = serde_json::to_vec(&encoded).expect("serialize properties");+ // The real leader OR-merges the flip and answers with the updated person.+ person.is_identified = person.is_identified || flip;self.record(LeaderCall::PropertyPush {person_id: request.person_id,is_identified: request.is_identified,diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rsindex 4f7a103d0158..7643ed05f458 100644--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs@@ -304,6 +304,7 @@ async fn a_live_lease_blocks_a_second_driver_until_it_lapses() {execute_timeout: std::time::Duration::from_millis(200),poll_interval: std::time::Duration::from_millis(25),attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,},);let err = short_engine@@ -320,6 +321,62 @@ async fn a_live_lease_blocks_a_second_driver_until_it_lapses() {ctx.cleanup().await.expect("cleanup");}+/// Sleeps through the execute deadline without ever advancing, modeling+/// a wedged step under a held claim.+struct SlowDriver;++#[async_trait]+impl OpDriver for SlowDriver {+ fn op_type(&self) -> &'static str {+ "merge"+ }++ fn initial_step(&self) -> &'static str {+ "started"+ }++ async fn run_step(&self, _pool: &PgPool, _op: &OpRow) -> Result<(), SagaError> {+ tokio::time::sleep(std::time::Duration::from_millis(400)).await;+ Ok(())+ }+}++#[tokio::test]+async fn a_drive_that_runs_out_its_own_deadline_says_so_and_releases_the_lease() {+ let ctx = TestContext::new().await;+ let op_id = Uuid::now_v7();++ let short_engine = personhog_identity::lifecycle::engine::Engine::new(+ ctx.pool.clone(),+ personhog_identity::lifecycle::engine::EngineConfig {+ lease: std::time::Duration::from_secs(5),+ execute_timeout: std::time::Duration::from_millis(200),+ poll_interval: std::time::Duration::from_millis(25),+ attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,+ },+ );++ // The claim was ours the whole time, so the answer must not blame a+ // contending instance that does not exist; and the lease releases so+ // the retry is not locked out for a lease term on top.+ let err = short_engine+ .execute(&SlowDriver, op_id, ctx.team_id, &json!({}))+ .await+ .expect_err("the slow drive runs out its deadline");+ assert!(matches!(err, SagaError::DeadlineElapsed));+ let lease_live: bool = sqlx::query_scalar(+ "SELECT lease_expires_at IS NOT NULL AND lease_expires_at >= now() FROM lifecycle_op WHERE op_id = $1",+ )+ .bind(op_id)+ .fetch_one(&ctx.pool)+ .await+ .expect("op row exists");+ assert!(!lease_live, "the deadline return released the lease");++ ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn resume_bails_immediately_when_another_driver_holds_the_lease() {let ctx = TestContext::new().await;@@ -424,6 +481,7 @@ async fn a_driver_whose_lease_was_stolen_stops_running_steps_instead_of_renewingexecute_timeout: std::time::Duration::from_millis(200),poll_interval: std::time::Duration::from_millis(25),attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,},);let err = short_enginediff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsindex fde2a9631605..8247da8da218 100644--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -20,11 +20,12 @@ use personhog_common::grpc::semantic_refusal;use personhog_common::persons::person_uuid;use serde_json::json;use sqlx::postgres::PgPool;+use sqlx::Row;use tonic::{Code, Status};use uuid::Uuid;use personhog_identity::lifecycle::engine::{- Engine, OpRow, SagaError, STEP_ABORTED, STEP_COMPLETED,+ Engine, OpDriver, OpRow, SagaError, STEP_ABORTED, STEP_COMPLETED,};use personhog_identity::lifecycle::merge::{MergeDriver, MergeOutcome, MergeRequest, MergeSourceEntry, OUTCOME_MERGED,@@ -253,6 +254,8 @@ fn merge_request(target: &str, sources: &[&str]) -> MergeRequest {event_set_once: json!({}),allow_identified_sources: false,move_limit: 1_000,+ creator_event_uuid: String::new(),+ target_born: false,}}@@ -264,6 +267,110 @@ fn result_map(outcome: &MergeOutcome) -> HashMap<String, String> {.collect()}+/// A person carrying the uuid establishment derives for `distinct_id`;+/// `with_mapping` controls whether the distinct id row is written too.+async fn insert_person_with_derived_uuid(+ ctx: &TestContext,+ distinct_id: &str,+ with_mapping: bool,+) -> i64 {+ let insert_sql = format!(+ r#"+ INSERT INTO {}+ (created_at, properties, properties_last_updated_at, properties_last_operation,+ team_id, is_identified, uuid, version)+ VALUES (now(), '{{}}'::jsonb, '{{}}'::jsonb, '{{}}'::jsonb, $1, false, $2, 0)+ RETURNING id+ "#,+ ctx.tables.person+ );+ let person_id: i64 = sqlx::query_scalar(&insert_sql)+ .bind(ctx.team_id as i32)+ .bind(person_uuid(ctx.team_id, distinct_id))+ .fetch_one(&ctx.pool)+ .await+ .expect("insert person");+ if with_mapping {+ let pdi_sql = format!(+ "INSERT INTO {} (distinct_id, person_id, team_id, version) VALUES ($1, $2, $3, 0)",+ ctx.tables.person_distinct_id+ );+ sqlx::query(&pdi_sql)+ .bind(distinct_id)+ .bind(person_id)+ .bind(ctx.team_id as i32)+ .execute(&ctx.pool)+ .await+ .expect("insert mapping");+ }+ person_id+}++#[tokio::test]+async fn a_completing_fold_stamps_a_born_targets_creating_event() {+ // The frozen request says establishment birthed the target; the source+ // was classified refused but recycled to a claimable person before the+ // claim's authoritative re-resolve, so the saga completes.+ let h = MergeHarness::new().await;+ let _target = insert_person_with_derived_uuid(&h.ctx, "born-target", true).await;+ let _source = h.ctx.insert_person_with_distinct_id("born-source").await;++ let mut request = merge_request("born-target", &["born-source"]);+ request.creator_event_uuid = "88888888-8888-8888-8888-888888888888".to_string();+ request.target_born = true;+ let outcome = h+ .execute(Uuid::now_v7(), &request)+ .await+ .expect("merge completes");++ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("born-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ let survivor = outcome+ .survivor+ .expect("committed merges carry the survivor");+ assert_eq!(+ survivor["properties"]["$creator_event_uuid"],+ json!("88888888-8888-8888-8888-888888888888")+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_completing_fold_leaves_a_moved_away_target_unstamped() {+ // The claimed target is not the person this call birthed (the newborn+ // was settled away and the did re-resolved before the claim), so the+ // fold must not overwrite that person's own creating event.+ let h = MergeHarness::new().await;+ let _target = h+ .ctx+ .insert_person_with_distinct_id("moved-fold-target")+ .await;+ let _source = h+ .ctx+ .insert_person_with_distinct_id("moved-fold-source")+ .await;++ let mut request = merge_request("moved-fold-target", &["moved-fold-source"]);+ request.creator_event_uuid = "88888888-8888-8888-8888-888888888888".to_string();+ request.target_born = true;+ let outcome = h+ .execute(Uuid::now_v7(), &request)+ .await+ .expect("merge completes");++ assert!(!outcome.aborted);+ let survivor = outcome+ .survivor+ .expect("committed merges carry the survivor");+ assert!(survivor["properties"].get("$creator_event_uuid").is_none());++ h.ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {let h = MergeHarness::new().await;@@ -863,49 +970,72 @@ async fn a_leader_refusal_at_release_parks_the_op_until_an_explicit_retry() {}#[tokio::test]-async fn a_leader_refusal_at_fold_aborts_and_releases_the_fences() {+async fn a_stale_drivers_fold_refusal_defers_instead_of_unfencing_the_new_owners_sources() {let h = MergeHarness::new().await;- let team = h.ctx.team_id;- let source = h.ctx.insert_person_with_distinct_id("fabort-source").await;- let target = h.ctx.insert_person_with_distinct_id("fabort-target").await;+ let source = h.ctx.insert_person_with_distinct_id("stale-source").await;+ let target = h.ctx.insert_person_with_distinct_id("stale-target").await;let op_id = Uuid::now_v7();- let request = merge_request("fabort-target", &["fabort-source"]);- // The real leader's fold-unverified shape (the fold matches on the- // target's id).+ let request = merge_request("stale-target", &["stale-source"]);+ h.create(op_id, &request).await;+ h.step(op_id).await.expect("claim");+ let row = h.step(op_id).await.expect("seal");+ assert_eq!(row.step, "sources_sealed");++ // This drive's snapshot of the row, taken before another driver+ // steals its lapsed lease and flips the op.+ let stale = sqlx::query("SELECT request, created_at FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(&h.ctx.pool)+ .await+ .expect("row exists");+ let stale_row = OpRow {+ op_id,+ op_type: "merge".to_string(),+ team_id: h.ctx.team_id,+ step: "sources_sealed".to_string(),+ attempt: 1,+ request: stale.get("request"),+ outcome: None,+ created_at: stale.get("created_at"),+ completed_at: None,+ lease_live: false,+ };+ sqlx::query("UPDATE lifecycle_op SET step = 'flipped' WHERE op_id = $1")+ .bind(op_id)+ .execute(&h.ctx.pool)+ .await+ .expect("the stealer's flip commits");+ // The stealer's fold already verified; the stale driver's late fold+ // draws the real leader's fold-unverified shape.h.leader.fail_next(Rpc::Fold,target,semantic_refusal("injected fold refusal", "fold-unverified"),);- // Pre-flip the refused call wrote nothing, so the op backs out- // instead of parking: a terminal aborted outcome, not an error.- let outcome = h- .execute(op_id, &request)+ // Aborting would release the sources' fences — the leader's aborted+ // release verifies nothing beyond the op id, which matches — between+ // the stealer's flip and its death documents, where an acked write+ // could land and be destroyed. The stale drive defers to the row.+ let err = h+ .driver+ .run_step(&h.ctx.pool, &stale_row).await- .expect("the refusal aborts the op cleanly");- assert!(outcome.aborted);- let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;- assert_eq!(step, STEP_ABORTED);- assert!(completed);+ .expect_err("the stale drive defers rather than settling");+ assert!(matches!(err, SagaError::Busy));assert!(- !parked_state(&h.ctx.pool, op_id).await.0,- "a pre-flip refusal aborts; it never parks"+ h.leader.fence_for(source).is_some(),+ "the fence stays held for the op's new owner");-- // The unwind is complete: fence released, marks settled, both persons- // untouched and writable again.- assert!(h.leader.fence_for(source).is_none());- h.leader- .admit_write(team, source)- .await- .expect("the source unfroze");- assert_eq!(h.op_person_status(op_id, source).await, "aborted");- assert_eq!(h.op_person_status(op_id, target).await, "cleared");- let (source_deleted, _, _) = h.person_state(source).await;- assert!(!source_deleted, "no person was destroyed");- assert_eq!(h.pdi_state("fabort-source").await.0, source);+ assert_eq!(+ h.op_person_status(op_id, source).await,+ "sealed",+ "nothing was unwound"+ );+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, "flipped", "the stealer's progress stands");+ assert!(!completed);assert!(h.leader.death_documents().is_empty());h.ctx.cleanup().await.expect("cleanup");@@ -958,6 +1088,7 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {execute_timeout: std::time::Duration::from_secs(10),poll_interval: std::time::Duration::from_millis(25),attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,},);let resumed = sweep_engine.sweep(&[&h.driver]).await.expect("sweep runs");@@ -1036,6 +1167,15 @@ async fn a_fold_without_a_live_target_mark_is_refused_and_the_op_aborts() {.expect("the refused fold aborts cleanly");assert_eq!(row.step, STEP_ABORTED);assert!(row.completed_at.is_some());+ // A slugged refusal is a definitive verdict, not contention: recorded+ // as a conflict, the caller would salt retries that abort identically+ // and then misfile the loss as a claim race. Its own verdict name+ // keeps it apart from a completed operation's indeterminate source.+ let outcome = row+ .outcome+ .as_ref()+ .expect("a terminal op records its outcome");+ assert_eq!(outcome["results"][0]["outcome"], "skipped_refused");assert!(!parked_state(&h.ctx.pool, op_id).await.0);assert!(h.leader.fence_for(source).is_none(),@@ -1578,6 +1718,7 @@ fn rpc_request(team_id: i64, target: &str, sources: &[&str], op_id: Uuid) -> Merallow_identified_sources: false,move_limit: Some(1_000),created_at: 0,+ creator_event_uuid: String::new(),}}@@ -1590,6 +1731,184 @@ fn rpc_outcomes(response: &MergePersonsResponse) -> Vec<(String, MergeSourceOutc}#[tokio::test]+async fn a_conflict_is_not_recorded_and_a_plain_retry_merges_once_released() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("cr-target").await;+ let source = h.ctx.insert_person_with_distinct_id("cr-source").await;++ // A rival live op holds the source's mark.+ let rival = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at) VALUES ($1, 'merge', $2, 'claimed', '{}'::jsonb, now() + interval '1 hour')",+ )+ .bind(rival)+ .bind(h.ctx.team_id as i32)+ .execute(&h.ctx.pool)+ .await+ .expect("insert rival op");+ sqlx::query(+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) VALUES ($1, $2, $3, gen_random_uuid(), 'source', 'marked')",+ )+ .bind(rival)+ .bind(h.ctx.team_id as i32)+ .bind(source)+ .execute(&h.ctx.pool)+ .await+ .expect("insert rival mark");++ let op_id = Uuid::now_v7();+ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "cr-target",+ &["cr-source"],+ op_id,+ )))+ .await+ .expect("conflict answers, not errors")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&response),+ vec![("cr-source".to_string(), MergeSourceOutcome::SkippedConflict)]+ );+ // The conflict is the one unsettled verdict: a retry may genuinely+ // succeed, and the caller redelivers rather than acking a loss.+ assert!(!response.results[0].settled);++ // The rival releases; a retry under the SAME op id must re-run the+ // merge rather than replaying the recorded contention.+ sqlx::query("UPDATE lifecycle_op_person SET status = 'cleared' WHERE op_id = $1")+ .bind(rival)+ .execute(&h.ctx.pool)+ .await+ .expect("release rival mark");++ let retry = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "cr-target",+ &["cr-source"],+ op_id,+ )))+ .await+ .expect("retry merges")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ vec![("cr-source".to_string(), MergeSourceOutcome::Merged)]+ );+ assert!(retry.results[0].settled);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_completed_op_answers_its_embedded_conflict_settled() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("emb-target").await;+ let held = h.ctx.insert_person_with_distinct_id("emb-held").await;+ let _free = h.ctx.insert_person_with_distinct_id("emb-free").await;++ let rival = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at) VALUES ($1, 'merge', $2, 'claimed', '{}'::jsonb, now() + interval '1 hour')",+ )+ .bind(rival)+ .bind(h.ctx.team_id as i32)+ .execute(&h.ctx.pool)+ .await+ .expect("insert rival op");+ sqlx::query(+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) VALUES ($1, $2, $3, gen_random_uuid(), 'source', 'marked')",+ )+ .bind(rival)+ .bind(h.ctx.team_id as i32)+ .bind(held)+ .execute(&h.ctx.pool)+ .await+ .expect("insert rival mark");++ // The free source completes the saga, freezing the held source's+ // conflict in the terminal record.+ let op_id = Uuid::now_v7();+ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "emb-target",+ &["emb-held", "emb-free"],+ op_id,+ )))+ .await+ .expect("merge completes around the held source")+ .into_inner();+ let outcomes: HashMap<String, MergeSourceOutcome> =+ rpc_outcomes(&response).into_iter().collect();+ assert_eq!(outcomes["emb-free"], MergeSourceOutcome::Merged);+ assert_eq!(outcomes["emb-held"], MergeSourceOutcome::SkippedConflict);+ // A completed op's answers replay verbatim forever, so the conflict is+ // settled: retrying this op id cannot change it.+ for result in &response.results {+ assert!(result.settled, "{} unsettled", result.source_distinct_id);+ }++ // Even released, a retry replays the frozen answer rather than+ // re-running the held pair.+ sqlx::query("UPDATE lifecycle_op_person SET status = 'cleared' WHERE op_id = $1")+ .bind(rival)+ .execute(&h.ctx.pool)+ .await+ .expect("release rival mark");+ let retry = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "emb-target",+ &["emb-held", "emb-free"],+ op_id,+ )))+ .await+ .expect("retry attaches")+ .into_inner();+ let replayed: HashMap<String, MergeSourceOutcome> = rpc_outcomes(&retry).into_iter().collect();+ assert_eq!(replayed["emb-held"], MergeSourceOutcome::SkippedConflict);+ assert!(retry.results.iter().all(|r| r.settled));++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_saga_survivor_carries_the_folded_last_seen_at() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("seen-target").await;+ let source = h.ctx.insert_person_with_distinct_id("seen-source").await;+ h.leader.set_last_seen(target, 1_000);+ h.leader.set_last_seen(source, 2_000);++ let request = rpc_request(+ h.ctx.team_id,+ "seen-target",+ &["seen-source"],+ Uuid::now_v7(),+ );+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("merge succeeds")+ .into_inner();++ // The saga records its survivor as JSON and rebuilds the wire person+ // from it, so a field the record leaves out reaches the caller as unset+ // however well the fold computed it.+ let survivor = response.survivor.expect("survivor present");+ assert_eq!(survivor.id, target);+ assert_eq!(survivor.last_seen_at, Some(2_000));++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test(flavor = "multi_thread")]async fn the_rpc_runs_the_saga_and_a_retry_returns_the_recorded_answer() {let h = MergeHarness::new().await;let service = h.service();@@ -1987,6 +2306,45 @@ async fn an_unresolved_target_attaches_to_the_first_resolved_sources_person() {h.ctx.cleanup().await.expect("cleanup");}+#[tokio::test]+async fn a_call_that_lost_the_birth_race_does_not_stamp_its_creator() {+ // The person already exists under the derived uuid with the distinct id+ // unmapped: establishment finds the row and only adds the mapping, so+ // this call is not the creator and must not stamp.+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = insert_person_with_derived_uuid(&h.ctx, "lost-target", false).await;+ let source = h+ .ctx+ .insert_person_with_distinct_id("lost-ident-source")+ .await;+ h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;++ let mut request = rpc_request(+ h.ctx.team_id,+ "lost-target",+ &["lost-ident-source"],+ Uuid::now_v7(),+ );+ request.creator_event_uuid = "66666666-6666-6666-6666-666666666666".to_string();+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("call succeeds")+ .into_inner();++ let survivor = response.survivor.expect("survivor present");+ assert_eq!(survivor.id, target);+ let properties: serde_json::Value = if survivor.properties.is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_slice(&survivor.properties).expect("properties are JSON")+ };+ assert_eq!(properties.get("$creator_event_uuid"), None);++ h.ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_target() {let h = MergeHarness::new().await;@@ -1997,13 +2355,15 @@ async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_targ.await;h.set_person(source, r#"{"plan": "pro"}"#, 3, true).await;+ let mut request = rpc_request(+ h.ctx.team_id,+ "elig-target",+ &["elig-ident-source"],+ Uuid::now_v7(),+ );+ request.creator_event_uuid = "77777777-7777-7777-7777-777777777777".to_string();let response = service- .merge_persons(Request::new(rpc_request(- h.ctx.team_id,- "elig-target",- &["elig-ident-source"],- Uuid::now_v7(),- )))+ .merge_persons(Request::new(request)).await.expect("call succeeds").into_inner();@@ -2025,6 +2385,17 @@ async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_targMergeSourceOutcome::SkippedAlreadyIdentified)]);+ // Establishment birthed the target, so the abort delivery stamps its+ // creating event.+ let born_properties: serde_json::Value = if survivor.properties.is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_slice(&survivor.properties).expect("survivor properties are JSON")+ };+ assert_eq!(+ born_properties.get("$creator_event_uuid"),+ Some(&serde_json::json!("77777777-7777-7777-7777-777777777777"))+ );assert_eq!(h.pdi_state("elig-target").await, (survivor.id, false, 0));assert_eq!(h.pdi_state("elig-ident-source").await.0, source);let (source_deleted, _, _) = h.person_state(source).await;@@ -2042,6 +2413,68 @@ async fn an_identified_source_is_not_an_eligible_survivor_for_an_unresolved_targh.ctx.cleanup().await.expect("cleanup");}+#[tokio::test]+async fn an_abort_redelivery_does_not_stamp_a_person_the_did_moved_to() {+ // A refused abort replays on attach, so its delivery re-runs against+ // whatever the distinct id resolves to now; a person other than the+ // newborn must not gain the creating event.+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("moved-target").await;+ let source = h.ctx.insert_person_with_distinct_id("moved-source").await;++ // Engine-stage the refused abort of a born-frozen op: the fence+ // refusal at the seal step aborts without the claim-abort discard.+ h.leader.fail_next(+ Rpc::Fence,+ source,+ semantic_refusal("injected fence refusal", "test-refusal"),+ );+ let op_id = Uuid::now_v7();+ let mut request = merge_request("moved-target", &["moved-source"]);+ request.creator_event_uuid = "55555555-5555-5555-5555-555555555555".to_string();+ request.target_born = true;+ let mut frozen = serde_json::to_value(&request).unwrap();+ frozen["original"] = json!({+ "target_distinct_id": "moved-target",+ "sources": ["moved-source"],+ "event_set": {},+ "event_set_once": {},+ "allow_identified_sources": false,+ "move_limit": 1000,+ "created_at": 0,+ });+ frozen["inline_results"] = json!({});+ let row = h+ .engine+ .execute(&h.driver, op_id, h.ctx.team_id, &frozen)+ .await+ .expect("the refusal aborts the op");+ assert_eq!(row.outcome.as_ref().unwrap()["aborted"], json!(true));++ let mut rpc = rpc_request(h.ctx.team_id, "moved-target", &["moved-source"], op_id);+ rpc.creator_event_uuid = "55555555-5555-5555-5555-555555555555".to_string();+ let response = service+ .merge_persons(Request::new(rpc))+ .await+ .expect("the redelivery attaches")+ .into_inner();++ let survivor = response.survivor.expect("delivery answers the person");+ assert_eq!(survivor.id, target);+ // The delivery ran (the flip landed) but the stamp stayed off a person+ // this op did not birth.+ assert!(survivor.is_identified);+ let properties: serde_json::Value = if survivor.properties.is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_slice(&survivor.properties).expect("properties are JSON")+ };+ assert_eq!(properties.get("$creator_event_uuid"), None);++ h.ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn allow_identified_sources_lets_an_identified_source_survive_an_unresolved_target() {let h = MergeHarness::new().await;@@ -2087,6 +2520,7 @@ async fn a_fully_unresolved_call_births_the_target_person() {let op_id = Uuid::now_v7();let mut request = rpc_request(h.ctx.team_id, "birth-target", &["birth-anon"], op_id);request.created_at = 1_700_000_000_000;+ request.creator_event_uuid = "11111111-2222-3333-4444-555555555555".to_string();let response = service.merge_persons(Request::new(request.clone())).await@@ -2122,6 +2556,19 @@ async fn a_fully_unresolved_call_births_the_target_person() {is_identified: Some(true),}]);+ // The event that created the person is recorded on it, which is what the+ // Postgres backend writes at creation. It rides the settlement push rather+ // than the stub row, because a stub is written straight to Postgres and+ // never reaches the leader's changelog.+ let properties: serde_json::Value =+ serde_json::from_slice(&survivor.properties).expect("survivor properties are JSON");+ assert_eq!(+ properties+ .get("$creator_event_uuid")+ .and_then(serde_json::Value::as_str),+ Some("11111111-2222-3333-4444-555555555555")+ );+ // Born by this call, so the inline settlement stamped the creator.let op_count: i64 = sqlx::query_scalar("SELECT count(*) FROM lifecycle_op WHERE op_id = $1").bind(op_id).fetch_one(&h.ctx.pool)@@ -2148,6 +2595,108 @@ async fn a_fully_unresolved_call_births_the_target_person() {h.ctx.cleanup().await.expect("cleanup");}+#[tokio::test]+async fn attaching_an_unseen_target_onto_a_source_is_not_a_birth() {+ // With no target person to resolve, establish_target attaches the unseen+ // target id onto the eligible source's person instead of birthing one.+ // That person predates the call, so the event that reached it did not+ // create it and must not be recorded as having done so.+ let h = MergeHarness::new().await;+ let service = h.service();+ let source = h.ctx.insert_person_with_distinct_id("attach-source").await;++ let mut request = rpc_request(+ h.ctx.team_id,+ "attach-target",+ &["attach-source"],+ Uuid::now_v7(),+ );+ request.creator_event_uuid = "44444444-3333-2222-1111-000000000000".to_string();+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("merge succeeds")+ .into_inner();++ let survivor = response.survivor.as_ref().expect("survivor present");+ assert_eq!(survivor.id, source);+ let properties: serde_json::Value =+ serde_json::from_slice(&survivor.properties).expect("survivor properties are JSON");+ assert!(properties.get("$creator_event_uuid").is_none());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_event_cannot_choose_its_own_creator_event_uuid() {+ // The property names the event that created the person, and it is+ // client-supplied input, so a value the event carries for that key must+ // not survive. The Postgres backend spreads its own last over both maps+ // at creation for the same reason.+ let h = MergeHarness::new().await;+ let service = h.service();++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(h.ctx.team_id, "forge-target", &["forge-anon"], op_id);+ request.created_at = 1_700_000_000_000;+ request.creator_event_uuid = "11111111-2222-3333-4444-555555555555".to_string();+ request.event_set = serde_json::to_vec(&serde_json::json!({+ "$creator_event_uuid": "99999999-9999-9999-9999-999999999999"+ }))+ .expect("set serializes");+ request.event_set_once = serde_json::to_vec(&serde_json::json!({+ "$creator_event_uuid": "88888888-8888-8888-8888-888888888888"+ }))+ .expect("set_once serializes");++ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("target birth succeeds")+ .into_inner();++ let survivor = response.survivor.as_ref().expect("survivor present");+ let properties: serde_json::Value =+ serde_json::from_slice(&survivor.properties).expect("survivor properties are JSON");+ assert_eq!(+ properties+ .get("$creator_event_uuid")+ .and_then(serde_json::Value::as_str),+ Some("11111111-2222-3333-4444-555555555555")+ );++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_resolved_target_does_not_gain_a_creator_event_uuid() {+ // The Postgres backend stamps $creator_event_uuid at creation and never+ // afterwards, so a merge landing on a person that already existed must+ // leave it alone. Only the establish path's newborn gets one.+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h.ctx.insert_person_with_distinct_id("keep-target").await;++ let mut request = rpc_request(h.ctx.team_id, "keep-target", &["keep-anon"], Uuid::now_v7());+ request.creator_event_uuid = "99999999-8888-7777-6666-555555555555".to_string();+ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("merge succeeds")+ .into_inner();++ let survivor = response.survivor.as_ref().expect("survivor present");+ assert_eq!(survivor.id, target);+ let properties: serde_json::Value = if survivor.properties.is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_slice(&survivor.properties).expect("survivor properties are JSON")+ };+ assert_eq!(properties.get("$creator_event_uuid"), None);++ h.ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn an_all_illegal_call_births_the_target_unidentified() {let h = MergeHarness::new().await;@@ -2661,3 +3210,273 @@ async fn a_vanished_survivor_answers_unavailable_with_nothing_written() {h.ctx.cleanup().await.expect("cleanup");}++/// Sources whose verdict is fixed before any lookup — illegal ids and ids+/// too long for the varchar(400) column — must not ride the resolution+/// query: nothing reads their resolutions, so resolving them would let a+/// caller pump arbitrarily large ids through the primary for free.+#[tokio::test]+async fn settled_sources_stay_out_of_the_resolution_query() {+ let h = MergeHarness::new().await;+ let racing = Arc::new(common::RacingStorage::new(h.ctx.storage.clone()));+ let service = h.service_with_storage(racing.clone());+ h.ctx.insert_person_with_distinct_id("resq-target").await;+ h.ctx.insert_person_with_distinct_id("resq-source").await;++ let oversized = "x".repeat(401);+ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "resq-target",+ &["resq-source", "anonymous", &oversized],+ Uuid::now_v7(),+ )))+ .await+ .expect("merge succeeds")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![+ ("resq-source".to_string(), MergeSourceOutcome::Merged),+ ("anonymous".to_string(), MergeSourceOutcome::SkippedIllegal),+ (oversized.clone(), MergeSourceOutcome::SkippedIllegal),+ ]+ );+ let resolved: Vec<String> = racing+ .resolved_keys+ .lock()+ .unwrap()+ .iter()+ .map(|(_, did)| did.clone())+ .collect();+ assert!(+ resolved.contains(&"resq-target".to_string())+ && resolved.contains(&"resq-source".to_string()),+ "the live pair still resolves"+ );+ assert!(+ !resolved.contains(&"anonymous".to_string()) && !resolved.contains(&oversized),+ "settled sources must not reach the resolution query: {resolved:?}"+ );++ h.ctx.cleanup().await.expect("cleanup");+}++/// An oversized source settles per-source, exactly like an illegal id: it+/// cannot exist in the varchar(400) column, so it can never resolve, and+/// failing the whole request would take legitimate sources down with it.+#[tokio::test]+async fn an_oversized_source_settles_per_source_instead_of_failing_the_request() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let target = h+ .ctx+ .insert_person_with_distinct_id("oversize-target")+ .await;+ let oversized = "x".repeat(401);++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "oversize-target",+ &[oversized.as_str()],+ Uuid::now_v7(),+ )))+ .await+ .expect("the request succeeds; the source settles")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![(oversized, MergeSourceOutcome::SkippedIllegal)]+ );+ assert_eq!(response.survivor.expect("survivor").id, target);++ h.ctx.cleanup().await.expect("cleanup");+}++/// A multibyte source inside 400 characters but past 400 bytes is storable+/// (varchar counts characters) and must merge, not bounce the request.+#[tokio::test]+async fn a_multibyte_source_within_the_character_limit_merges() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h+ .ctx+ .insert_person_with_distinct_id("multibyte-target")+ .await;+ // 200 three-byte chars: 600 bytes, 200 characters.+ let multibyte = "\u{4e16}".repeat(200);+ let source = h.ctx.insert_person_with_distinct_id(&multibyte).await;++ let response = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "multibyte-target",+ &[multibyte.as_str()],+ Uuid::now_v7(),+ )))+ .await+ .expect("a storable id merges")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![(multibyte, MergeSourceOutcome::Merged)]+ );+ let _ = source;++ h.ctx.cleanup().await.expect("cleanup");+}++/// NUL in the merge event's payload sanitizes rather than killing the+/// frozen op row's jsonb insert; the merge itself proceeds.+#[tokio::test]+async fn a_nul_bearing_event_payload_is_sanitized_and_the_merge_runs() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("nul-target").await;+ let _source = h.ctx.insert_person_with_distinct_id("nul-source").await;++ let mut request = rpc_request(h.ctx.team_id, "nul-target", &["nul-source"], Uuid::now_v7());+ request.event_set = serde_json::to_vec(&json!({"note": "x\u{0000}y"})).unwrap();++ let response = service+ .merge_persons(Request::new(request))+ .await+ .expect("the merge survives a NUL payload")+ .into_inner();++ assert_eq!(+ rpc_outcomes(&response),+ vec![("nul-source".to_string(), MergeSourceOutcome::Merged)]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++/// NUL cannot exist in Postgres text: a NUL target would fail person+/// establishment with an internal error on every attempt, and a NUL source+/// would make the frozen op row unwritable jsonb. Both refuse up front.+#[tokio::test]+async fn nul_bearing_distinct_ids_are_refused_before_any_durable_work() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("nul-id-target").await;++ let target_nul = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "bad\u{0000}target",+ &["nul-id-source"],+ Uuid::now_v7(),+ )))+ .await+ .expect_err("a NUL target refuses");+ assert_eq!(target_nul.code(), Code::InvalidArgument);++ let source_nul = service+ .merge_persons(Request::new(rpc_request(+ h.ctx.team_id,+ "nul-id-target",+ &["bad\u{0000}source"],+ Uuid::now_v7(),+ )))+ .await+ .expect_err("a NUL source refuses");+ assert_eq!(source_nul.code(), Code::InvalidArgument);++ h.ctx.cleanup().await.expect("cleanup");+}++/// The one job of the `created_at` strip in `same_merge`: a redelivery+/// whose event carried no timestamp derives a fresh wall-clock created_at,+/// and the retry must attach to the recorded op and replay its outcome+/// rather than bounce FAILED_PRECONDITION forever.+#[tokio::test]+async fn a_retry_with_a_drifted_created_at_replays_the_recorded_outcome() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("drift-target").await;+ let source = h.ctx.insert_person_with_distinct_id("drift-source").await;++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(h.ctx.team_id, "drift-target", &["drift-source"], op_id);+ request.created_at = 1_000;+ let first = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect("first call merges")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&first),+ vec![("drift-source".to_string(), MergeSourceOutcome::Merged)]+ );++ request.created_at = 2_000;+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("the drifted retry attaches instead of bouncing")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ vec![("drift-source".to_string(), MergeSourceOutcome::Merged)]+ );+ let _ = source;++ h.ctx.cleanup().await.expect("cleanup");+}++/// Two deliveries of one event disagree on pipeline-refreshed properties,+/// so the retry must attach to the recorded op and replay its outcome — a+/// refusal here is permanent and drops the merge with the fence standing.+/// The recorded op re-executes from its own frozen request, so drifted+/// values are discarded either way.+#[tokio::test]+async fn a_retry_with_drifted_event_properties_replays_the_recorded_outcome() {+ let h = MergeHarness::new().await;+ let service = h.service();+ let _target = h.ctx.insert_person_with_distinct_id("props-target").await;+ let _source = h.ctx.insert_person_with_distinct_id("props-source").await;++ let op_id = Uuid::now_v7();+ let mut request = rpc_request(h.ctx.team_id, "props-target", &["props-source"], op_id);+ request.event_set = serde_json::to_vec(&json!({"$geoip_city_name": "Paris"})).unwrap();+ request.event_set_once = serde_json::to_vec(&json!({"$initial_referrer": "a"})).unwrap();+ let first = service+ .merge_persons(Request::new(request.clone()))+ .await+ .expect("first call merges")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&first),+ vec![("props-source".to_string(), MergeSourceOutcome::Merged)]+ );++ request.event_set = serde_json::to_vec(&json!({"$geoip_city_name": "Berlin"})).unwrap();+ request.event_set_once = serde_json::to_vec(&json!({"$initial_referrer": "b"})).unwrap();+ let retry = service+ .merge_persons(Request::new(request))+ .await+ .expect("the drifted retry attaches instead of bouncing")+ .into_inner();+ assert_eq!(+ rpc_outcomes(&retry),+ vec![("props-source".to_string(), MergeSourceOutcome::Merged)]+ );++ h.ctx.cleanup().await.expect("cleanup");+}++/// U+0085 (NEL) survives JavaScript's trim, so a JavaScript client reads a+/// NEL-only id as legal; the server must agree or every merge naming one+/// bounces INVALID_ARGUMENT on a check the client cannot predict.+#[test]+fn nel_only_ids_match_the_javascript_trim_semantics() {+ use personhog_identity::lifecycle::validation::is_distinct_id_illegal;+ assert!(!is_distinct_id_illegal("\u{0085}"));+ assert!(is_distinct_id_illegal(" \t\n "));+ assert!(is_distinct_id_illegal("\u{FEFF}"));+}diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rsindex 88c23dbac5e9..c626dc5d300b 100644--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs@@ -35,6 +35,7 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {execute_timeout: Duration::from_secs(1),poll_interval: Duration::from_millis(10),attempt_alert_threshold: 5,+ gc_batch_limit: 10_000,},));let tables = IdentityTables::real();diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 152bc5fe230d..bc6ac8716e72 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -267,7 +267,8 @@ pub struct Config {/// the dirty index prunes a mark as soon as the writer's committed/// offset shows the primary has the row, so reading an async replica/// here would serve stale rows for unmarked persons and silently- /// break read-your-write. Leader reads are strong reads.+ /// break read-your-write. Lifecycle mark verifications read this pool+ /// too and fail closed on replica lag.#[envconfig(default = "")]pub fallback_database_url: String,diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rsindex 40cd7254ff0a..5384f87fc612 100644--- a/rust/personhog-leader/src/fence.rs+++ b/rust/personhog-leader/src/fence.rs@@ -173,7 +173,6 @@ pub async fn rebuild_partition_fences(if partition_for_person(team_id as i64, person_id, num_partitions) != partition {continue;}- let op_id: Uuid = row.get("op_id");let op_type: String = row.get("op_type");fences.insert(PersonCacheKey {@@ -181,7 +180,7 @@ pub async fn rebuild_partition_fences(person_id,},FenceState {- op_id,+ op_id: row.get("op_id"),op_type: LifecycleOpType::from_op_type_str(&op_type),},);diff --git a/rust/personhog-leader/src/person_update.rs b/rust/personhog-leader/src/person_update.rsindex 0c53d36f5d64..54d6cc1c8a54 100644--- a/rust/personhog-leader/src/person_update.rs+++ b/rust/personhog-leader/src/person_update.rs@@ -8,67 +8,132 @@ use serde_json::Value;static NO_PERSON_UPDATE_EVENTS: LazyLock<HashSet<&'static str>> =LazyLock::new(|| HashSet::from(["$exception", "$$heatmap"]));+/// Properties that change too often to be worth a person update on their+/// own. Copied from FILTERED_PERSON_UPDATE_PROPERTIES in+/// nodejs/src/common/persons/person-property-utils.ts, which links back;+/// the two lists must stay identical while both backends run.+static FILTERED_PERSON_UPDATE_PROPERTIES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {+ HashSet::from([+ "$current_url",+ "$pathname",+ "$referring_domain",+ "$referrer",+ "$screen_height",+ "$screen_width",+ "$viewport_height",+ "$viewport_width",+ "$browser",+ "$browser_version",+ "$device_type",+ "$raw_user_agent",+ "$os",+ "$os_name",+ "$os_version",+ "$geoip_postal_code",+ "$geoip_time_zone",+ "$geoip_latitude",+ "$geoip_longitude",+ "$geoip_accuracy_radius",+ "$geoip_subdivision_1_code",+ "$geoip_subdivision_1_name",+ "$geoip_subdivision_2_code",+ "$geoip_subdivision_2_name",+ "$geoip_subdivision_3_code",+ "$geoip_subdivision_3_name",+ "$geoip_city_confidence",+ "$geoip_country_confidence",+ "$geoip_postal_code_confidence",+ "$geoip_subdivision_1_confidence",+ "$geoip_subdivision_2_confidence",+ ])+});+/// The result of computing property diffs from an event.#[derive(Debug, Clone)]pub struct PropertyUpdates {pub to_set: HashMap<String, Value>,pub to_unset: Vec<String>,pub has_changes: bool,+ /// Whether any change warrants a write on its own: a new `$set` key,+ /// an unset, a non-filtered value change, or anything under force.+ /// False with `has_changes` true is the filtered-only shape.+ pub has_non_filtered_changes: bool,}/// Compute property changes from event data without modifying the existing person properties.///-/// This mirrors the TypeScript `computeEventPropertyUpdates` in `person-update.ts`,-/// but simplified for the PoC by omitting the property filtering logic-/// (FILTERED_PERSON_UPDATE_PROPERTIES).+/// Mirrors the TypeScript `refineEventOps`, filtered-property promotion+/// included: the classification must be byte-identical across backends+/// or shadow comparison reads the drift as divergence.pub fn compute_event_property_updates(event_name: &str,set_properties: &Value,set_once_properties: &Value,unset_properties: &[String],person_properties: &Value,+ force_update: bool,) -> PropertyUpdates {if NO_PERSON_UPDATE_EVENTS.contains(event_name) {return PropertyUpdates {has_changes: false,to_set: HashMap::new(),to_unset: Vec::new(),+ has_non_filtered_changes: false,};}+ let promotes = |key: &str| force_update || !FILTERED_PERSON_UPDATE_PROPERTIES.contains(key);let person_props = person_properties.as_object();let mut has_changes = false;+ let mut has_non_filtered_changes = false;let mut to_set = HashMap::new();let mut to_unset = Vec::new();- // Process $set_once: only set if the property doesn't already exist+ // $set_once fills absent keys; a new filtered key does not promote+ // on its own, as in the TS reference.if let Some(set_once_map) = set_once_properties.as_object() {for (key, value) in set_once_map {let existing = person_props.and_then(|p| p.get(key));if existing.is_none() {has_changes = true;+ if promotes(key) {+ has_non_filtered_changes = true;+ }to_set.insert(key.clone(), value.clone());}}}- // Process $set: apply all changed properties+ // $set, two passes: if any changed key promotes (a new key always+ // does, filtered or not), every changed key rides along.+ let mut set_changes: Vec<(&String, &Value)> = Vec::new();+ let mut any_set_promotes = false;if let Some(set_map) = set_properties.as_object() {for (key, value) in set_map {let existing = person_props.and_then(|p| p.get(key));if existing != Some(value) {- has_changes = true;- to_set.insert(key.clone(), value.clone());+ if existing.is_none() || promotes(key) {+ any_set_promotes = true;+ }+ set_changes.push((key, value));}}}+ for (key, value) in set_changes {+ has_changes = true;+ if any_set_promotes {+ has_non_filtered_changes = true;+ }+ to_set.insert(key.clone(), value.clone());+ }- // Process $unset: remove properties that exist+ // An unset of a present key always warrants the write.for key in unset_properties {let exists = person_props.is_some_and(|p| p.contains_key(key));if exists {has_changes = true;+ has_non_filtered_changes = true;to_unset.push(key.clone());}}@@ -77,6 +142,7 @@ pub fn compute_event_property_updates(has_changes,to_set,to_unset,+ has_non_filtered_changes,}}@@ -124,6 +190,7 @@ mod tests {&json!({}),&[],&json!({}),+ false,);assert!(!result.has_changes);assert!(result.to_set.is_empty());@@ -139,6 +206,7 @@ mod tests {&json!({}),&[],&json!({}),+ false,);assert!(result.has_changes);assert_eq!(result.to_set["email"], json!("[email protected]"));@@ -153,6 +221,7 @@ mod tests {&json!({}),&[],&json!({"email": "[email protected]"}),+ false,);assert!(!result.has_changes);assert!(result.to_set.is_empty());@@ -166,6 +235,7 @@ mod tests {&json!({"initial_referrer": "google.com", "email": "[email protected]"}),&[],&json!({"email": "[email protected]"}),+ false,);assert!(result.has_changes);assert_eq!(result.to_set.len(), 1);@@ -182,6 +252,7 @@ mod tests {&json!({}),&["email".to_string()],&json!({"email": "[email protected]", "name": "Test"}),+ false,);assert!(result.has_changes);assert_eq!(result.to_unset, vec!["email"]);@@ -195,6 +266,7 @@ mod tests {&json!({}),&["nonexistent".to_string()],&json!({"email": "[email protected]"}),+ false,);assert!(!result.has_changes);assert!(result.to_unset.is_empty());@@ -208,6 +280,7 @@ mod tests {&json!({"initial_source": "organic"}),&["old_prop".to_string()],&json!({"email": "[email protected]", "old_prop": "value"}),+ false,);assert!(result.has_changes);assert_eq!(result.to_set["name"], json!("New Name"));@@ -223,6 +296,7 @@ mod tests {&json!({"plan": "free"}),&[],&json!({}),+ false,);assert!(result.has_changes);assert_eq!(@@ -232,6 +306,93 @@ mod tests {);}+ #[test]+ fn filtered_only_changes_do_not_warrant_a_write() {+ // All changes filtered: the caller answers updated=false and discards.+ let result = compute_event_property_updates(+ "$pageview",+ &json!({"$current_url": "https://example.com/b", "$browser": "Firefox"}),+ &json!({}),+ &[],+ &json!({"$current_url": "https://example.com/a", "$browser": "Chrome"}),+ false,+ );+ assert!(result.has_changes);+ assert!(!result.has_non_filtered_changes);+ }++ #[test]+ fn one_real_change_promotes_the_filtered_values_with_it() {+ let result = compute_event_property_updates(+ "$pageview",+ &json!({"plan": "pro", "$current_url": "https://example.com/b"}),+ &json!({}),+ &[],+ &json!({"plan": "free", "$current_url": "https://example.com/a"}),+ false,+ );+ assert!(result.has_non_filtered_changes);+ assert_eq!(+ result.to_set["$current_url"],+ json!("https://example.com/b")+ );+ }++ #[test]+ fn a_new_set_key_promotes_even_when_filtered() {+ // A never-seen key is worth writing even when filtered, $set only.+ let result = compute_event_property_updates(+ "$pageview",+ &json!({"$browser": "Chrome"}),+ &json!({}),+ &[],+ &json!({}),+ false,+ );+ assert!(result.has_non_filtered_changes);+ }++ #[test]+ fn a_new_set_once_filtered_key_fills_without_promoting() {+ let result = compute_event_property_updates(+ "$pageview",+ &json!({}),+ &json!({"$browser": "Chrome"}),+ &[],+ &json!({}),+ false,+ );+ assert!(result.has_changes);+ assert!(!result.has_non_filtered_changes);+ assert_eq!(result.to_set["$browser"], json!("Chrome"));+ }++ #[test]+ fn an_unset_of_a_filtered_key_always_promotes() {+ let result = compute_event_property_updates(+ "$pageview",+ &json!({}),+ &json!({}),+ &["$browser".to_string()],+ &json!({"$browser": "Chrome"}),+ false,+ );+ assert!(result.has_non_filtered_changes);+ }++ #[test]+ fn force_promotes_filtered_only_changes() {+ let result = compute_event_property_updates(+ "$identify",+ &json!({"$current_url": "https://example.com/b"}),+ &json!({}),+ &[],+ &json!({"$current_url": "https://example.com/a"}),+ true,+ );+ assert!(result.has_non_filtered_changes);+ }+#[test]fn apply_updates_sets_properties() {let updates = PropertyUpdates {@@ -241,6 +402,7 @@ mod tests {]),to_unset: vec![],has_changes: true,+ has_non_filtered_changes: true,};let (result, updated) =@@ -257,6 +419,7 @@ mod tests {to_set: HashMap::new(),to_unset: vec!["email".to_string()],has_changes: true,+ has_non_filtered_changes: true,};let (result, updated) = apply_property_updates(@@ -275,6 +438,7 @@ mod tests {to_set: HashMap::from([("email".to_string(), json!("[email protected]"))]),to_unset: vec![],has_changes: true,+ has_non_filtered_changes: true,};let (result, updated) =diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex 3e4ee70e05c1..ca3d79698ba8 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -352,6 +352,8 @@ impl PersonHogLeaderService {key: &PersonCacheKey,) -> Result<Arc<CachedPerson>, Status> {let Some(fallback) = &self.fallback else {+ // Without the pool a cache miss answers NotFound, which callers+ // read as authoritative death; production always sets it.return Err(Status::not_found(format!("person not found: team_id={}, person_id={}",key.team_id, key.person_id@@ -1064,6 +1066,7 @@ impl PersonHogLeader for PersonHogLeaderService {&set_once_properties,&unset_properties,&person_properties,+ req.force_update,);// OR-merge: identification never reverts through this RPC, so@@ -1102,6 +1105,16 @@ impl PersonHogLeader for PersonHogLeaderService {}));}+ // Filtered-only changes are answered without writing, matching the+ // Postgres suppression; a scalar move or force promotes everything.+ if !updates.has_non_filtered_changes && !identity_changed && !last_seen_changed {+ counter!("personhog_leader_updates_total", "outcome" => "filtered_only").increment(1);+ return Ok(Response::new(UpdatePersonPropertiesResponse {+ person: Some(cached_person_to_proto(&person)),+ updated: false,+ }));+ }+// Slow path: apply diffs and check if the values actually changed// (has_changes can be true when $set sends the same value that already exists)let (new_properties, actually_updated) =@@ -1519,6 +1532,9 @@ impl PersonHogLeader for PersonHogLeaderService {// is an identify; last_seen_at max-merges like the update path —// the merged person was last seen whenever any constituent was// (snapshot values were already hour-floored when stored).+ //+ // The Postgres backend never passes last_seen_at to its merge+ // update; the caller's follow-up update advances it.let created_at = snapshots.iter().map(|snapshot| snapshot.created_at)@@ -1589,7 +1605,6 @@ impl PersonHogLeader for PersonHogLeaderService {if op_type == LifecycleOpType::Unspecified {return Err(Status::invalid_argument("op_type must be specified"));}-// A fence installed anywhere but the current owner protects// nothing: the map that gates writes is the owner's. Both guards// are needed — ownership covers a pod that already handed the@@ -2196,6 +2211,71 @@ mod tests {/// The person is seeded deliberately: without it a removed check/// would still surface `FailedPrecondition` from the ownership guard/// further down, and the test would pass having proved nothing.+ /// Filtered-only lanes answer updated=false with no write or produce;+ /// force writes. A demotion regression would produce, hang on the+ /// absent broker, and time out rather than pass.+ #[tokio::test]+ async fn filtered_only_update_answers_without_writing() {+ let service = make_test_service().await;+ let (team_id, person_id) = (7, 43);+ service.cache.create_partition(0);+ service.cache.put(+ 0,+ PersonCacheKey { team_id, person_id },+ CachedPerson {+ id: person_id,+ uuid: "00000000-0000-0000-0000-000000000008".to_string(),+ team_id,+ properties: serde_json::to_vec(+ &serde_json::json!({"$current_url": "https://example.com/a"}),+ )+ .unwrap(),+ created_at: 0,+ version: 3,+ is_identified: false,+ is_deleted: false,+ last_seen_at: None,+ approx_bytes: 64,+ },+ );++ let request = |force: bool| {+ let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: force,+ team_id,+ person_id,+ event_name: "$pageview".to_string(),+ set_properties: serde_json::to_vec(+ &serde_json::json!({"$current_url": "https://example.com/b"}),+ )+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ is_identified: None,+ last_seen_at: None,+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ request+ };++ let response = tokio::time::timeout(+ Duration::from_secs(5),+ service.update_person_properties(request(false)),+ )+ .await+ .expect("a demoted update must answer without producing")+ .expect("demoted update answers ok")+ .into_inner();+ assert!(!response.updated);+ assert_eq!(+ response.person.expect("carries the person").version,+ 3,+ "a discarded change must not bump the version"+ );+ }+#[tokio::test]async fn update_refuses_once_authority_is_surrendered() {let clock = Arc::new(AuthorityClock::unclaimed());@@ -2225,6 +2305,7 @@ mod tests {let request = || {let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id,person_id,event_name: "$set".to_string(),@@ -2382,6 +2463,7 @@ mod tests {let held = mutex.lock().await;let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id,person_id,event_name: "$set".to_string(),@@ -2465,6 +2547,7 @@ mod tests {assert_eq!(err.code(), Code::FailedPrecondition);let mut write = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id,person_id,event_name: "$set".to_string(),diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rsindex 465a6ca4ec70..0fa28055c8e6 100644--- a/rust/personhog-leader/tests/fence_integration.rs+++ b/rust/personhog-leader/tests/fence_integration.rs@@ -56,6 +56,7 @@ fn fence_request(team_id: i64, person_id: i64, op_id: &Uuid) -> FencePersonRequefn update_request(team_id: i64, person_id: i64) -> UpdatePersonPropertiesRequest {UpdatePersonPropertiesRequest {+ force_update: false,team_id,person_id,event_name: "$set".to_string(),diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rsindex 5bb01110b5ac..80bca3bed0d1 100644--- a/rust/personhog-leader/tests/integration.rs+++ b/rust/personhog-leader/tests/integration.rs@@ -131,6 +131,7 @@ async fn service_accepts_requests_after_coordination_warmup() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -222,6 +223,7 @@ async fn unowned_partition_returns_failed_precondition() {let result = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -315,6 +317,7 @@ async fn missing_partition_metadata_returns_invalid_argument() {let result = client.update_person_properties(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -401,6 +404,7 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {let result = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -504,6 +508,7 @@ async fn writes_fenced_after_drain_reads_still_served() {let update = |email: &str| {with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -647,6 +652,7 @@ async fn drain_fences_before_waiting_on_inflight() {let status = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -946,6 +952,7 @@ async fn update_produces_person_state_to_kafka() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -1063,6 +1070,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {let result = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -1101,6 +1109,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -1190,6 +1199,7 @@ async fn e2e_update_produces_to_local_kafka() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -1443,6 +1453,7 @@ async fn update_triggers_pg_fallback_then_applies_changes() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: team_id as i64,person_id,event_name: "$set".to_string(),@@ -1539,6 +1550,7 @@ async fn evicted_dirty_person_recovers_from_changelog() {client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -1642,6 +1654,7 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -1761,6 +1774,7 @@ async fn writes_shed_when_dirty_index_is_full() {let mut client = create_leader_client(addr).await;let update_for = |person_id: i64, value: &str| UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id,event_name: "$set".to_string(),@@ -1853,6 +1867,7 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -1967,6 +1982,7 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {let client = create_leader_client(addr).await;let update_for = |person_id: i64, value: &str| UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id,event_name: "$set".to_string(),@@ -2192,6 +2208,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let err = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -2235,6 +2252,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -2278,6 +2296,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: OVERSIZED_PERSON_ID,event_name: "$set".to_string(),@@ -2349,6 +2368,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let err = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: UNREMEDIABLE_PERSON_ID,event_name: "$set".to_string(),@@ -2447,6 +2467,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -2464,6 +2485,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 2,person_id: TEAM_2_PERSON_ID,event_name: "$set".to_string(),@@ -2498,6 +2520,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -2546,6 +2569,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {let response = client.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: PERSON_ID,event_name: "$set".to_string(),@@ -2633,6 +2657,7 @@ async fn an_unresolved_version_is_never_reused() {let response = service.update_person_properties(with_partition(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -2705,6 +2730,7 @@ async fn a_fenced_write_that_bounces_does_not_hand_its_version_back() {// no-change fast path and never reaches the produce at all.let update = |n: i64| {let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -2827,6 +2853,7 @@ async fn an_unknown_outcome_keeps_its_version(};let update = |n: i64| {let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -2909,6 +2936,7 @@ async fn scalar_fields_merge_rather_than_assign() {let update = |set: serde_json::Value, identified: Option<bool>, seen: Option<i64>| {let mut request = Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$identify".to_string(),diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex a0940b669da3..71742d978b03 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -14,6 +14,11 @@ use tonic::{Code, Status};use tower::{Service, ServiceExt};use personhog_common::grpc::{current_client_name, SEMANTIC_REFUSAL_METADATA_KEY};++/// Set by the leader on writes refused for a lifecycle hold. Mirrored so+/// the router does not depend on the leader crate.+const FENCED_METADATA_KEY: &str = "x-person-fenced";+const FENCED_OP_ID_METADATA_KEY: &str = "x-person-fenced-op-id";use personhog_common::partitioning::partition_for_person;use super::stash::{StashDecision, StashTable};@@ -100,6 +105,11 @@ pub enum ForwardDecision {call_ms: f64,},Bounced(BounceReason),+ /// Any non-semantic FAILED_PRECONDITION with its refusal metadata;+ /// the holder's op id tells a caller whether the fence is its own.+ BouncedFenced {+ headers: HeaderMap,+ },}/// Static configuration for `LeaderBackend`. Bundles the knobs that come@@ -340,7 +350,9 @@ impl LeaderBackend {{ForwardDecision::Delivered { response, call_ms }} else {- ForwardDecision::Bounced(BounceReason::Fenced)+ ForwardDecision::BouncedFenced {+ headers: response.headers().clone(),+ }}}Ok((response, call_ms)) => ForwardDecision::Delivered { response, call_ms },@@ -391,6 +403,8 @@ impl LeaderBackend {frame: Bytes,) -> (http::Response<BoxBody>, Option<f64>) {let mut consecutive_bounces = 0u32;+ // Whether any attempt may have been applied, which the stash+ // needs to treat a replay as at-least-once.let mut possibly_applied = false;loop {// The stash module emits its own enqueued/rejected counters@@ -430,20 +444,51 @@ impl LeaderBackend {ForwardDecision::Delivered { response, call_ms } => {return (response, Some(call_ms));}- ForwardDecision::Bounced(reason) => {+ decision+ @ (ForwardDecision::Bounced(_) | ForwardDecision::BouncedFenced { .. }) => {+ let reason = match &decision {+ ForwardDecision::Bounced(reason) => *reason,+ _ => BounceReason::Fenced,+ };if counts_as_possibly_applied(reason) {possibly_applied = true;}consecutive_bounces += 1;if consecutive_bounces >= MAX_CONSECUTIVE_BOUNCES {- counter!("personhog_router_forward_retries_exhausted_total").increment(1);- return (- grpc_error_response(- Code::Unavailable,- "leader unreachable or transitioning; retry",- ),- None,+ // The label separates a fence exhaustion (acked,+ // dropped) from a transport one (redelivered).+ counter!(+ "personhog_router_forward_retries_exhausted_total",+ "reason" => reason.label(),+ )+ .increment(1);+ // Fence metadata names a lifecycle holder; a bare+ // FAILED_PRECONDITION is ordinary handoff/ownership.+ let held_by_op = matches!(+ &decision,+ ForwardDecision::BouncedFenced { headers }+ if headers.contains_key(FENCED_METADATA_KEY)+ );+ let mut response = grpc_error_response(+ Code::Unavailable,+ if held_by_op {+ "person is held by a lifecycle operation; retries exhausted"+ } else if matches!(reason, BounceReason::Fenced) {+ "leader refused the write precondition (handoff or ownership); retries exhausted"+ } else {+ "leader unreachable or transitioning; retry"+ },);+ // Keys travel only from the bounce that ended the+ // request, so a dead leader cannot report as held.+ if let ForwardDecision::BouncedFenced { headers: fence } = &decision {+ for key in [FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY] {+ if let Some(value) = fence.get(key) {+ response.headers_mut().insert(key, value.clone());+ }+ }+ }+ return (response, None);}counter!("personhog_router_forward_retries_total",diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 93a604a35483..471a4f69b139 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -557,7 +557,10 @@ fn preregister_metrics() {use metrics::counter;counter!("personhog_router_stash_enqueued_total").increment(0);counter!("personhog_router_stash_replayed_total").increment(0);- counter!("personhog_router_forward_retries_exhausted_total").increment(0);+ for reason in ["unrouted", "fenced", "transport"] {+ counter!("personhog_router_forward_retries_exhausted_total", "reason" => reason)+ .increment(0);+ }for outcome in ["success", "error", "expired"] {counter!("personhog_router_stash_drained_total", "outcome" => outcome).increment(0);}diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rsindex 2d3f83e0896b..fd2888b6e9ca 100644--- a/rust/personhog-router/src/stash_handler.rs+++ b/rust/personhog-router/src/stash_handler.rs@@ -177,6 +177,11 @@ async fn forward_one(Disposition::Reply { response, outcome }}ForwardDecision::Bounced(reason) => Disposition::Bounce(reason),+ // A bounced replay is not an answer: it re-enters the bounce+ // backoff, so there is no response here to carry fence metadata on.+ // A never-settling stash expires with a plain-retry reply, so a+ // fence met during a handoff costs a redelivery.+ ForwardDecision::BouncedFenced { .. } => Disposition::Bounce(BounceReason::Fenced),}}diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex 008b2d0ac991..20d9393c3703 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -3,7 +3,7 @@use std::collections::HashMap;use std::net::SocketAddr;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Arc;+use std::sync::{Arc, Mutex};use std::time::Duration;use dashmap::DashMap;@@ -643,6 +643,10 @@ pub struct TestLeaderService {/// runtime-toggleable so tests can clear the fence mid-drain, the way/// a real fence clears in watch-propagation time.fenced: Arc<AtomicBool>,+ /// The lifecycle operation holding this person, if any. Unlike the+ /// partition fence above this one names its holder, which is the fact+ /// the refusal has to carry all the way back to the caller.+ person_fence_op: Arc<Mutex<Option<String>>>,}impl TestLeaderService {@@ -650,9 +654,18 @@ impl TestLeaderService {Self {persons: DashMap::new(),fenced: Arc::new(AtomicBool::new(false)),+ person_fence_op: Arc::new(Mutex::new(None)),}}+ /// Refuse every write for this person the way the leader refuses one+ /// held by a lifecycle operation: FAILED_PRECONDITION carrying the+ /// fence keys and the holding op's id.+ pub fn person_fenced_by(self, op_id: &str) -> Self {+ *self.person_fence_op.lock().unwrap() = Some(op_id.to_string());+ self+ }+pub fn with_person(self, person: Person) -> Self {self.persons.insert((person.team_id, person.id), person);self@@ -751,6 +764,18 @@ impl PersonHogLeader for TestLeaderService {"partition is fenced for handoff; writes are rejected",));}+ if let Some(op_id) = self.person_fence_op.lock().unwrap().clone() {+ let mut status = Status::failed_precondition("person is held by a lifecycle operation");+ // The real leader carries the op-type string here, never a+ // boolean; see fenced_status in personhog-leader/src/fence.rs.+ status+ .metadata_mut()+ .insert("x-person-fenced", "merge".parse().unwrap());+ status+ .metadata_mut()+ .insert("x-person-fenced-op-id", op_id.parse().unwrap());+ return Err(status);+ }let key = (req.team_id, req.person_id);let mut person = self@@ -861,6 +886,68 @@ fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<Lead))}+/// A leader backend whose pod answers once and is then unreachable: the+/// resolver hands out the real address for the first resolution and a dead+/// port after it. Models a leader that refuses a request and then dies,+/// which is the only way to follow one bounce reason with another.+fn make_dying_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<LeaderBackend> {+ let mut routing = HashMap::new();+ for p in 0..num_partitions {+ routing.insert(p, "leader-0".to_string());+ }+ let routing_table = Arc::new(RwLock::new(routing));+ let leader_url = format!("http://{}", leader_addr);+ let resolutions = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let address_resolver: Arc<dyn Fn(&str) -> Option<String> + Send + Sync> =+ Arc::new(move |_pod_name| {+ if resolutions.fetch_add(1, Ordering::SeqCst) == 0 {+ Some(leader_url.clone())+ } else {+ // Reserved-for-documentation address, so nothing can be listening.+ Some("http://192.0.2.1:1".to_string())+ }+ });+ Arc::new(LeaderBackend::new(+ routing_table,+ address_resolver,+ LeaderBackendConfig {+ num_partitions,+ timeout: Duration::from_millis(200),+ },+ StashTable::with_bounds(usize::MAX, usize::MAX),+ ))+}++/// Raw proxy router whose leader answers one request and is then gone.+pub async fn start_test_router_raw_with_dying_leader(+ replica_addr: SocketAddr,+ leader_addr: SocketAddr,+ num_partitions: u32,+) -> SocketAddr {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let proxy = RawProxyService::new(+ make_replica_backend(replica_addr),+ Some(make_dying_leader_backend(leader_addr, num_partitions)),+ RetryConfig {+ max_retries: 1,+ initial_backoff_ms: 1,+ max_backoff_ms: 1,+ },+ 4 * 1024 * 1024,+ 0,+ );+ tokio::spawn(async move {+ Server::builder()+ .add_service(proxy)+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))+ .await+ .unwrap();+ });+ tokio::time::sleep(Duration::from_millis(10)).await;+ addr+}+/// Start a raw proxy router (replica only, no leader).pub async fn start_test_router_raw(replica_addr: SocketAddr) -> SocketAddr {start_test_router_raw_with_max_recv(replica_addr, 4 * 1024 * 1024).awaitdiff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rsindex 063f5c061470..1f4fff06320b 100644--- a/rust/personhog-router/tests/raw_proxy_integration.rs+++ b/rust/personhog-router/tests/raw_proxy_integration.rs@@ -4,8 +4,9 @@ use common::{create_client, create_compressed_client, create_test_person, raw_grpc_call_with_gzip_accept,start_test_leader, start_test_replica, start_test_replica_with_async_gzip,start_test_replica_with_async_gzip_disabled, start_test_router_raw,- start_test_router_raw_with_leader, start_test_router_raw_with_leader_and_max_recv,- start_test_router_raw_with_max_recv, TestLeaderService, TestReplicaService,+ start_test_router_raw_with_dying_leader, start_test_router_raw_with_leader,+ start_test_router_raw_with_leader_and_max_recv, start_test_router_raw_with_max_recv,+ TestLeaderService, TestReplicaService,};use personhog_proto::personhog::types::v1::{CheckCohortMembershipRequest, CohortMembership, DeletePersonsRequest, GetGroupsRequest,@@ -251,6 +252,7 @@ async fn raw_proxy_update_person_properties_routes_to_leader() {let response = client.update_person_properties(with_person_key(Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -272,6 +274,100 @@ async fn raw_proxy_update_person_properties_routes_to_leader() {assert_eq!(result.person.unwrap().version, test_person.version + 1);}+/// A lifecycle fence is the one refusal whose holder the caller can act+/// on, by recognising its own merge's op id and driving it to completion.+/// The router exhausts the bounce into its own UNAVAILABLE, so unless the+/// fence keys ride along, the one fact the caller needs is discarded in+/// transit.+#[tokio::test]+async fn raw_proxy_exhausted_person_fence_bounce_names_the_holder() {+ let test_person = create_test_person();+ let leader_service = TestLeaderService::new()+ .with_person(test_person.clone())+ .person_fenced_by("0189f0e0-0000-7000-8000-000000000000");+ let replica_service = TestReplicaService::new();++ let replica_addr = start_test_replica(replica_service).await;+ let leader_addr = start_test_leader(leader_service).await;+ let router_addr =+ start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;+ let mut client = create_client(router_addr).await;++ let status = client+ .update_person_properties(with_person_key(+ Request::new(UpdatePersonPropertiesRequest {+ force_update: false,+ team_id: 1,+ person_id: 42,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test User"}))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ is_identified: None,+ last_seen_at: None,+ }),+ 1,+ 42,+ ))+ .await+ .expect_err("a permanently fenced person exhausts the bounce budget");++ assert_eq!(status.code(), tonic::Code::Unavailable);+ assert_eq!(+ status+ .metadata()+ .get("x-person-fenced-op-id")+ .map(|value| value.to_str().unwrap()),+ Some("0189f0e0-0000-7000-8000-000000000000"),+ );+ assert!(status.metadata().get("x-person-fenced").is_some());+}++/// Callers ack rather than retry a fence naming somebody else's operation,+/// so the keys must describe the bounce that actually ended the request.+/// Carried forward from an earlier attempt, they report a dead leader as a+/// held person and the caller acks a merge that never happened.+#[tokio::test]+async fn raw_proxy_a_dead_leader_after_a_fence_is_not_reported_as_fenced() {+ let test_person = create_test_person();+ let leader_service = TestLeaderService::new()+ .with_person(test_person.clone())+ .person_fenced_by("0189f0e0-0000-7000-8000-000000000000");+ let replica_addr = start_test_replica(TestReplicaService::new()).await;+ let leader_addr = start_test_leader(leader_service).await;+ let router_addr =+ start_test_router_raw_with_dying_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;+ let mut client = create_client(router_addr).await;++ let status = client+ .update_person_properties(with_person_key(+ Request::new(UpdatePersonPropertiesRequest {+ force_update: false,+ team_id: 1,+ person_id: 42,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test User"}))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ is_identified: None,+ last_seen_at: None,+ }),+ 1,+ 42,+ ))+ .await+ .expect_err("the leader is gone after its first answer");++ assert_eq!(status.code(), tonic::Code::Unavailable);+ assert!(+ status.metadata().get("x-person-fenced").is_none(),+ "a transport failure must not inherit the earlier bounce's fence keys"+ );+ assert!(status.metadata().get("x-person-fenced-op-id").is_none());+}+#[tokio::test]async fn raw_proxy_write_then_strong_read_roundtrip() {let test_person = create_test_person();@@ -287,6 +383,7 @@ async fn raw_proxy_write_then_strong_read_roundtrip() {client.update_person_properties(with_person_key(Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -344,6 +441,7 @@ async fn raw_proxy_leader_requests_without_key_headers_rejected() {let update_result = client.update_person_properties(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -412,6 +510,7 @@ async fn raw_proxy_update_person_properties_no_leader_returns_unimplemented() {let result = client.update_person_properties(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -449,6 +548,7 @@ async fn raw_proxy_compressed_leader_requests_transit_untouched() {let response = compressed.update_person_properties(with_person_key(Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),@@ -531,6 +631,7 @@ async fn raw_proxy_rejects_oversized_leader_request() {let result = client.update_person_properties(with_person_key(Request::new(UpdatePersonPropertiesRequest {+ force_update: false,team_id: 1,person_id: 42,event_name: "$set".to_string(),diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rsindex 44f4e9811063..644a65b279f7 100644--- a/rust/personhog-router/tests/stash_integration.rs+++ b/rust/personhog-router/tests/stash_integration.rs@@ -72,6 +72,7 @@ async fn make_backend(leader_addr: std::net::SocketAddr, stash: StashTable) -> Afn mk_request(team_id: i64, person_id: i64, set_email: &str) -> UpdatePersonPropertiesRequest {UpdatePersonPropertiesRequest {+ force_update: false,team_id,person_id,event_name: "test".to_string(),diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rsindex aae7996a5e56..40e585b6e103 100644--- a/rust/personhog-test-harness/src/client.rs+++ b/rust/personhog-test-harness/src/client.rs@@ -107,6 +107,7 @@ impl HarnessClient {) -> Result<UpdatePersonPropertiesResponse> {self.inner.update_person_properties(UpdatePersonPropertiesRequest {+ force_update: true,team_id,person_id,event_name: "$set".to_string(),@@ -159,7 +160,9 @@ impl IdentityClient {/// Merge `source_distinct_ids` into the person that/// `target_distinct_id` resolves to. A retry with the same op id- /// returns the recorded outcome and does not merge again.+ /// returns the recorded outcome and does not merge again. The+ /// creator must stay stable across those retries, so the caller+ /// mints it once per merge alongside the op id.#[allow(clippy::too_many_arguments)]pub async fn merge_persons(&self,@@ -169,6 +172,7 @@ impl IdentityClient {event_set: serde_json::Value,event_set_once: serde_json::Value,op_id: &uuid::Uuid,+ creator_event_uuid: &uuid::Uuid,allow_identified_sources: bool,move_limit: i64,) -> Result<MergePersonsResponse> {@@ -191,6 +195,7 @@ impl IdentityClient {allow_identified_sources,move_limit: Some(move_limit),created_at: 0,+ creator_event_uuid: creator_event_uuid.to_string(),})).await.context("MergePersons failed")?;diff --git a/rust/personhog-test-harness/src/scenarios/merge.rs b/rust/personhog-test-harness/src/scenarios/merge.rsindex b1db97613d6a..eba989bab13f 100644--- a/rust/personhog-test-harness/src/scenarios/merge.rs+++ b/rust/personhog-test-harness/src/scenarios/merge.rs@@ -230,6 +230,7 @@ pub async fn run_merges(state.mark_merge_pending(source).await;}let op_id = uuid::Uuid::new_v4();+ let creator_event_uuid = uuid::Uuid::new_v4();let event = MergeEvent::new(&op_id);let start = Instant::now();@@ -244,6 +245,7 @@ pub async fn run_merges(json!(event.set),json!(event.set_once),&op_id,+ &creator_event_uuid,allow_identified_sources,move_limit,)@@ -670,6 +672,7 @@ pub fn outcome_name(outcome: MergeSourceOutcome) -> &'static str {MergeSourceOutcome::SkippedIllegal => "skipped_illegal",MergeSourceOutcome::SkippedAlreadyIdentified => "skipped_already_identified",MergeSourceOutcome::SkippedConflict => "skipped_conflict",+ MergeSourceOutcome::SkippedRefused => "skipped_refused",MergeSourceOutcome::SkippedMoveLimit => "skipped_move_limit",MergeSourceOutcome::Error => "error",MergeSourceOutcome::Unspecified => "unspecified",