: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): merge saga driver in personhog-identity (#79227)
Nick Beste4ca2e5d4dec
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rsindex 7dbeb40e3ffe..ceb213c23201 100644--- a/rust/personhog-common/src/grpc.rs+++ b/rust/personhog-common/src/grpc.rs@@ -34,6 +34,35 @@ const CLIENT_NAME_HEADER: &str = "x-client-name";/// observability.pub const SEMANTIC_REFUSAL_METADATA_KEY: &str = "x-semantic-refusal";+/// Build a semantic refusal. The reason is a short slug used as a metric+/// label.+pub fn semantic_refusal(message: impl Into<String>, reason: &'static str) -> tonic::Status {+ let mut status = tonic::Status::failed_precondition(message.into());+ if let Ok(value) = reason.parse() {+ status+ .metadata_mut()+ .insert(SEMANTIC_REFUSAL_METADATA_KEY, value);+ }+ status+}++/// Whether a status is a definitive semantic refusal rather than a+/// transient failure a retry can outlive.+pub fn is_semantic_refusal(status: &tonic::Status) -> bool {+ status.code() == tonic::Code::FailedPrecondition+ && status+ .metadata()+ .contains_key(SEMANTIC_REFUSAL_METADATA_KEY)+}++/// The refusal's reason slug, when present.+pub fn semantic_refusal_reason(status: &tonic::Status) -> Option<&str> {+ status+ .metadata()+ .get(SEMANTIC_REFUSAL_METADATA_KEY)+ .and_then(|v| v.to_str().ok())+}+/// 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-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.json b/rust/personhog-identity/.sqlx/query-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.jsonnew file mode 100644index 000000000000..7c751cf0995a--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT person_id, person_uuid FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')\n ",+ "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": "049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9"+}diff --git a/rust/personhog-identity/.sqlx/query-10399aec9f42794d6374624fab6cd9480fc81b57fa2ff5e09df6cf66c400a83c.json b/rust/personhog-identity/.sqlx/query-10399aec9f42794d6374624fab6cd9480fc81b57fa2ff5e09df6cf66c400a83c.jsonnew file mode 100644index 000000000000..033f5b717f5a--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-10399aec9f42794d6374624fab6cd9480fc81b57fa2ff5e09df6cf66c400a83c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND person_id = ANY($3) AND status IN ('marked', 'sealed')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "10399aec9f42794d6374624fab6cd9480fc81b57fa2ff5e09df6cf66c400a83c"+}diff --git a/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.json b/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.jsonnew file mode 100644index 000000000000..d13c7ce49e0a--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM lifecycle_op_person lop\n WHERE lop.op_id = $1 AND lop.status = 'marked'\n AND NOT EXISTS (\n SELECT 1 FROM posthog_person p\n WHERE p.team_id = $2 AND p.id = lop.person_id AND p.is_deleted = false\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f"+}diff --git a/rust/personhog-identity/.sqlx/query-1cbc9c47bb8f3d0d93790fdd5d2270e7d7097e5b94e1f3fdaffe27709096a74e.json b/rust/personhog-identity/.sqlx/query-1cbc9c47bb8f3d0d93790fdd5d2270e7d7097e5b94e1f3fdaffe27709096a74e.jsonnew file mode 100644index 000000000000..4769f59bd456--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-1cbc9c47bb8f3d0d93790fdd5d2270e7d7097e5b94e1f3fdaffe27709096a74e.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO lifecycle_op_person\n (op_id, team_id, person_id, person_uuid, role, ordinal, status)\n SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, $6\n FROM unnest($3::bigint[], $4::uuid[], $5::text[], $7::int[])\n AS u(person_id, person_uuid, role, ordinal)\n ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING\n RETURNING person_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4",+ "Int8Array",+ "UuidArray",+ "TextArray",+ "Text",+ "Int4Array"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "1cbc9c47bb8f3d0d93790fdd5d2270e7d7097e5b94e1f3fdaffe27709096a74e"+}diff --git a/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.json b/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.jsondeleted file mode 100644index 92fdb4c2b71d..000000000000--- a/rust/personhog-identity/.sqlx/query-1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "1ffe54744effa34537dd4ca4b98e9e90e92b95858866b531efe4ed696b2760a0"-}diff --git a/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.json b/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.jsondeleted file mode 100644index 2905cf603e1d..000000000000--- a/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2),\n attempt = attempt + 1\n WHERE op_id = $1 AND completed_at IS NULL\n AND (lease_expires_at IS NULL OR lease_expires_at < now())\n RETURNING attempt\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "attempt",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid",- "Float8"- ]- },- "nullable": [- false- ]- },- "hash": "23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc"-}diff --git a/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.json b/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.jsonnew file mode 100644index 000000000000..8897cd94df0c--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.json@@ -0,0 +1,36 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_persondistinctid pdi\n SET person_id = $3, version = COALESCE(pdi.version, 0) + 1\n FROM posthog_persondistinctid old\n WHERE old.id = pdi.id\n AND pdi.team_id = $1 AND pdi.person_id = ANY($2) AND pdi.is_deleted = false\n RETURNING old.person_id as \"old_person_id!\", pdi.distinct_id, pdi.version as \"version!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "old_person_id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "distinct_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "version!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a"+}diff --git a/rust/personhog-identity/.sqlx/query-322ca9ef09b4f6396595c9195b18fbd5a3e99a4dc544c8f37bdb59f92c4fcaee.json b/rust/personhog-identity/.sqlx/query-322ca9ef09b4f6396595c9195b18fbd5a3e99a4dc544c8f37bdb59f92c4fcaee.jsonnew file mode 100644index 000000000000..2cc25c3427a1--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-322ca9ef09b4f6396595c9195b18fbd5a3e99a4dc544c8f37bdb59f92c4fcaee.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND person_id = ANY($3) AND status = $4\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Int8Array",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "322ca9ef09b4f6396595c9195b18fbd5a3e99a4dc544c8f37bdb59f92c4fcaee"+}diff --git a/rust/personhog-identity/.sqlx/query-43ffcbbecab243f07c49c6c8c6648f2e4d78e9804e1de5ac4f36bf263f545689.json b/rust/personhog-identity/.sqlx/query-43ffcbbecab243f07c49c6c8c6648f2e4d78e9804e1de5ac4f36bf263f545689.jsonnew file mode 100644index 000000000000..da54f0741b30--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-43ffcbbecab243f07c49c6c8c6648f2e4d78e9804e1de5ac4f36bf263f545689.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "43ffcbbecab243f07c49c6c8c6648f2e4d78e9804e1de5ac4f36bf263f545689"+}diff --git a/rust/personhog-identity/.sqlx/query-45affb23f143cd23cea3ebabc6f3e43972a366cbdac5ff5a69169df1dc854c1f.json b/rust/personhog-identity/.sqlx/query-45affb23f143cd23cea3ebabc6f3e43972a366cbdac5ff5a69169df1dc854c1f.jsonnew file mode 100644index 000000000000..ec4f6db8dc66--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-45affb23f143cd23cea3ebabc6f3e43972a366cbdac5ff5a69169df1dc854c1f.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status = $4\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "45affb23f143cd23cea3ebabc6f3e43972a366cbdac5ff5a69169df1dc854c1f"+}diff --git a/rust/personhog-identity/.sqlx/query-5121f35d8db57bf3fe0c0e9bba74ea0a5293dabb718e54d380c9b8053396d182.json b/rust/personhog-identity/.sqlx/query-5121f35d8db57bf3fe0c0e9bba74ea0a5293dabb718e54d380c9b8053396d182.jsonnew file mode 100644index 000000000000..ba9364f3d85b--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-5121f35d8db57bf3fe0c0e9bba74ea0a5293dabb718e54d380c9b8053396d182.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT person_id FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "5121f35d8db57bf3fe0c0e9bba74ea0a5293dabb718e54d380c9b8053396d182"+}diff --git a/rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.json b/rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.jsonnew file mode 100644index 000000000000..cd28cc3a4f68--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.json@@ -0,0 +1,36 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT person_id, ordinal as \"ordinal!\", sealed as \"sealed!\" FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ORDER BY ordinal\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "ordinal!",+ "type_info": "Int4"+ },+ {+ "ordinal": 2,+ "name": "sealed!",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true+ ]+ },+ "hash": "5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e"+}diff --git a/rust/personhog-identity/.sqlx/query-5d37082df24b4f99dc26e5ebe5d10baaf89fbb079f48ce6d2fc7890e1088a905.json b/rust/personhog-identity/.sqlx/query-5d37082df24b4f99dc26e5ebe5d10baaf89fbb079f48ce6d2fc7890e1088a905.jsonnew file mode 100644index 000000000000..4ccb0e40b250--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-5d37082df24b4f99dc26e5ebe5d10baaf89fbb079f48ce6d2fc7890e1088a905.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM lifecycle_op WHERE completed_at IS NULL AND parked_at IS NOT NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "5d37082df24b4f99dc26e5ebe5d10baaf89fbb079f48ce6d2fc7890e1088a905"+}diff --git a/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.json b/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.jsonnew file mode 100644index 000000000000..3570dca72cdb--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT d.distinct_id, d.person_id as \"person_id!\", p.uuid as \"person_uuid!\",\n p.is_identified as \"is_identified!\"\n FROM posthog_persondistinctid d\n JOIN posthog_person p ON p.team_id = d.team_id AND p.id = d.person_id\n WHERE d.team_id = $1 AND d.distinct_id = ANY($2)\n AND d.is_deleted = false AND p.is_deleted = false\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "distinct_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 1,+ "name": "person_id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "person_uuid!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "is_identified!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32"+}diff --git a/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.json b/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.jsonnew file mode 100644index 000000000000..b4e264b42e44--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816"+}diff --git a/rust/personhog-identity/.sqlx/query-7e2d32739341dee936762ee4cf28b8f5d65d5a5e331288be76c2b77ed172c0ae.json b/rust/personhog-identity/.sqlx/query-7e2d32739341dee936762ee4cf28b8f5d65d5a5e331288be76c2b77ed172c0ae.jsonnew file mode 100644index 000000000000..8515e022bf31--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-7e2d32739341dee936762ee4cf28b8f5d65d5a5e331288be76c2b77ed172c0ae.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE posthog_cohortpeople SET person_id = $2 WHERE person_id = ANY($1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int8Array",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "7e2d32739341dee936762ee4cf28b8f5d65d5a5e331288be76c2b77ed172c0ae"+}diff --git a/rust/personhog-identity/.sqlx/query-88c5c79bf91abf98a71cac3239c6002efe488df90268884cc0bb866ced94d021.json b/rust/personhog-identity/.sqlx/query-88c5c79bf91abf98a71cac3239c6002efe488df90268884cc0bb866ced94d021.jsonnew file mode 100644index 000000000000..0df932a62eb3--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-88c5c79bf91abf98a71cac3239c6002efe488df90268884cc0bb866ced94d021.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE lifecycle_op_person SET sealed = $2 WHERE op_id = $1 AND role = $3",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Jsonb",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "88c5c79bf91abf98a71cac3239c6002efe488df90268884cc0bb866ced94d021"+}diff --git a/rust/personhog-identity/.sqlx/query-92c1ca048420781fbdbce0e666a2c86a297b3e6659619c5e050d31de036f4b68.json b/rust/personhog-identity/.sqlx/query-92c1ca048420781fbdbce0e666a2c86a297b3e6659619c5e050d31de036f4b68.jsonnew file mode 100644index 000000000000..592557efb7c8--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-92c1ca048420781fbdbce0e666a2c86a297b3e6659619c5e050d31de036f4b68.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "92c1ca048420781fbdbce0e666a2c86a297b3e6659619c5e050d31de036f4b68"+}diff --git a/rust/personhog-identity/.sqlx/query-92e196ea6783df5abef1ca0b0c3e7eb67bbd30ba8866de5c9d353b597fa26b5a.json b/rust/personhog-identity/.sqlx/query-92e196ea6783df5abef1ca0b0c3e7eb67bbd30ba8866de5c9d353b597fa26b5a.jsonnew file mode 100644index 000000000000..d873fd2b80fa--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-92e196ea6783df5abef1ca0b0c3e7eb67bbd30ba8866de5c9d353b597fa26b5a.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE lifecycle_op_person SET moved = $2 WHERE op_id = $1 AND role = $3",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Jsonb",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "92e196ea6783df5abef1ca0b0c3e7eb67bbd30ba8866de5c9d353b597fa26b5a"+}diff --git a/rust/personhog-identity/.sqlx/query-99eac54ad5e1c689f1782d8b1e7e828a0d58fdb026e2c85b2d8c201e566c8f21.json b/rust/personhog-identity/.sqlx/query-99eac54ad5e1c689f1782d8b1e7e828a0d58fdb026e2c85b2d8c201e566c8f21.jsonnew file mode 100644index 000000000000..063551976c38--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-99eac54ad5e1c689f1782d8b1e7e828a0d58fdb026e2c85b2d8c201e566c8f21.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person lop\n SET status = $4, sealed = u.sealed\n FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, sealed)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n AND lop.status IN ('marked', 'sealed')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8Array",+ "JsonbArray",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "99eac54ad5e1c689f1782d8b1e7e828a0d58fdb026e2c85b2d8c201e566c8f21"+}diff --git a/rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.json b/rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.jsonnew file mode 100644index 000000000000..b212eacdd97e--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2),\n attempt = attempt + 1,\n parked_at = NULL,\n parked_reason = NULL\n WHERE op_id = $1 AND completed_at IS NULL\n AND (lease_expires_at IS NULL OR lease_expires_at < now())\n AND (parked_at IS NULL OR $3)\n RETURNING attempt\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "attempt",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Float8",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23"+}diff --git a/rust/personhog-identity/.sqlx/query-b67ee4c93677a7c1ebc77814acba6ad51cd1a09ccbfe469af2ae1f3ffc19549a.json b/rust/personhog-identity/.sqlx/query-b67ee4c93677a7c1ebc77814acba6ad51cd1a09ccbfe469af2ae1f3ffc19549a.jsonnew file mode 100644index 000000000000..f690248d2ae9--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-b67ee4c93677a7c1ebc77814acba6ad51cd1a09ccbfe469af2ae1f3ffc19549a.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "status",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b67ee4c93677a7c1ebc77814acba6ad51cd1a09ccbfe469af2ae1f3ffc19549a"+}diff --git a/rust/personhog-identity/.sqlx/query-c06236beb4d3303a998ede6b8a950b2344d0ee3963d07816ba16f67090e90f65.json b/rust/personhog-identity/.sqlx/query-c06236beb4d3303a998ede6b8a950b2344d0ee3963d07816ba16f67090e90f65.jsonnew file mode 100644index 000000000000..9f9838481ef3--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-c06236beb4d3303a998ede6b8a950b2344d0ee3963d07816ba16f67090e90f65.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op\n SET parked_at = now(), parked_reason = $3, lease_expires_at = NULL\n WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "c06236beb4d3303a998ede6b8a950b2344d0ee3963d07816ba16f67090e90f65"+}diff --git a/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.json b/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.jsonnew file mode 100644index 000000000000..2305705fef8a--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH removed AS (\n DELETE FROM posthog_featureflaghashkeyoverride\n WHERE team_id = $1 AND person_id = ANY($2)\n RETURNING feature_flag_key, hash_key\n )\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT $1, $3, feature_flag_key, hash_key FROM removed\n ON CONFLICT (team_id, person_id, feature_flag_key) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431"+}diff --git a/rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.json b/rust/personhog-identity/.sqlx/query-ca22305afd5cd863bf9438805dc90a17393e0089548d49122e99f09ccfdd51af.jsonsimilarity index 61%rename from rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.jsonrename to rust/personhog-identity/.sqlx/query-ca22305afd5cd863bf9438805dc90a17393e0089548d49122e99f09ccfdd51af.jsonindex c7831ac77a21..8318d9996f6a 100644--- a/rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.json+++ b/rust/personhog-identity/.sqlx/query-ca22305afd5cd863bf9438805dc90a17393e0089548d49122e99f09ccfdd51af.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT op_id, op_type\n FROM lifecycle_op\n WHERE completed_at IS NULL\n AND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))\n OR lease_expires_at < now())\n ORDER BY created_at\n LIMIT $2\n ",+ "query": "\n SELECT op_id, op_type\n FROM lifecycle_op\n WHERE completed_at IS NULL\n AND parked_at IS NULL\n AND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))\n OR lease_expires_at < now())\n ORDER BY created_at\n LIMIT $2\n ","describe": {"columns": [{@@ -25,5 +25,5 @@false]},- "hash": "d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a"+ "hash": "ca22305afd5cd863bf9438805dc90a17393e0089548d49122e99f09ccfdd51af"}diff --git a/rust/personhog-identity/.sqlx/query-cf8b990cd88a4780087dcbba82b1bcca11fde4125a1df6f1e0ede518bac60e64.json b/rust/personhog-identity/.sqlx/query-cf8b990cd88a4780087dcbba82b1bcca11fde4125a1df6f1e0ede518bac60e64.jsonnew file mode 100644index 000000000000..f0c983c8e3c7--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-cf8b990cd88a4780087dcbba82b1bcca11fde4125a1df6f1e0ede518bac60e64.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = $3",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "cf8b990cd88a4780087dcbba82b1bcca11fde4125a1df6f1e0ede518bac60e64"+}diff --git a/rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.json b/rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.jsonnew file mode 100644index 000000000000..4da26399af3c--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.json@@ -0,0 +1,36 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT person_id, person_uuid, sealed as \"sealed!\" FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "person_uuid",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "sealed!",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034"+}diff --git a/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.json b/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.jsonnew file mode 100644index 000000000000..ff26aea95a1f--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_person p\n SET is_deleted = true,\n properties = '{}'::jsonb,\n properties_last_updated_at = '{}'::jsonb,\n properties_last_operation = '{}'::jsonb,\n version = (lop.sealed->>'version')::bigint + 1\n FROM lifecycle_op_person lop\n WHERE lop.op_id = $1 AND lop.role = $3 AND lop.status = $4\n AND p.team_id = $2 AND p.id = lop.person_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2"+}diff --git a/rust/personhog-identity/.sqlx/query-d5f075f020ee0cbf9110c35ad78cfdd0dc7d1da6a643e83518f79206cb29932a.json b/rust/personhog-identity/.sqlx/query-d5f075f020ee0cbf9110c35ad78cfdd0dc7d1da6a643e83518f79206cb29932a.jsonnew file mode 100644index 000000000000..0a2b7a5ea6c1--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-d5f075f020ee0cbf9110c35ad78cfdd0dc7d1da6a643e83518f79206cb29932a.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT moved FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "moved",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "d5f075f020ee0cbf9110c35ad78cfdd0dc7d1da6a643e83518f79206cb29932a"+}diff --git a/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.json b/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.jsonnew file mode 100644index 000000000000..f5703b1e44e4--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.person_id AS \"person_id!\"\n FROM unnest($2::bigint[]) AS c(person_id)\n WHERE (\n SELECT count(*)\n FROM (\n SELECT 1\n FROM posthog_persondistinctid d\n WHERE d.team_id = $1\n AND d.person_id = c.person_id\n AND d.is_deleted = false\n LIMIT $3::bigint + 1\n ) capped\n ) > $3::bigint\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "person_id!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array",+ "Int8"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef"+}diff --git a/rust/personhog-identity/.sqlx/query-dfb4201590984a3d47ecb011e5c80e4971b0137d3792d2027975fe7a4812069e.json b/rust/personhog-identity/.sqlx/query-dfb4201590984a3d47ecb011e5c80e4971b0137d3792d2027975fe7a4812069e.jsonnew file mode 100644index 000000000000..1263cd85eebf--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-dfb4201590984a3d47ecb011e5c80e4971b0137d3792d2027975fe7a4812069e.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status = $4\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "dfb4201590984a3d47ecb011e5c80e4971b0137d3792d2027975fe7a4812069e"+}diff --git a/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.json b/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.jsondeleted file mode 100644index 68606422c1e1..000000000000--- a/rust/personhog-identity/.sqlx/query-e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2)\n WHERE op_id = $1 AND completed_at IS NULL\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Float8"- ]- },- "nullable": []- },- "hash": "e8237596b83e713aa64709393ce30d4896b22187848738397d70f49ee03360f8"-}diff --git a/rust/personhog-identity/.sqlx/query-ef3b40cf647bda64a199a2496280cdc4560ecb69953a6a66cd8e64b773512b9f.json b/rust/personhog-identity/.sqlx/query-ef3b40cf647bda64a199a2496280cdc4560ecb69953a6a66cd8e64b773512b9f.jsonnew file mode 100644index 000000000000..031c702f7e82--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-ef3b40cf647bda64a199a2496280cdc4560ecb69953a6a66cd8e64b773512b9f.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sealed FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sealed",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "ef3b40cf647bda64a199a2496280cdc4560ecb69953a6a66cd8e64b773512b9f"+}diff --git a/rust/personhog-identity/.sqlx/query-efaa179f9f914c40ee24a2f614a4abcfeb3c41a39015f3c716fffd70becac1ea.json b/rust/personhog-identity/.sqlx/query-efaa179f9f914c40ee24a2f614a4abcfeb3c41a39015f3c716fffd70becac1ea.jsonnew file mode 100644index 000000000000..d34484af7511--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-efaa179f9f914c40ee24a2f614a4abcfeb3c41a39015f3c716fffd70becac1ea.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)\n SELECT $1, $2, u.person_id, u.person_uuid, $5, $6\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\n ON CONFLICT (op_id, person_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4",+ "Int8Array",+ "UuidArray",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "efaa179f9f914c40ee24a2f614a4abcfeb3c41a39015f3c716fffd70becac1ea"+}diff --git a/rust/personhog-identity/.sqlx/query-f2cc527fb20cb2d049918b76a47abaff1d5b0fc456873e2bfb5850aa5ce5a103.json b/rust/personhog-identity/.sqlx/query-f2cc527fb20cb2d049918b76a47abaff1d5b0fc456873e2bfb5850aa5ce5a103.jsonnew file mode 100644index 000000000000..8b439286e28a--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-f2cc527fb20cb2d049918b76a47abaff1d5b0fc456873e2bfb5850aa5ce5a103.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person lop\n SET moved = u.moved\n FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8Array",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2cc527fb20cb2d049918b76a47abaff1d5b0fc456873e2bfb5850aa5ce5a103"+}diff --git a/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.json b/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.jsonnew file mode 100644index 000000000000..0c19a9b439c8--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97"+}diff --git a/rust/personhog-identity/src/leader.rs b/rust/personhog-identity/src/leader.rsindex 4a22c2ea9cc4..e9a66b91a972 100644--- a/rust/personhog-identity/src/leader.rs+++ b/rust/personhog-identity/src/leader.rs@@ -3,7 +3,9 @@ use tonic::Status;use personhog_common::client::RouterClient;use personhog_proto::personhog::types::v1::{- UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,+ FencePersonRequest, FencePersonResponse, FoldPersonDocumentRequest, FoldPersonDocumentResponse,+ ReleaseFenceRequest, ReleaseFenceResponse, UpdatePersonPropertiesRequest,+ UpdatePersonPropertiesResponse,};/// Writes initial person properties on the creation branch. Production goes@@ -25,3 +27,48 @@ impl PropertyWriter for RouterClient {RouterClient::update_person_properties(self, request).await}}++/// The lifecycle sagas' leader surface: fence, release, and fold. Production+/// goes through the router (which routes each call to the owning leader);+/// tests mock this.+#[async_trait]+pub trait LifecycleLeader: Send + Sync {+ async fn fence_person(+ &self,+ request: FencePersonRequest,+ ) -> Result<FencePersonResponse, Status>;++ async fn release_fence(+ &self,+ request: ReleaseFenceRequest,+ ) -> Result<ReleaseFenceResponse, Status>;++ async fn fold_person_document(+ &self,+ request: FoldPersonDocumentRequest,+ ) -> Result<FoldPersonDocumentResponse, Status>;+}++#[async_trait]+impl LifecycleLeader for RouterClient {+ async fn fence_person(+ &self,+ request: FencePersonRequest,+ ) -> Result<FencePersonResponse, Status> {+ RouterClient::fence_person(self, request).await+ }++ async fn release_fence(+ &self,+ request: ReleaseFenceRequest,+ ) -> Result<ReleaseFenceResponse, Status> {+ RouterClient::release_fence(self, request).await+ }++ async fn fold_person_document(+ &self,+ request: FoldPersonDocumentRequest,+ ) -> Result<FoldPersonDocumentResponse, Status> {+ RouterClient::fold_person_document(self, request).await+ }+}diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rsindex 1d7c8f3a9bcc..b3bcbe433c09 100644--- a/rust/personhog-identity/src/lifecycle/delete.rs+++ b/rust/personhog-identity/src/lifecycle/delete.rs@@ -267,6 +267,26 @@ async fn mark(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {.await?;}+ // The live filter above and the mark insert run in different+ // statement snapshots, so a merge can destroy a person between them+ // and the insert lands on a corpse. Remove such marks here, in the+ // same transaction: the person reports as not_found and is never+ // touched again. From here on the mark keeps every held person alive.+ sqlx::query!(+ r#"+ DELETE FROM lifecycle_op_person lop+ WHERE lop.op_id = $1 AND lop.status = 'marked'+ AND NOT EXISTS (+ SELECT 1 FROM posthog_person p+ WHERE p.team_id = $2 AND p.id = lop.person_id AND p.is_deleted = false+ )+ "#,+ op.op_id,+ team_id,+ )+ .execute(&mut *tx)+ .await?;+let claims: i64 = sqlx::query_scalar!(r#"SELECT count(*) as "count!" FROM lifecycle_op_person@@ -510,10 +530,9 @@ async fn complete(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {/// One outcome entry per requested person id, in request order, from the/// per-person rows: `deleted` and `skipped_conflict` map to themselves; a-/// missing row means no live person existed at mark time (`not_found`). A-/// row still `marked`/`sealed` at completion means the person row vanished-/// under us mid-saga — impossible while the saga is the only deleter (the-/// per-team exclusivity rollout) — and is reported `not_found`.+/// missing row means no live person existed at claim time (`not_found`).+/// A row still `marked`/`sealed` at completion should be unreachable and+/// reports `not_found`.async fn build_outcome(tx: &mut Tx<'_>,op_id: Uuid,diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rsindex 3ab214830722..741a46385fce 100644--- a/rust/personhog-identity/src/lifecycle/engine.rs+++ b/rust/personhog-identity/src/lifecycle/engine.rs@@ -32,6 +32,9 @@ pub const STEP_ABORTED: &str = "aborted";const OPS_COMPLETED_TOTAL: &str = "personhog_lifecycle_ops_completed_total";const SWEEPER_RESUMED_TOTAL: &str = "personhog_lifecycle_sweeper_resumed_total";+const STEP_FAILURES_TOTAL: &str = "personhog_lifecycle_step_failures_total";+const OPS_PARKED_TOTAL: &str = "personhog_lifecycle_ops_parked_total";+const OPS_PARKED: &str = "personhog_lifecycle_ops_parked";/// How many abandoned ops one sweep pass will pick up.const SWEEP_BATCH_SIZE: i64 = 100;@@ -48,11 +51,34 @@ pub enum SagaError {/// Another instance held the lease past our deadline.#[error("another instance is driving this operation")]Busy,+ /// 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.+ #[error("leader call failed: {0}")]+ Leader(Box<Status>),+ /// A leader RPC was refused definitively: the request itself failed+ /// the leader's verification, so retries cannot succeed. Drivers+ /// unwind where they still can (the merge driver aborts before the+ /// flip); a refusal that reaches the engine parks the op.+ #[error("leader refused: {0}")]+ LeaderRefused(Box<Status>),/// State this engine or driver cannot interpret.#[error("corrupt saga state: {0}")]CorruptState(String),}+impl SagaError {+ /// Classify a leader RPC failure: a semantic refusal is definitive+ /// and never retried; everything else is transient and retried.+ pub fn leader(status: Status) -> Self {+ if personhog_common::grpc::is_semantic_refusal(&status) {+ SagaError::LeaderRefused(Box::new(status))+ } else {+ SagaError::Leader(Box::new(status))+ }+ }+}+impl From<SagaError> for Status {fn from(err: SagaError) -> Status {match err {@@ -61,6 +87,14 @@ impl From<SagaError> for Status {SagaError::Busy => Status::unavailable("another instance is driving this operation; retry with the same op_id",),+ SagaError::Leader(status) => Status::unavailable(format!(+ "leader call failed ({}: {}); retry with the same op_id",+ status.code(),+ status.message()+ )),+ // Passed through verbatim so the caller sees a definitive+ // refusal, not a retriable error to loop on.+ SagaError::LeaderRefused(status) => *status,SagaError::CorruptState(msg) => Status::internal(msg),}}@@ -136,6 +170,25 @@ impl Engine {op_id: Uuid,team_id: i64,request: &Value,+ ) -> Result<OpRow, SagaError> {+ self.create_or_attach(driver, op_id, team_id, request)+ .await?;+ self.drive(driver, op_id, true).await+ }++ /// The create-or-attach half of [`execute`], without driving: create+ /// the op if it is new, verify an existing op matches the request, and+ /// return the current row. Lets tests and tooling walk an op step by+ /// step with [`step_once`].+ ///+ /// [`execute`]: Engine::execute+ /// [`step_once`]: Engine::step_once+ pub async fn create_or_attach(+ &self,+ driver: &dyn OpDriver,+ op_id: Uuid,+ team_id: i64,+ request: &Value,) -> Result<OpRow, SagaError> {sqlx::query!(r#"@@ -160,8 +213,38 @@ impl Engine {"op {op_id} already exists with a different request")));}+ Ok(row)+ }- self.drive(driver, op_id, true).await+ /// Run exactly one step of an existing op and return the reloaded row;+ /// a terminal row is returned as-is. Skips the lease machinery — the+ /// lease is a throttle, not a lock (see the module docs), so a+ /// concurrent driver stays correct either way. This is the walkthrough+ /// entry point for tests and tooling that assert state between steps;+ /// `team_id` must match the op's.+ pub async fn step_once(+ &self,+ driver: &dyn OpDriver,+ op_id: Uuid,+ team_id: i64,+ ) -> Result<OpRow, SagaError> {+ let Some(row) = self.load(op_id).await? else {+ return Err(SagaError::CorruptState(format!(+ "op {op_id} does not exist"+ )));+ };+ if row.team_id != team_id {+ return Err(SagaError::RequestMismatch(format!(+ "op {op_id} belongs to a different team"+ )));+ }+ if row.completed_at.is_some() {+ return Ok(row);+ }+ driver.run_step(&self.pool, &row).await?;+ self.load(op_id).await?.ok_or_else(|| {+ SagaError::CorruptState(format!("op {op_id} vanished while being driven"))+ })}/// Drive an existing op (sweeper entry point — no create, no request@@ -222,7 +305,7 @@ impl Engine {continue;}}- None => match self.try_claim(op_id).await? {+ None => match self.try_claim(op_id, wait_for_lease).await? {Some(attempt) => {claim_attempt = Some(attempt);if attempt >= self.config.attempt_alert_threshold {@@ -248,6 +331,51 @@ impl Engine {}if let Err(err) = driver.run_step(&self.pool, &row).await {+ // Attributable escalation: a persistently failing op (a+ // corrupt row, a wedged leader call) shows up as this+ // counter climbing for one op_type/kind, not as generic+ // retry noise. Alert on it — a wedged op can hold fences.+ let kind = match &err {+ SagaError::Db(_) => "db",+ 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",+ };+ common_metrics::inc(+ STEP_FAILURES_TOTAL,+ &[+ ("op_type".to_string(), row.op_type.clone()),+ ("kind".to_string(), kind.to_string()),+ ],+ 1,+ );+ if let SagaError::LeaderRefused(status) = &err {+ // Retrying a refusal cannot succeed, and the sweeper+ // looping on it would hold this op's fences forever.+ // Park it; only an explicit retry with the same op_id+ // resumes a parked op.+ if let Some(attempt) = claim_attempt {+ match self.park(op_id, attempt, &row, status).await {+ Ok(true) => {}+ // The park lost its compare-and-swap: another+ // driver claimed or completed the op, so this+ // refusal is stale. Answer Busy, never a+ // definitive refusal for an op that may yet+ // complete.+ Ok(false) => return Err(SagaError::Busy),+ // Parking failed: drop the lease anyway; the+ // sweeper will re-drive into the refusal and+ // park then.+ Err(_) => {+ self.release_lease(op_id, attempt).await.ok();+ }+ }+ }+ return Err(err);+ }// Drop the lease so an immediate retry doesn't wait it out.if let Some(attempt) = claim_attempt {self.release_lease(op_id, attempt).await.ok();@@ -274,23 +402,86 @@ impl Engine {/// Claim the op if its lease is free or lapsed. Returns the new attempt/// count on success, None when another instance holds a live lease.- async fn try_claim(&self, op_id: Uuid) -> Result<Option<i32>, sqlx::Error> {+ /// Only an explicit retry (`unpark`, the execute path) may claim a+ /// parked op; the sweeper cannot, even when a park lands after its+ /// scan.+ async fn try_claim(&self, op_id: Uuid, unpark: bool) -> Result<Option<i32>, sqlx::Error> {sqlx::query_scalar!(r#"UPDATE lifecycle_opSET lease_expires_at = now() + make_interval(secs => $2),- attempt = attempt + 1+ attempt = attempt + 1,+ parked_at = NULL,+ parked_reason = NULLWHERE op_id = $1 AND completed_at IS NULLAND (lease_expires_at IS NULL OR lease_expires_at < now())+ AND (parked_at IS NULL OR $3)RETURNING attempt"#,op_id,self.config.lease.as_secs_f64(),+ unpark,).fetch_optional(&self.pool).await}+ /// Park an op after a definitive leader refusal: record when and why,+ /// and drop the lease so an explicit retry need not wait it out.+ /// Guarded by `attempt` like renew/release, so a displaced driver+ /// cannot park a stealer's op. Returns whether the park won.+ async fn park(+ &self,+ op_id: Uuid,+ attempt: i32,+ 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 parked = sqlx::query!(+ r#"+ UPDATE lifecycle_op+ SET parked_at = now(), parked_reason = $3, lease_expires_at = NULL+ WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2+ "#,+ op_id,+ attempt,+ reason,+ )+ .execute(&self.pool)+ .await?+ .rows_affected()+ > 0;+ if parked {+ tracing::error!(+ op_id = %op_id,+ op_type = %row.op_type,+ step = %row.step,+ reason = %reason,+ message = %status.message(),+ "leader definitively refused a lifecycle op step; op parked until explicitly retried"+ );+ common_metrics::inc(+ OPS_PARKED_TOTAL,+ &[+ ("op_type".to_string(), row.op_type.clone()),+ ("reason".to_string(), reason),+ ],+ 1,+ );+ }+ Ok(parked)+ }+/// Extend our lease. Returns false when the lease is no longer ours/// (another driver claimed the op and bumped `attempt`).async fn renew_lease(&self, op_id: Uuid, attempt: i32) -> Result<bool, sqlx::Error> {@@ -320,16 +511,17 @@ impl Engine {Ok(())}- /// One sweeper pass: resume abandoned ops — incomplete, and either never- /// claimed (older than one lease, so a freshly created op isn't stolen- /// from the RPC that is about to claim it) or with a lapsed lease.- /// Returns how many ops reached a terminal step.+ /// One sweeper pass: resume abandoned ops, meaning incomplete, not+ /// parked, and either with a lapsed lease or never claimed for longer+ /// than one lease (so a freshly created op isn't stolen from the RPC+ /// about to claim it). Returns how many ops reached a terminal step.pub async fn sweep(&self, drivers: &[&dyn OpDriver]) -> Result<u32, SagaError> {let abandoned = sqlx::query!(r#"SELECT op_id, op_typeFROM lifecycle_opWHERE completed_at IS NULL+ AND parked_at IS NULLAND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))OR lease_expires_at < now())ORDER BY created_at@@ -353,15 +545,33 @@ impl Engine {resumed += 1;common_metrics::inc(SWEEPER_RESUMED_TOTAL, &[], 1);}- // Claimed by another driver between our scan and now, so it- // is live, not abandoned — leave it to its owner.+ // Claimed by another driver (or parked) between our scan+ // and now, so it is no longer ours to drive.Err(SagaError::Busy) => {}+ Err(err @ SagaError::LeaderRefused(_)) => {+ tracing::warn!(op_id = %op.op_id, error = %err,+ "sweeper resume was definitively refused; op is parked until explicitly retried");+ }Err(err) => {tracing::warn!(op_id = %op.op_id, error = %err,"sweeper failed to resume op; will retry next pass");}}}++ // The park counter dies with the process, so a gauge refreshed+ // every pass keeps parked ops visible across restarts. Telemetry+ // only: a failure must not fail a pass whose resumes succeeded.+ match sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM lifecycle_op WHERE completed_at IS NULL AND parked_at IS NOT NULL"#+ )+ .fetch_one(&self.pool)+ .await+ {+ Ok(parked) => common_metrics::gauge(OPS_PARKED, &[], parked as f64),+ Err(e) => tracing::warn!(error = %e, "failed to refresh the parked-ops gauge"),+ }+Ok(resumed)}diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rsnew file mode 100644index 000000000000..83544f10d79c--- /dev/null+++ b/rust/personhog-identity/src/lifecycle/merge.rs@@ -0,0 +1,1715 @@+//! The merge saga's step handlers.+//!+//! Steps run in order: `started → claimed → sources_sealed →+//! document_folded → flipped → completed`. `aborted` is reachable from+//! every handler up to and including the fold; the flip is the point of+//! no return, after which the op can only complete (or park on a+//! definitive leader refusal).+//!+//! Two rules make every step safe to re-run (the engine's lease is a+//! throttle, not a lock, so any step may execute more than once):+//!+//! - Each step commits its Postgres work in the same transaction as its+//! step advance, so a lost step CAS rolls the work back with it.+//! - Leader calls (fence, fold, release) cannot roll back with a lost+//! CAS, so every leader call is convergent under repetition: a re-run+//! step re-issues the call and lands in the same state.+//!+//! The driver receives the classified case-3 set of a MergePersons call:+//! source distinct ids that resolved to persons distinct from the+//! target. That classification is advisory. The claim step re-resolves+//! everything authoritatively inside its own transaction, because the+//! world can change between the handler and the saga.+//!+//! Durable per-op state beyond the step column lives on the op's+//! `lifecycle_op_person` rows. Source rows use the JSONB columns as the+//! schema intends: `sealed` freezes the fence snapshot, `moved` records+//! the repointed mapping rows for later ClickHouse emission (delete+//! parity). The target row's columns are repurposed as the op's scratch+//! anchor, which is safe because a target is never fenced (`sealed` is+//! otherwise unused) and a target's dids never move (`moved` is+//! otherwise unused): `moved` holds the per-did claim dispositions and+//! `sealed` holds the folded survivor document.++use std::collections::HashMap;+use std::sync::Arc;++use async_trait::async_trait;+use futures::stream::{self, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use sqlx::postgres::PgPool;+use tonic::{Code, Status};+use uuid::Uuid;++use personhog_proto::personhog::types::v1::{+ FencePersonRequest, FoldPersonDocumentRequest, LifecycleOpType, Person, ReleaseFenceRequest,+ ReleaseOutcome, SealedSourceSnapshot,+};++use crate::leader::LifecycleLeader;+use crate::lifecycle::engine::{+ advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,+ STEP_COMPLETED,+};++// Derived from the shared enum so the op-type string cannot drift from+// the leader's fence records or the lifecycle_op CHECK constraint.+pub const OP_TYPE_MERGE: &str = LifecycleOpType::Merge.as_op_type_str();++/// The merge saga's non-terminal steps, in order.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MergeStep {+ Started,+ Claimed,+ SourcesSealed,+ DocumentFolded,+ Flipped,+}++impl MergeStep {+ pub fn as_str(self) -> &'static str {+ match self {+ MergeStep::Started => "started",+ MergeStep::Claimed => "claimed",+ MergeStep::SourcesSealed => "sources_sealed",+ MergeStep::DocumentFolded => "document_folded",+ MergeStep::Flipped => "flipped",+ }+ }++ fn parse(step: &str) -> Option<Self> {+ match step {+ "started" => Some(MergeStep::Started),+ "claimed" => Some(MergeStep::Claimed),+ "sources_sealed" => Some(MergeStep::SourcesSealed),+ "document_folded" => Some(MergeStep::DocumentFolded),+ "flipped" => Some(MergeStep::Flipped),+ _ => None,+ }+ }+}++/// The frozen `lifecycle_op.request` payload for a merge op: the case-3+/// set the handler classified, plus the merge event's property payloads.+/// `sources` order is property precedence (earlier beats later).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MergeRequest {+ pub target_distinct_id: String,+ pub sources: Vec<MergeSourceEntry>,+ #[serde(default)]+ pub event_set: Value,+ #[serde(default)]+ pub event_set_once: Value,+ /// `$merge_dangerously` legally merges identified sources; `$identify`+ /// does not.+ #[serde(default)]+ pub allow_identified_sources: bool,+ /// Per-source distinct-id count guard. Required: an unlimited merge+ /// would make the flip's repoint an unbounded statement.+ pub move_limit: i64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MergeSourceEntry {+ pub distinct_id: String,+ /// The `$identify` event that contributed this pair; carried for the+ /// caller's warning correlation, unused by the saga itself.+ #[serde(default)]+ pub event_uuid: String,+}++/// The recorded `lifecycle_op.outcome` payload: one entry per requested+/// source distinct id, in request order, plus the survivor document when+/// the merge committed.+#[derive(Debug, Serialize, Deserialize)]+pub struct MergeOutcome {+ pub aborted: bool,+ /// The folded survivor document (id, uuid, properties, created_at,+ /// is_identified, version). Absent when the op aborted.+ pub survivor: Option<Value>,+ pub results: Vec<MergeSourceRecord>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct MergeSourceRecord {+ pub distinct_id: String,+ pub outcome: String,+}++pub const OUTCOME_MERGED: &str = "merged";+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_ERROR: &str = "error";++/// Per-person row statuses this driver writes. `marked`/`sealed` are the+/// mark-covered set (the partial unique index); everything else releases+/// the mark. `dropped` and `aborted` are merge-specific settlements the+/// schema comment does not list — the column is unconstrained TEXT and the+/// mark index only cares that they are outside `('marked','sealed')`.+const STATUS_MARKED: &str = "marked";+const STATUS_SEALED: &str = "sealed";+const STATUS_DELETED: &str = "deleted";+const STATUS_CLEARED: &str = "cleared";+const STATUS_DROPPED: &str = "dropped";+const STATUS_ABORTED: &str = "aborted";+const STATUS_SKIPPED_CONFLICT: &str = "skipped_conflict";++const ROLE_TARGET: &str = "target";+const ROLE_SOURCE: &str = "source";++/// Cap on concurrent leader RPCs per fan-out (fence, release): a bulk+/// merge must not burst the router with one in-flight call per source.+const LEADER_CALL_CONCURRENCY: usize = 8;++const STEPS_TOTAL: &str = "personhog_lifecycle_merge_steps_total";+const OUTCOMES_TOTAL: &str = "personhog_lifecycle_merge_outcomes_total";++fn record_transition(from: &str, to: &str) {+ common_metrics::inc(+ STEPS_TOTAL,+ &[+ ("from".to_string(), from.to_string()),+ ("to".to_string(), to.to_string()),+ ],+ 1,+ );+}++fn record_outcomes(outcome: &Value) {+ let Ok(parsed) = serde_json::from_value::<MergeOutcome>(outcome.clone()) else {+ return;+ };+ for label in [+ OUTCOME_MERGED,+ OUTCOME_NOOP_SAME_PERSON,+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED,+ OUTCOME_SKIPPED_CONFLICT,+ OUTCOME_SKIPPED_MOVE_LIMIT,+ OUTCOME_ERROR,+ ] {+ let count = parsed.results.iter().filter(|r| r.outcome == label).count();+ if count > 0 {+ common_metrics::inc(+ OUTCOMES_TOTAL,+ &[("outcome".to_string(), label.to_string())],+ count as u64,+ );+ }+ }+}++/// One requested source did's claim-time decision, persisted in the target+/// row's `moved` column so the terminal outcome can be rebuilt after any+/// crash. `pending_merge` resolves to `merged` (row settled `deleted`) or+/// to the drop reason recorded when the source fell out.+#[derive(Debug, Clone, Serialize, Deserialize)]+struct Disposition {+ distinct_id: String,+ /// The person the did resolved to at claim time; absent when it+ /// resolved to nothing.+ person_id: Option<i64>,+ decision: String,+}++const DECISION_PENDING_MERGE: &str = "pending_merge";++#[derive(Debug, Serialize, Deserialize)]+struct ClaimRecord {+ dispositions: Vec<Disposition>,+}++/// The fence snapshot persisted per source row (`sealed`), and the exact+/// inputs the fold and the committed release replay from. `created_at` is+/// in the unit `Person.created_at` carries (epoch seconds today).+#[derive(Debug, Clone, Serialize, Deserialize)]+struct SealedSnapshot {+ version: i64,+ created_at: i64,+ is_identified: bool,+ properties: Value,+ // Defaulted so seals written before the field existed still parse.+ #[serde(default)]+ last_seen_at: Option<i64>,+}++pub struct MergeDriver {+ leader: Arc<dyn LifecycleLeader>,+}++impl MergeDriver {+ pub fn new(leader: Arc<dyn LifecycleLeader>) -> Self {+ Self { leader }+ }+}++#[async_trait]+impl OpDriver for MergeDriver {+ fn op_type(&self) -> &'static str {+ OP_TYPE_MERGE+ }++ fn initial_step(&self) -> &'static str {+ MergeStep::Started.as_str()+ }++ async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let step = MergeStep::parse(&op.step).ok_or_else(|| {+ SagaError::CorruptState(format!(+ "merge op {} is on unknown step '{}'",+ op.op_id, op.step+ ))+ })?;+ match step {+ MergeStep::Started => self.claim(pool, op).await,+ MergeStep::Claimed => self.seal(pool, op).await,+ MergeStep::SourcesSealed => self.fold(pool, op).await,+ MergeStep::DocumentFolded => flip(pool, op).await,+ MergeStep::Flipped => self.complete(pool, op).await,+ }+ }+}++fn parse_request(op: &OpRow) -> Result<MergeRequest, SagaError> {+ let request: MergeRequest = serde_json::from_value(op.request.clone()).map_err(|e| {+ SagaError::CorruptState(format!(+ "merge op {} has a malformed request: {e}",+ op.op_id+ ))+ })?;+ // A non-positive limit would silently skip every source.+ if request.move_limit < 1 {+ return Err(SagaError::CorruptState(format!(+ "merge op {} has a non-positive move_limit ({})",+ op.op_id, request.move_limit+ )));+ }+ Ok(request)+}++/// A did's resolution on the primary: the live person its live mapping row+/// points at.+struct Resolution {+ person_id: i64,+ person_uuid: Uuid,+ is_identified: bool,+}++/// Post-insert reconciliation of the pending set against the fresh+/// resolve. A pending did that no longer resolves to its claimed person+/// was remapped by a concurrent identify — the flip will not repoint it,+/// so reporting it merged would be a lie; it settles as a retryable+/// conflict even when a sibling did keeps the person claimed. Returns the+/// claimed persons no pending did still reaches (to be dropped).+fn reconcile_pending_claims(+ dispositions: &mut [Disposition],+ claim_persons: &[(i64, Uuid, i32)],+ marked: &[i64],+ fresh: &HashMap<String, Resolution>,+) -> Vec<i64> {+ for d in dispositions.iter_mut() {+ if d.decision != DECISION_PENDING_MERGE {+ continue;+ }+ let Some(person_id) = d.person_id else {+ continue;+ };+ if !marked.contains(&person_id) {+ continue;+ }+ if fresh+ .get(&d.distinct_id)+ .is_none_or(|r| r.person_id != person_id)+ {+ d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();+ }+ }+ claim_persons+ .iter()+ .filter(|(person_id, _, _)| {+ marked.contains(person_id)+ && !dispositions.iter().any(|d| {+ d.decision == DECISION_PENDING_MERGE && d.person_id == Some(*person_id)+ })+ })+ .map(|(person_id, _, _)| *person_id)+ .collect()+}++async fn resolve_dids(+ tx: &mut Tx<'_>,+ team_id: i32,+ dids: &[String],+) -> Result<HashMap<String, Resolution>, SagaError> {+ let rows = sqlx::query!(+ r#"+ SELECT d.distinct_id, d.person_id as "person_id!", p.uuid as "person_uuid!",+ p.is_identified as "is_identified!"+ FROM posthog_persondistinctid d+ JOIN posthog_person p ON p.team_id = d.team_id AND p.id = d.person_id+ WHERE d.team_id = $1 AND d.distinct_id = ANY($2)+ AND d.is_deleted = false AND p.is_deleted = false+ "#,+ team_id,+ dids,+ )+ .fetch_all(&mut **tx)+ .await?;+ Ok(rows+ .into_iter()+ .map(|r| {+ (+ r.distinct_id,+ Resolution {+ person_id: r.person_id,+ person_uuid: r.person_uuid,+ is_identified: r.is_identified,+ },+ )+ })+ .collect())+}++impl MergeDriver {+ /// `started → claimed` (or `→ aborted`): re-resolve authoritatively,+ /// classify every source did, and claim the target plus every+ /// still-mergeable source person via the mark index — all in one+ /// transaction. Nothing outside this op's own rows is mutated, so the+ /// abort branch can end the op in the same commit.+ async fn claim(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let request = parse_request(op)?;+ let team_id = op.team_id as i32;+ let mut tx = pool.begin().await?;++ // Authoritative resolution: the handler's classification aged while+ // the op row traveled here.+ let mut all_dids: Vec<String> = Vec::with_capacity(request.sources.len() + 1);+ all_dids.push(request.target_distinct_id.clone());+ all_dids.extend(request.sources.iter().map(|s| s.distinct_id.clone()));+ all_dids.sort_unstable();+ all_dids.dedup();+ let resolved = resolve_dids(&mut tx, team_id, &all_dids).await?;++ let Some(target) = resolved.get(&request.target_distinct_id) else {+ // The target person vanished between classification and now. The+ // caller's re-drive (new op) re-classifies; this op has changed+ // nothing.+ let dispositions = request+ .sources+ .iter()+ .map(|s| Disposition {+ distinct_id: s.distinct_id.clone(),+ person_id: None,+ decision: OUTCOME_SKIPPED_CONFLICT.to_string(),+ })+ .collect();+ return abort_in_claim_tx(tx, op, dispositions).await;+ };+ let (target_person_id, target_person_uuid) = (target.person_id, target.person_uuid);++ // Classify each source did; collect the distinct persons to claim.+ // Two dids resolving to one person share a claim (first ordinal+ // wins the row's ordinal; both dids ride its fate).+ let mut dispositions: Vec<Disposition> = Vec::with_capacity(request.sources.len());+ let mut claim_persons: Vec<(i64, Uuid, i32)> = Vec::new();+ for (ordinal, source) in request.sources.iter().enumerate() {+ let Some(resolution) = resolved.get(&source.distinct_id) else {+ // Consumed by another lifecycle op (or never existed): a+ // retryable signal — the caller's re-drive re-classifies it.+ dispositions.push(Disposition {+ distinct_id: source.distinct_id.clone(),+ person_id: None,+ decision: OUTCOME_SKIPPED_CONFLICT.to_string(),+ });+ continue;+ };+ if resolution.person_id == target_person_id {+ dispositions.push(Disposition {+ distinct_id: source.distinct_id.clone(),+ person_id: Some(resolution.person_id),+ decision: OUTCOME_NOOP_SAME_PERSON.to_string(),+ });+ continue;+ }+ if resolution.is_identified && !request.allow_identified_sources {+ // Cheap Postgres pre-filter; the authoritative re-check runs+ // on the sealed state (Postgres lags the leader, and+ // is_identified only ever flips true, so this can only+ // under-drop, never over-drop).+ dispositions.push(Disposition {+ distinct_id: source.distinct_id.clone(),+ person_id: Some(resolution.person_id),+ decision: OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string(),+ });+ continue;+ }+ if !claim_persons+ .iter()+ .any(|(id, _, _)| *id == resolution.person_id)+ {+ claim_persons.push((resolution.person_id, resolution.person_uuid, ordinal as i32));+ }+ dispositions.push(Disposition {+ distinct_id: source.distinct_id.clone(),+ person_id: Some(resolution.person_id),+ decision: DECISION_PENDING_MERGE.to_string(),+ });+ }++ // The move-limit guard: a source with more distinct ids than the+ // caller's limit is skipped, not chunked; the caller applies its+ // merge-mode policy to the skip. The inner LIMIT stops each+ // candidate's scan at limit+1 rows, so an oversized person cannot+ // blow the statement timeout.+ let candidate_ids: Vec<i64> = claim_persons.iter().map(|(id, _, _)| *id).collect();+ let over: Vec<i64> = sqlx::query_scalar!(+ r#"+ SELECT c.person_id AS "person_id!"+ FROM unnest($2::bigint[]) AS c(person_id)+ WHERE (+ SELECT count(*)+ FROM (+ SELECT 1+ FROM posthog_persondistinctid d+ WHERE d.team_id = $1+ AND d.person_id = c.person_id+ AND d.is_deleted = false+ LIMIT $3::bigint + 1+ ) capped+ ) > $3::bigint+ "#,+ team_id,+ &candidate_ids,+ request.move_limit,+ )+ .fetch_all(&mut *tx)+ .await?;+ if !over.is_empty() {+ claim_persons.retain(|(id, _, _)| !over.contains(id));+ for d in dispositions.iter_mut() {+ if d.decision == DECISION_PENDING_MERGE+ && d.person_id.is_some_and(|id| over.contains(&id))+ {+ d.decision = OUTCOME_SKIPPED_MOVE_LIMIT.to_string();+ }+ }+ }++ // The mark: one sorted insert covering the target and every source+ // person, so concurrent ops touching the same persons take row+ // locks in the same order. Inserting is claiming; a unique+ // violation on the partial mark index IS the conflict.+ let mut rows: Vec<(i64, Uuid, &str, Option<i32>)> = claim_persons+ .iter()+ .map(|(id, uuid, ordinal)| (*id, *uuid, ROLE_SOURCE, Some(*ordinal)))+ .collect();+ rows.push((target_person_id, target_person_uuid, ROLE_TARGET, None));+ rows.sort_unstable_by_key(|(id, _, _, _)| *id);+ let ids: Vec<i64> = rows.iter().map(|r| r.0).collect();+ let uuids: Vec<Uuid> = rows.iter().map(|r| r.1).collect();+ let roles: Vec<String> = rows.iter().map(|r| r.2.to_string()).collect();+ let ordinals: Vec<Option<i32>> = rows.iter().map(|r| r.3).collect();++ let marked: Vec<i64> = sqlx::query_scalar!(+ r#"+ INSERT INTO lifecycle_op_person+ (op_id, team_id, person_id, person_uuid, role, ordinal, status)+ SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, $6+ FROM unnest($3::bigint[], $4::uuid[], $5::text[], $7::int[])+ AS u(person_id, person_uuid, role, ordinal)+ ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING+ RETURNING person_id+ "#,+ op.op_id,+ team_id,+ &ids,+ &uuids,+ roles.as_slice(),+ STATUS_MARKED,+ ordinals.as_slice() as _,+ )+ .fetch_all(&mut *tx)+ .await?;++ if !marked.contains(&target_person_id) {+ // Another live op holds the target: abort. Flip whatever this+ // insert claimed back out of the mark set in the same commit —+ // nothing outside our rows has happened.+ sqlx::query!(+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = $3",+ op.op_id,+ STATUS_ABORTED,+ STATUS_MARKED,+ )+ .execute(&mut *tx)+ .await?;+ for d in dispositions.iter_mut() {+ if d.decision == DECISION_PENDING_MERGE {+ d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();+ }+ }+ return abort_in_claim_tx(tx, op, dispositions).await;+ }++ // Sources another live op holds: record the skip (the status keeps+ // the row outside the mark index). ON CONFLICT on the primary key+ // covers a concurrent driver of this same op racing us.+ let conflicted: Vec<(i64, Uuid)> = claim_persons+ .iter()+ .filter(|(id, _, _)| !marked.contains(id))+ .map(|(id, uuid, _)| (*id, *uuid))+ .collect();+ if !conflicted.is_empty() {+ let conflicted_ids: Vec<i64> = conflicted.iter().map(|c| c.0).collect();+ let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|c| c.1).collect();+ sqlx::query!(+ r#"+ INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)+ SELECT $1, $2, u.person_id, u.person_uuid, $5, $6+ FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)+ ON CONFLICT (op_id, person_id) DO NOTHING+ "#,+ op.op_id,+ team_id,+ &conflicted_ids,+ &conflicted_uuids,+ ROLE_SOURCE,+ STATUS_SKIPPED_CONFLICT,+ )+ .execute(&mut *tx)+ .await?;+ for d in dispositions.iter_mut() {+ if d.decision == DECISION_PENDING_MERGE+ && d.person_id.is_some_and(|id| conflicted_ids.contains(&id))+ {+ d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();+ }+ }+ }++ // Post-insert liveness recheck. The resolve above and the insert run+ // in different statement snapshots, so a destroyer that tombstoned a+ // person and settled its mark between them makes our insert succeed+ // on a corpse. One fresh statement re-verifies person liveness and+ // mapping stability; after it, mark + liveness hold in one snapshot+ // and nothing can destroy or re-map a claimed person (the mark+ // blocks every lifecycle op and identity mutation).+ let fresh = resolve_dids(&mut tx, team_id, &all_dids).await?;+ let target_still_live = fresh+ .get(&request.target_distinct_id)+ .is_some_and(|r| r.person_id == target_person_id);+ if !target_still_live {+ sqlx::query!(+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = $3",+ op.op_id,+ STATUS_ABORTED,+ STATUS_MARKED,+ )+ .execute(&mut *tx)+ .await?;+ for d in dispositions.iter_mut() {+ if d.decision == DECISION_PENDING_MERGE {+ d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();+ }+ }+ return abort_in_claim_tx(tx, op, dispositions).await;+ }+ let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &marked, &fresh);+ if !dropped.is_empty() {+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND person_id = ANY($3) AND status = $4+ "#,+ op.op_id,+ STATUS_DROPPED,+ &dropped,+ STATUS_MARKED,+ )+ .execute(&mut *tx)+ .await?;+ }++ if !dispositions+ .iter()+ .any(|d| d.decision == DECISION_PENDING_MERGE)+ {+ // Every source fell out: release the target's just-taken mark+ // and end the op. No fences exist yet.+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND role = $3 AND status = $4+ "#,+ op.op_id,+ STATUS_CLEARED,+ ROLE_TARGET,+ STATUS_MARKED,+ )+ .execute(&mut *tx)+ .await?;+ return abort_in_claim_tx(tx, op, dispositions).await;+ }++ // Persist the claim record on the target row; the terminal outcome+ // is rebuilt from it after any crash.+ let claim_record = serde_json::to_value(ClaimRecord { dispositions }).map_err(|e| {+ SagaError::CorruptState(format!("failed to serialize claim record: {e}"))+ })?;+ sqlx::query!(+ "UPDATE lifecycle_op_person SET moved = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ claim_record,+ ROLE_TARGET,+ )+ .execute(&mut *tx)+ .await?;++ if !advance_step_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::Started.as_str(),+ MergeStep::Claimed.as_str(),+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(MergeStep::Started.as_str(), MergeStep::Claimed.as_str());+ Ok(())+ }+}++/// End an op inside the claim transaction: nothing outside this op's own+/// rows has been mutated, so recording the outcome and the terminal step+/// in the same commit is the whole abort.+async fn abort_in_claim_tx(+ mut tx: Tx<'_>,+ op: &OpRow,+ dispositions: Vec<Disposition>,+) -> Result<(), SagaError> {+ let outcome = outcome_from_dispositions(&dispositions, true, None, &HashMap::new())?;+ if !complete_op_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::Started.as_str(),+ STEP_ABORTED,+ &outcome,+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(MergeStep::Started.as_str(), STEP_ABORTED);+ record_outcomes(&outcome);+ Ok(())+}++impl MergeDriver {+ /// `claimed → sources_sealed` (or `→ aborted`): fence every claimed+ /// source's owning leader and persist the sealed snapshots. The fences+ /// are the step's only external effect and re-fencing with the same+ /// op_id is a re-seal returning identical state (the fence itself+ /// froze the person), so the fan-out is safe to repeat; the snapshots+ /// and the step CAS commit together afterwards.+ ///+ /// Known residual: a stale duplicate driver can re-fence a source the+ /// winner already dropped (its settling TX loses the CAS, but its+ /// fence call does not roll back). No later step releases a dropped+ /// source, so the orphan clears via the leader's ghost-fence healer on+ /// the next rejected write (or a partition handoff) — the same class+ /// the takeover scan can mint, bounded the same way.+ async fn seal(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let request = parse_request(op)?;+ let sources = sqlx::query!(+ r#"+ SELECT person_id, person_uuid FROM lifecycle_op_person+ WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')+ "#,+ op.op_id,+ ROLE_SOURCE,+ )+ .fetch_all(pool)+ .await?;++ let mut sealed: Vec<(i64, SealedSnapshot)> = Vec::new();+ let mut vanished: Vec<i64> = Vec::new();+ let fence_calls: Vec<_> = sources+ .iter()+ .map(|source| {+ let leader = Arc::clone(&self.leader);+ let request = FencePersonRequest {+ team_id: op.team_id,+ person_id: source.person_id,+ op_id: op.op_id.to_string(),+ op_type: LifecycleOpType::Merge.into(),+ };+ let person_id = source.person_id;+ async move { (person_id, leader.fence_person(request).await) }+ })+ .collect();+ let fence_results: Vec<_> = stream::iter(fence_calls)+ .buffer_unordered(LEADER_CALL_CONCURRENCY)+ .collect()+ .await;+ for (person_id, result) in fence_results {+ match result {+ Ok(response) => {+ let person = response.sealed.ok_or_else(|| {+ SagaError::CorruptState(format!(+ "fence response for person {person_id} carries no sealed state"+ ))+ })?;+ sealed.push((person_id, snapshot_from_sealed(&person)?));+ }+ Err(status) if status.code() == Code::NotFound => {+ // Unreachable while the mark holds (the claim recheck+ // closed the pre-mark race), so a hit here is an+ // anomaly worth shouting about — but dropping the+ // source is still the correct settlement: it no longer+ // exists, and no fence was installed.+ tracing::error!(+ op_id = %op.op_id,+ person_id,+ "marked merge source vanished before its fence; dropping it"+ );+ vanished.push(person_id);+ }+ Err(status) => {+ // Fenced-by-another-op can only be a ghost fence (a+ // real foreign op would need a live mark we hold); the+ // leader's healer clears it on observation. Transient+ // failures retry the step; a refusal backs the op out.+ return match SagaError::leader(status) {+ SagaError::LeaderRefused(status) => {+ self.abort_refused(pool, op, MergeStep::Claimed, &status)+ .await+ }+ err => Err(err),+ };+ }+ }+ }++ // The authoritative is_identified check, on the sealed state the+ // fold would consume. An identified source drops out; its fence is+ // released (produce nothing) before its mark settles below.+ let mut identified: Vec<i64> = Vec::new();+ if !request.allow_identified_sources {+ let (keep, drop_identified): (Vec<_>, Vec<_>) = sealed+ .into_iter()+ .partition(|(_, snapshot)| !snapshot.is_identified);+ sealed = keep;+ identified = drop_identified.iter().map(|(id, _)| *id).collect();+ let identified_pairs: Vec<(i64, Uuid)> = sources+ .iter()+ .filter(|s| identified.contains(&s.person_id))+ .map(|s| (s.person_id, s.person_uuid))+ .collect();+ self.release_fences(op, &identified_pairs).await?;+ }++ if sealed.is_empty() {+ // Every source fell out between claim and seal: abort. Fences+ // for remaining marked sources were never installed (vanished)+ // or already released (identified); release again vacuously for+ // crash-resilience, then settle the rows.+ let remaining: Vec<(i64, Uuid)> = sources+ .iter()+ .map(|s| (s.person_id, s.person_uuid))+ .collect();+ self.release_fences(op, &remaining).await?;+ let mut tx = pool.begin().await?;+ settle_drops(&mut tx, op, &vanished, &identified).await?;+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')+ "#,+ op.op_id,+ STATUS_ABORTED,+ ROLE_SOURCE,+ )+ .execute(&mut *tx)+ .await?;+ sqlx::query!(+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ STATUS_CLEARED,+ ROLE_TARGET,+ )+ .execute(&mut *tx)+ .await?;+ let outcome = build_outcome(&mut tx, op, true).await?;+ if !complete_op_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::Claimed.as_str(),+ STEP_ABORTED,+ &outcome,+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(MergeStep::Claimed.as_str(), STEP_ABORTED);+ record_outcomes(&outcome);+ return Ok(());+ }++ let mut tx = pool.begin().await?;+ settle_drops(&mut tx, op, &vanished, &identified).await?;+ let sealed_ids: Vec<i64> = sealed.iter().map(|(id, _)| *id).collect();+ let sealed_jsons: Vec<Value> = sealed+ .iter()+ .map(|(_, snapshot)| serde_json::to_value(snapshot))+ .collect::<Result<_, _>>()+ .map_err(|e| SagaError::CorruptState(format!("failed to serialize seal: {e}")))?;+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person lop+ SET status = $4, sealed = u.sealed+ FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, sealed)+ WHERE lop.op_id = $1 AND lop.person_id = u.person_id+ AND lop.status IN ('marked', 'sealed')+ "#,+ op.op_id,+ &sealed_ids,+ &sealed_jsons,+ STATUS_SEALED,+ )+ .execute(&mut *tx)+ .await?;++ if !advance_step_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::Claimed.as_str(),+ MergeStep::SourcesSealed.as_str(),+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(+ MergeStep::Claimed.as_str(),+ MergeStep::SourcesSealed.as_str(),+ );+ 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.+ async fn abort_refused(+ &self,+ pool: &PgPool,+ op: &OpRow,+ from_step: MergeStep,+ status: &Status,+ ) -> Result<(), SagaError> {+ let live = sqlx::query!(+ r#"+ SELECT person_id, person_uuid FROM lifecycle_op_person+ WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')+ "#,+ op.op_id,+ ROLE_SOURCE,+ )+ .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!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')+ "#,+ op.op_id,+ STATUS_ABORTED,+ ROLE_SOURCE,+ )+ .execute(&mut *tx)+ .await?;+ sqlx::query!(+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ STATUS_CLEARED,+ ROLE_TARGET,+ )+ .execute(&mut *tx)+ .await?;+ let outcome = build_outcome(&mut tx, op, true).await?;+ if !complete_op_in_tx(+ &mut tx,+ op.op_id,+ from_step.as_str(),+ STEP_ABORTED,+ &outcome,+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ tracing::error!(+ op_id = %op.op_id,+ step = %from_step.as_str(),+ reason = %personhog_common::grpc::semantic_refusal_reason(status).unwrap_or("unknown"),+ message = %status.message(),+ "leader definitively refused a pre-flip merge step; op aborted and fences released"+ );+ record_transition(from_step.as_str(), STEP_ABORTED);+ record_outcomes(&outcome);+ Ok(())+ }++ /// Release fences with outcome `aborted` for the given persons,+ /// bounded-concurrently. Releasing a never-fenced person is a no-op at+ /// the leader, so callers pass every candidate rather than tracking+ /// which fences actually installed.+ async fn release_fences(&self, op: &OpRow, persons: &[(i64, Uuid)]) -> Result<(), SagaError> {+ let calls: Vec<_> = persons+ .iter()+ .map(|(person_id, person_uuid)| {+ let leader = Arc::clone(&self.leader);+ let request = ReleaseFenceRequest {+ team_id: op.team_id,+ person_id: *person_id,+ person_uuid: person_uuid.to_string(),+ op_id: op.op_id.to_string(),+ outcome: ReleaseOutcome::Aborted.into(),+ sealed_version: None,+ created_at: 0,+ };+ async move { leader.release_fence(request).await }+ })+ .collect();+ let results: Vec<_> = stream::iter(calls)+ .buffer_unordered(LEADER_CALL_CONCURRENCY)+ .collect()+ .await;+ for result in results {+ result.map_err(SagaError::leader)?;+ }+ Ok(())+ }+}++fn snapshot_from_sealed(person: &Person) -> Result<SealedSnapshot, SagaError> {+ let properties = if person.properties.is_empty() {+ Value::Object(serde_json::Map::new())+ } else {+ serde_json::from_slice(&person.properties).map_err(|e| {+ SagaError::CorruptState(format!("sealed properties do not parse as JSON: {e}"))+ })?+ };+ Ok(SealedSnapshot {+ version: person.version,+ created_at: person.created_at,+ is_identified: person.is_identified,+ properties,+ last_seen_at: person.last_seen_at,+ })+}++/// Settle sources that dropped out during the seal: `dropped` releases+/// their marks; the claim record's decisions flip to the drop reason.+async fn settle_drops(+ tx: &mut Tx<'_>,+ op: &OpRow,+ vanished: &[i64],+ identified: &[i64],+) -> Result<(), SagaError> {+ let all: Vec<i64> = vanished.iter().chain(identified.iter()).copied().collect();+ if all.is_empty() {+ return Ok(());+ }+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND person_id = ANY($3) AND status IN ('marked', 'sealed')+ "#,+ op.op_id,+ STATUS_DROPPED,+ &all,+ )+ .execute(&mut **tx)+ .await?;++ let mut record = claim_record(tx, op).await?;+ for disposition in record.dispositions.iter_mut() {+ if disposition.decision != DECISION_PENDING_MERGE {+ continue;+ }+ let Some(person_id) = disposition.person_id else {+ continue;+ };+ if vanished.contains(&person_id) {+ disposition.decision = OUTCOME_ERROR.to_string();+ } else if identified.contains(&person_id) {+ disposition.decision = OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string();+ }+ }+ let updated = serde_json::to_value(&record)+ .map_err(|e| SagaError::CorruptState(format!("failed to serialize claim record: {e}")))?;+ sqlx::query!(+ "UPDATE lifecycle_op_person SET moved = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ updated,+ ROLE_TARGET,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++impl MergeDriver {+ /// `sources_sealed → document_folded`: one FoldPersonDocument call to+ /// the target's leader with the sealed snapshots in precedence order.+ /// A re-driven fold on unchanged target state changes no content and+ /// only bumps the version, so a crash between the fold and the CAS is+ /// absorbed — up to the accepted re-appliable-merge residual: the+ /// target is never fenced, so a re-fold recomputes over writes that+ /// landed in between (see FoldPersonDocumentRequest.op_id in the+ /// proto). The folded document persists on the target row: the+ /// terminal outcome's survivor, durable without ever re-folding.+ async fn fold(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let request = parse_request(op)?;+ let target = target_row(pool, op).await?;+ let sources = sqlx::query!(+ r#"+ SELECT person_id, ordinal as "ordinal!", sealed as "sealed!" FROM lifecycle_op_person+ WHERE op_id = $1 AND role = $2 AND status = $3+ ORDER BY ordinal+ "#,+ op.op_id,+ ROLE_SOURCE,+ STATUS_SEALED,+ )+ .fetch_all(pool)+ .await?;++ // The fold verifies each snapshot's identity and orders by the+ // ordinal itself, so the request carries the recorded pair order+ // and the source's real identity fields.+ let mut snapshots: Vec<SealedSourceSnapshot> = Vec::with_capacity(sources.len());+ for source in &sources {+ let snapshot: SealedSnapshot =+ serde_json::from_value(source.sealed.clone()).map_err(|e| {+ SagaError::CorruptState(format!(+ "merge op {} source {} has a malformed seal: {e}",+ op.op_id, source.person_id+ ))+ })?;+ snapshots.push(SealedSourceSnapshot {+ person: Some(Person {+ id: source.person_id,+ team_id: op.team_id,+ properties: serde_json::to_vec(&snapshot.properties).map_err(|e| {+ SagaError::CorruptState(format!("failed to serialize seal properties: {e}"))+ })?,+ version: snapshot.version,+ created_at: snapshot.created_at,+ is_identified: snapshot.is_identified,+ last_seen_at: snapshot.last_seen_at,+ ..Default::default()+ }),+ ordinal: source.ordinal,+ });+ }++ 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_once: encode_json_map(&request.event_set_once)?,+ op_id: op.op_id.to_string(),+ })+ .await+ {+ Ok(response) => response,+ Err(status) => {+ return match SagaError::leader(status) {+ SagaError::LeaderRefused(status) => {+ self.abort_refused(pool, op, MergeStep::SourcesSealed, &status)+ .await+ }+ err => Err(err),+ };+ }+ };+ let folded = response.person.ok_or_else(|| {+ SagaError::CorruptState(format!(+ "fold response for merge op {} carries no document",+ op.op_id+ ))+ })?;+ let survivor = serde_json::json!({+ "id": folded.id,+ "uuid": folded.uuid,+ "properties": serde_json::from_slice::<Value>(&folded.properties)+ .unwrap_or_else(|_| Value::Object(serde_json::Map::new())),+ "created_at": folded.created_at,+ "is_identified": folded.is_identified,+ "version": folded.version,+ });++ let mut tx = pool.begin().await?;+ sqlx::query!(+ "UPDATE lifecycle_op_person SET sealed = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ survivor,+ ROLE_TARGET,+ )+ .execute(&mut *tx)+ .await?;+ if !advance_step_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::SourcesSealed.as_str(),+ MergeStep::DocumentFolded.as_str(),+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(+ MergeStep::SourcesSealed.as_str(),+ MergeStep::DocumentFolded.as_str(),+ );+ Ok(())+ }+}++struct TargetRow {+ person_id: i64,+}++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",+ op.op_id,+ ROLE_TARGET,+ )+ .fetch_one(pool)+ .await?;+ Ok(TargetRow {+ person_id: row.person_id,+ })+}++fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {+ if value.is_null() {+ return Ok(Vec::new());+ }+ serde_json::to_vec(value)+ .map_err(|e| SagaError::CorruptState(format!("failed to serialize event payload: {e}")))+}++/// `document_folded → flipped`: the destroying transaction, all Postgres.+/// Repoint every sealed source's distinct ids to the target (recording the+/// moves per source row in the same commit), move cohort membership and+/// hash-key overrides target-wins, scrub and tombstone the source person+/// rows at their exact death versions, and clear the target's mark. The+/// source marks stay: they are the fences' durable record until release.+async fn flip(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let team_id = op.team_id as i32;+ let mut tx = pool.begin().await?;++ let target = {+ let row = sqlx::query!(+ "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",+ op.op_id,+ ROLE_TARGET,+ )+ .fetch_one(&mut *tx)+ .await?;+ row.person_id+ };+ let mut sources: Vec<i64> = sqlx::query_scalar!(+ r#"+ SELECT person_id FROM lifecycle_op_person+ WHERE op_id = $1 AND role = $2 AND status = $3+ "#,+ op.op_id,+ ROLE_SOURCE,+ STATUS_SEALED,+ )+ .fetch_all(&mut *tx)+ .await?;+ sources.sort_unstable();++ let repointed = repoint_distinct_ids(&mut tx, team_id, &sources, target).await?;+ record_moved_mappings(&mut tx, op, &sources, &repointed).await?;+ move_cohort_membership(&mut tx, &sources, target).await?;+ move_hash_key_overrides(&mut tx, team_id, &sources, target).await?;+ tombstone_sealed_sources(&mut tx, op, team_id).await?;+ clear_target_mark(&mut tx, op).await?;++ if !advance_step_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::DocumentFolded.as_str(),+ MergeStep::Flipped.as_str(),+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(+ MergeStep::DocumentFolded.as_str(),+ MergeStep::Flipped.as_str(),+ );+ Ok(())+}++/// One distinct-id row repointed by [`repoint_distinct_ids`], keyed by its+/// pre-update owner.+struct RepointedDid {+ old_person_id: i64,+ distinct_id: String,+ version: i64,+}++/// Repoint every sealed source's live distinct ids to the target, bumping+/// each row's version.+async fn repoint_distinct_ids(+ tx: &mut Tx<'_>,+ team_id: i32,+ sources: &[i64],+ target: i64,+) -> Result<Vec<RepointedDid>, SagaError> {+ // RETURNING sees the post-update row, so the pre-update owner has to+ // come from a self-join snapshot — without it every returned+ // person_id would be the target.+ let rows = sqlx::query!(+ r#"+ UPDATE posthog_persondistinctid pdi+ SET person_id = $3, version = COALESCE(pdi.version, 0) + 1+ FROM posthog_persondistinctid old+ WHERE old.id = pdi.id+ AND pdi.team_id = $1 AND pdi.person_id = ANY($2) AND pdi.is_deleted = false+ RETURNING old.person_id as "old_person_id!", pdi.distinct_id, pdi.version as "version!"+ "#,+ team_id,+ sources,+ target,+ )+ .fetch_all(&mut **tx)+ .await?;+ Ok(rows+ .into_iter()+ .map(|r| RepointedDid {+ old_person_id: r.old_person_id,+ distinct_id: r.distinct_id,+ version: r.version,+ })+ .collect())+}++/// Record the repointed mappings per source in the same commit — what a+/// later ClickHouse emission (or an operator) reads back (delete parity).+async fn record_moved_mappings(+ tx: &mut Tx<'_>,+ op: &OpRow,+ sources: &[i64],+ repointed: &[RepointedDid],+) -> Result<(), SagaError> {+ let mut moved_ids: Vec<i64> = Vec::new();+ let mut moved_json: Vec<Value> = Vec::new();+ for source in sources {+ let rows: Vec<Value> = repointed+ .iter()+ .filter(|r| r.old_person_id == *source)+ .map(|r| serde_json::json!({"distinct_id": r.distinct_id, "version": r.version}))+ .collect();+ if !rows.is_empty() {+ moved_ids.push(*source);+ moved_json.push(Value::Array(rows));+ }+ }+ if moved_ids.is_empty() {+ return Ok(());+ }+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person lop+ SET moved = u.moved+ FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)+ WHERE lop.op_id = $1 AND lop.person_id = u.person_id+ "#,+ op.op_id,+ &moved_ids,+ &moved_json,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++/// Cohort membership moves wholesale. The table has no unique+/// constraint, so a target already in a cohort ends up with duplicate+/// rows — deliberately matching the production merge path, whose+/// recalculation heals the rare duplicate.+async fn move_cohort_membership(+ tx: &mut Tx<'_>,+ sources: &[i64],+ target: i64,+) -> Result<(), SagaError> {+ sqlx::query!(+ "UPDATE posthog_cohortpeople SET person_id = $2 WHERE person_id = ANY($1)",+ sources,+ target,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++/// Hash-key overrides move target-wins: the target's existing override+/// for a flag beats any source's.+async fn move_hash_key_overrides(+ tx: &mut Tx<'_>,+ team_id: i32,+ sources: &[i64],+ target: i64,+) -> Result<(), SagaError> {+ sqlx::query!(+ r#"+ WITH removed AS (+ DELETE FROM posthog_featureflaghashkeyoverride+ WHERE team_id = $1 AND person_id = ANY($2)+ RETURNING feature_flag_key, hash_key+ )+ INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)+ SELECT $1, $3, feature_flag_key, hash_key FROM removed+ ON CONFLICT (team_id, person_id, feature_flag_key) DO NOTHING+ "#,+ team_id,+ sources,+ target,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++/// 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.+async fn tombstone_sealed_sources(+ tx: &mut Tx<'_>,+ op: &OpRow,+ team_id: i32,+) -> Result<(), SagaError> {+ sqlx::query!(+ r#"+ UPDATE posthog_person p+ SET is_deleted = true,+ properties = '{}'::jsonb,+ properties_last_updated_at = '{}'::jsonb,+ properties_last_operation = '{}'::jsonb,+ version = (lop.sealed->>'version')::bigint + 1+ FROM lifecycle_op_person lop+ WHERE lop.op_id = $1 AND lop.role = $3 AND lop.status = $4+ AND p.team_id = $2 AND p.id = lop.person_id+ "#,+ op.op_id,+ team_id,+ ROLE_SOURCE,+ STATUS_SEALED,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++/// The target's own person row is untouched: the folded document+/// reaches Postgres through the writer's projection (single-writer+/// rule). Only its mark clears — from here the merged person is+/// claimable by other lifecycle ops.+async fn clear_target_mark(tx: &mut Tx<'_>, op: &OpRow) -> Result<(), SagaError> {+ sqlx::query!(+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",+ op.op_id,+ STATUS_CLEARED,+ ROLE_TARGET,+ )+ .execute(&mut **tx)+ .await?;+ Ok(())+}++impl MergeDriver {+ /// `flipped → completed`: release every source fence with outcome+ /// committed — the leader verifies the live mark and produces each+ /// death document — then settle the rows and record the outcome. The+ /// order is load-bearing: the mark flip to `deleted` must follow the+ /// release ack, because to the leader a `deleted` mark means "the+ /// death document already exists; absorb the retry". Flipping first+ /// would make the first-ever release absorb and never produce.+ async fn complete(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {+ let sources = sqlx::query!(+ r#"+ SELECT person_id, person_uuid, sealed as "sealed!" FROM lifecycle_op_person+ WHERE op_id = $1 AND role = $2 AND status = $3+ "#,+ op.op_id,+ ROLE_SOURCE,+ STATUS_SEALED,+ )+ .fetch_all(pool)+ .await?;++ let release_calls: Vec<_> = sources+ .iter()+ .map(|source| {+ let snapshot: Result<SealedSnapshot, _> =+ serde_json::from_value(source.sealed.clone());+ let leader = Arc::clone(&self.leader);+ let op_id = op.op_id.to_string();+ let team_id = op.team_id;+ let person_id = source.person_id;+ let person_uuid = source.person_uuid.to_string();+ async move {+ let snapshot = match snapshot {+ Ok(snapshot) => snapshot,+ Err(e) => {+ return (+ person_id,+ Err(SagaError::CorruptState(format!(+ "merge source {person_id} has a malformed seal: {e}"+ ))),+ )+ }+ };+ let result = leader+ .release_fence(ReleaseFenceRequest {+ team_id,+ person_id,+ person_uuid,+ op_id,+ outcome: ReleaseOutcome::Committed.into(),+ sealed_version: Some(snapshot.version),+ created_at: snapshot.created_at,+ })+ .await+ .map(|_| ())+ .map_err(SagaError::leader);+ (person_id, result)+ }+ })+ .collect();+ let release_results: Vec<_> = stream::iter(release_calls)+ .buffer_unordered(LEADER_CALL_CONCURRENCY)+ .collect()+ .await;+ for (_, result) in release_results {+ result?;+ }++ let mut tx = pool.begin().await?;+ sqlx::query!(+ r#"+ UPDATE lifecycle_op_person SET status = $2+ WHERE op_id = $1 AND role = $3 AND status = $4+ "#,+ op.op_id,+ STATUS_DELETED,+ ROLE_SOURCE,+ STATUS_SEALED,+ )+ .execute(&mut *tx)+ .await?;+ let outcome = build_outcome(&mut tx, op, false).await?;+ if !complete_op_in_tx(+ &mut tx,+ op.op_id,+ MergeStep::Flipped.as_str(),+ STEP_COMPLETED,+ &outcome,+ )+ .await?+ {+ tx.rollback().await?;+ return Ok(());+ }+ tx.commit().await?;+ record_transition(MergeStep::Flipped.as_str(), STEP_COMPLETED);+ record_outcomes(&outcome);+ Ok(())+ }+}++async fn claim_record(tx: &mut Tx<'_>, op: &OpRow) -> Result<ClaimRecord, SagaError> {+ let row = sqlx::query!(+ r#"SELECT moved FROM lifecycle_op_person WHERE op_id = $1 AND role = $2"#,+ op.op_id,+ ROLE_TARGET,+ )+ .fetch_one(&mut **tx)+ .await?;+ let moved = row.moved.ok_or_else(|| {+ SagaError::CorruptState(format!("merge op {} has no claim record", op.op_id))+ })?;+ serde_json::from_value(moved).map_err(|e| {+ SagaError::CorruptState(format!(+ "merge op {} claim record is malformed: {e}",+ op.op_id+ ))+ })+}++/// Build the terminal outcome from the persisted claim record and the+/// settled per-person rows. `pending_merge` decisions resolve through+/// 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> {+ 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",+ op.op_id,+ ROLE_SOURCE,+ )+ .fetch_all(&mut **tx)+ .await?+ .into_iter()+ .map(|r| (r.person_id, r.status))+ .collect();++ let survivor = if aborted {+ None+ } else {+ let row = sqlx::query!(+ r#"SELECT sealed FROM lifecycle_op_person WHERE op_id = $1 AND role = $2"#,+ op.op_id,+ ROLE_TARGET,+ )+ .fetch_one(&mut **tx)+ .await?;+ row.sealed+ };++ outcome_from_dispositions(&record.dispositions, aborted, survivor, &statuses)+}++fn outcome_from_dispositions(+ dispositions: &[Disposition],+ aborted: bool,+ survivor: Option<Value>,+ statuses: &HashMap<i64, String>,+) -> Result<Value, SagaError> {+ let results = dispositions+ .iter()+ .map(|d| {+ let outcome = if d.decision == DECISION_PENDING_MERGE {+ let status = d+ .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,+ }+ } else {+ d.decision.as_str()+ };+ MergeSourceRecord {+ distinct_id: d.distinct_id.clone(),+ outcome: outcome.to_string(),+ }+ })+ .collect();+ serde_json::to_value(MergeOutcome {+ aborted,+ survivor,+ results,+ })+ .map_err(|e| SagaError::CorruptState(format!("failed to serialize merge outcome: {e}")))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pending(distinct_id: &str, person_id: i64) -> Disposition {+ Disposition {+ distinct_id: distinct_id.to_string(),+ person_id: Some(person_id),+ decision: DECISION_PENDING_MERGE.to_string(),+ }+ }++ fn resolution(person_id: i64) -> Resolution {+ Resolution {+ person_id,+ person_uuid: Uuid::new_v4(),+ is_identified: false,+ }+ }++ #[test]+ fn a_remapped_did_settles_as_conflict_while_a_sibling_keeps_the_person() {+ let mut dispositions = vec![pending("d1", 7), pending("d2", 7)];+ let claim_persons = vec![(7, Uuid::new_v4(), 0)];+ // d2 was remapped to person 9 between the resolve and the recheck.+ let fresh = HashMap::from([+ ("d1".to_string(), resolution(7)),+ ("d2".to_string(), resolution(9)),+ ]);++ let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &[7], &fresh);++ assert!(dropped.is_empty(), "person 7 is still reachable via d1");+ assert_eq!(dispositions[0].decision, DECISION_PENDING_MERGE);+ assert_eq!(+ dispositions[1].decision, OUTCOME_SKIPPED_CONFLICT,+ "the remapped did must not later be reported as merged"+ );+ }++ #[test]+ fn a_person_with_no_reachable_did_left_is_dropped() {+ let mut dispositions = vec![pending("d1", 7), pending("d2", 7)];+ let claim_persons = vec![(7, Uuid::new_v4(), 0)];+ let fresh = HashMap::from([+ ("d1".to_string(), resolution(9)),+ ("d2".to_string(), resolution(9)),+ ]);++ let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &[7], &fresh);++ assert_eq!(dropped, vec![7]);+ for d in &dispositions {+ assert_eq!(d.decision, OUTCOME_SKIPPED_CONFLICT);+ }+ }+}diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rsindex 2c7341af9739..7ddf7bb80d42 100644--- a/rust/personhog-identity/src/lifecycle/mod.rs+++ b/rust/personhog-identity/src/lifecycle/mod.rs@@ -11,6 +11,7 @@pub mod delete;pub mod engine;+pub mod merge;pub mod validation;use std::sync::Arc;diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rsindex b33df02c7870..3f5899d3a32c 100644--- a/rust/personhog-identity/src/main.rs+++ b/rust/personhog-identity/src/main.rs@@ -22,6 +22,7 @@ use personhog_common::client::RouterClient;use personhog_identity::config::Config;use personhog_identity::lifecycle::delete::DeleteDriver;use personhog_identity::lifecycle::engine::Engine;+use personhog_identity::lifecycle::merge::MergeDriver;use personhog_identity::lifecycle::PersonHogLifecycleService;use personhog_identity::service::PersonHogIdentityService;use personhog_identity::storage::postgres::PostgresIdentityStorage;@@ -183,6 +184,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.lifecycle_engine_config(),));if let Some(sweeper_handle) = sweeper_handle {+ let sweeper_merge_driver = MergeDriver::new(property_writer.clone());let sweeper_engine = engine.clone();let sweep_interval = config.lifecycle_sweep_interval();let retention = config.lifecycle_op_retention();@@ -203,7 +205,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {_ = sweeper_handle.shutdown_recv() => break,_ = ticker.tick() => {}}- match sweeper_engine.sweep(&[&DeleteDriver]).await {+ match sweeper_engine+ .sweep(&[&DeleteDriver, &sweeper_merge_driver])+ .await+ {Ok(resumed) if resumed > 0 => {tracing::info!(resumed, "Lifecycle sweeper resumed abandoned ops")}diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex 28ee7f7a7099..04b2db6b70f7 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -2,6 +2,8 @@// and none of them uses every helper.#![allow(dead_code)]+pub mod sim_leader;+use std::sync::Arc;use rand::Rng;@@ -65,13 +67,17 @@ impl TestContext {person_id}- /// An engine over this context's pool, tuned for tests: short lease and- /// poll so lease-contention tests run in milliseconds.+ /// An engine over this context's pool, tuned for tests: a short poll+ /// so contention tests run in milliseconds, and a lease long enough+ /// that a live test's op never looks expired to the suite's single+ /// sweep test (in lifecycle_merge_tests), which would otherwise claim+ /// and drive it with the wrong harness. Lease-expiry tests seed+ /// explicit lease_expires_at values instead of waiting this out.pub fn engine(&self) -> personhog_identity::lifecycle::engine::Engine {personhog_identity::lifecycle::engine::Engine::new(self.pool.clone(),personhog_identity::lifecycle::engine::EngineConfig {- lease: std::time::Duration::from_secs(5),+ lease: std::time::Duration::from_secs(300),execute_timeout: std::time::Duration::from_secs(10),poll_interval: std::time::Duration::from_millis(25),attempt_alert_threshold: 5,diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rsnew file mode 100644index 000000000000..fa8b748dd4bf--- /dev/null+++ b/rust/personhog-identity/tests/common/sim_leader.rs@@ -0,0 +1,517 @@+//! A stateful simulated leader for lifecycle saga tests. Unlike a+//! record-only fake, it enforces the real leader's admission rules so a+//! saga that violates the protocol fails the test instead of merely+//! logging a suspicious call sequence:+//!+//! - It owns a fence map: a fence installed by one op rejects every other+//! actor with the leader's typed rejection (FAILED_PRECONDITION plus+//! `x-person-fenced` metadata — mirrors `fenced_status` in+//! personhog-leader/src/fence.rs, which is not imported to keep that+//! heavy crate out of this one's dev-dependencies).+//! - A committed release verifies the op's live mark row before producing+//! a death document, and absorbs duplicates once one exists — the real+//! leader's fail-closed rule, enforced here rather than just recorded.+//! - Failures are scripted per RPC and per person, so a test can fail one+//! source's fence or release while its sibling succeeds.+//! - [`SimLeader::admit_write`] is the probe for "would the leader accept+//! an ordinary write right now": tests call it mid-saga to assert that+//! in-between states are never exposed to other actors.+//!+//! Its "cache" is the live Postgres row — what the real leader holds in a+//! quiet system — plus the death documents it has produced, which answer+//! as authoritative not-found exactly like the real cache's tombstones.++use std::collections::{HashMap, VecDeque};+use std::sync::Mutex;++use async_trait::async_trait;+use chrono::Utc;+use sqlx::postgres::PgPool;+use tonic::Status;+use uuid::Uuid;++use personhog_common::grpc::semantic_refusal;+use personhog_identity::leader::LifecycleLeader;+use personhog_proto::personhog::types::v1::{+ FencePersonRequest, FencePersonResponse, FoldPersonDocumentRequest, FoldPersonDocumentResponse,+ LifecycleOpType, Person, ReleaseFenceRequest, ReleaseFenceResponse, ReleaseOutcome,+};++/// Which RPC a scripted failure applies to.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Rpc {+ Fence,+ Fold,+ Release,+}++/// A person's live fence in the simulated leader.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Fence {+ pub op_id: Uuid,+ pub op_type: LifecycleOpType,+}++/// A death document produced by a committed release.+#[derive(Debug, Clone, PartialEq)]+pub struct DeathDocument {+ pub person_id: i64,+ pub person_uuid: String,+ pub version: i64,+ pub created_at: i64,+}++#[derive(Debug, Clone, PartialEq)]+pub enum LeaderCall {+ Fence {+ person_id: i64,+ op_type: LifecycleOpType,+ },+ Fold {+ target_person_id: i64,+ snapshot_versions: Vec<i64>,+ /// The folded document's max-merged `last_seen_at`.+ folded_last_seen_at: Option<i64>,+ },+ ReleaseCommitted {+ person_id: i64,+ sealed_version: i64,+ /// The source's `lifecycle_op_person.status` observed at release+ /// time. The sim also *enforces* mark liveness (see the module+ /// docs); the recorded value lets tests assert the exact status.+ mark_status_at_release: Option<String>,+ },+ ReleaseAborted {+ person_id: i64,+ },+}++/// Metadata keys carried on fenced-write rejections; must stay in sync+/// with personhog-leader/src/fence.rs.+pub const FENCED_METADATA_KEY: &str = "x-person-fenced";+pub const FENCED_OP_ID_METADATA_KEY: &str = "x-person-fenced-op-id";++fn fenced_status(fence: &Fence) -> Status {+ let what = match fence.op_type {+ LifecycleOpType::Delete => "PERSON_DELETING",+ LifecycleOpType::Merge => "PERSON_MERGING",+ LifecycleOpType::Unspecified => "PERSON_FENCED",+ };+ let mut status = Status::failed_precondition(format!(+ "{what}: person is fenced by lifecycle op {}",+ fence.op_id+ ));+ if let Ok(value) = fence.op_type.as_op_type_str().parse() {+ status.metadata_mut().insert(FENCED_METADATA_KEY, value);+ }+ if let Ok(value) = fence.op_id.to_string().parse() {+ status+ .metadata_mut()+ .insert(FENCED_OP_ID_METADATA_KEY, value);+ }+ status+}++pub struct SimLeader {+ pool: PgPool,+ calls: Mutex<Vec<LeaderCall>>,+ fences: Mutex<HashMap<i64, Fence>>,+ deaths: Mutex<HashMap<i64, DeathDocument>>,+ scripted: Mutex<HashMap<(Rpc, i64), VecDeque<Status>>>,+ /// Sealed `is_identified` overrides per person: the leader's state can+ /// be ahead of Postgres, which is exactly what the seal-time re-check+ /// exists for.+ sealed_identified: Mutex<HashMap<i64, bool>>,+ /// Injected `last_seen_at` per person: leader-side state with no+ /// Postgres column.+ last_seen: Mutex<HashMap<i64, i64>>,+}++impl SimLeader {+ pub fn new(pool: PgPool) -> Self {+ Self {+ pool,+ calls: Mutex::new(Vec::new()),+ fences: Mutex::new(HashMap::new()),+ deaths: Mutex::new(HashMap::new()),+ scripted: Mutex::new(HashMap::new()),+ sealed_identified: Mutex::new(HashMap::new()),+ last_seen: Mutex::new(HashMap::new()),+ }+ }++ pub fn calls(&self) -> Vec<LeaderCall> {+ self.calls.lock().unwrap().clone()+ }++ /// Script the next matching call for `person_id` (the fold matches on+ /// the target's id) to fail with `status`. Queued failures pop in+ /// order, one per call.+ pub fn fail_next(&self, rpc: Rpc, person_id: i64, status: Status) {+ self.scripted+ .lock()+ .unwrap()+ .entry((rpc, person_id))+ .or_default()+ .push_back(status);+ }++ pub fn set_sealed_identified(&self, person_id: i64, identified: bool) {+ self.sealed_identified+ .lock()+ .unwrap()+ .insert(person_id, identified);+ }++ pub fn set_last_seen(&self, person_id: i64, epoch: i64) {+ self.last_seen.lock().unwrap().insert(person_id, epoch);+ }++ pub fn fence_for(&self, person_id: i64) -> Option<Fence> {+ self.fences.lock().unwrap().get(&person_id).copied()+ }++ /// Death documents produced so far, ordered by person id.+ pub fn death_documents(&self) -> Vec<DeathDocument> {+ let mut deaths: Vec<DeathDocument> =+ self.deaths.lock().unwrap().values().cloned().collect();+ deaths.sort_by_key(|d| d.person_id);+ deaths+ }++ /// The leader's write-admission decision for an ordinary (non-lifecycle)+ /// write right now: fenced persons reject, destroyed persons are+ /// not found. Tests probe this mid-saga to assert intermediate states+ /// are shielded from other actors.+ pub async fn admit_write(&self, team_id: i64, person_id: i64) -> Result<(), Status> {+ if let Some(fence) = self.fence_for(person_id) {+ return Err(fenced_status(&fence));+ }+ if self.deaths.lock().unwrap().contains_key(&person_id) {+ return Err(Status::not_found("person is destroyed"));+ }+ match self.live_person(team_id, person_id).await {+ Some(_) => Ok(()),+ None => Err(Status::not_found("person is destroyed")),+ }+ }++ fn take_scripted(&self, rpc: Rpc, person_id: i64) -> Option<Status> {+ self.scripted+ .lock()+ .unwrap()+ .get_mut(&(rpc, person_id))+ .and_then(|queue| queue.pop_front())+ }++ async fn live_person(&self, team_id: i64, person_id: i64) -> Option<Person> {+ let row: Option<(Uuid, i64, chrono::DateTime<Utc>, bool, serde_json::Value)> =+ sqlx::query_as(+ r#"+ SELECT uuid, COALESCE(version, 0), created_at, is_identified, properties+ FROM posthog_person+ WHERE team_id = $1 AND id = $2 AND is_deleted = false+ "#,+ )+ .bind(team_id as i32)+ .bind(person_id)+ .fetch_optional(&self.pool)+ .await+ .expect("person lookup");+ row.map(+ |(uuid, version, created_at, is_identified, properties)| Person {+ id: person_id,+ uuid: uuid.to_string(),+ team_id,+ properties: serde_json::to_vec(&properties).unwrap(),+ created_at: created_at.timestamp(),+ version,+ is_identified,+ last_seen_at: self.last_seen.lock().unwrap().get(&person_id).copied(),+ ..Default::default()+ },+ )+ }++ /// The mark row the real leader consults before producing a death+ /// document (personhog-leader/src/fence.rs `mark_status`).+ async fn mark_status(&self, op_id: Uuid, team_id: i64, person_id: i64) -> Option<String> {+ sqlx::query_scalar(+ "SELECT status FROM lifecycle_op_person \+ WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role <> 'target'",+ )+ .bind(op_id)+ .bind(team_id as i32)+ .bind(person_id)+ .fetch_optional(&self.pool)+ .await+ .expect("mark lookup")+ }++ /// The target-mark row the real leader consults before folding.+ async fn target_mark_status(+ &self,+ op_id: Uuid,+ team_id: i64,+ person_id: i64,+ ) -> Option<String> {+ sqlx::query_scalar(+ "SELECT status FROM lifecycle_op_person \+ WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role = 'target'",+ )+ .bind(op_id)+ .bind(team_id as i32)+ .bind(person_id)+ .fetch_optional(&self.pool)+ .await+ .expect("target mark lookup")+ }++ fn record(&self, call: LeaderCall) {+ self.calls.lock().unwrap().push(call);+ }+}++#[async_trait]+impl LifecycleLeader for SimLeader {+ async fn fence_person(+ &self,+ request: FencePersonRequest,+ ) -> Result<FencePersonResponse, Status> {+ if let Some(status) = self.take_scripted(Rpc::Fence, request.person_id) {+ return Err(status);+ }+ let op_id = Uuid::parse_str(&request.op_id)+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;+ if let Some(existing) = self.fence_for(request.person_id) {+ if existing.op_id != op_id {+ return Err(fenced_status(&existing));+ }+ }+ if self.deaths.lock().unwrap().contains_key(&request.person_id) {+ return Err(Status::not_found("person is destroyed"));+ }+ let Some(mut person) = self.live_person(request.team_id, request.person_id).await else {+ return Err(Status::not_found("person is destroyed"));+ };+ if let Some(identified) = self+ .sealed_identified+ .lock()+ .unwrap()+ .get(&request.person_id)+ {+ person.is_identified = *identified;+ }+ self.fences.lock().unwrap().insert(+ request.person_id,+ Fence {+ op_id,+ op_type: request.op_type(),+ },+ );+ self.record(LeaderCall::Fence {+ person_id: request.person_id,+ op_type: request.op_type(),+ });+ Ok(FencePersonResponse {+ sealed: Some(person),+ })+ }++ async fn release_fence(+ &self,+ request: ReleaseFenceRequest,+ ) -> Result<ReleaseFenceResponse, Status> {+ if let Some(status) = self.take_scripted(Rpc::Release, request.person_id) {+ return Err(status);+ }+ let op_id = Uuid::parse_str(&request.op_id)+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;+ if let Some(existing) = self.fence_for(request.person_id) {+ if existing.op_id != op_id {+ return Err(fenced_status(&existing));+ }+ }+ match request.outcome() {+ ReleaseOutcome::Aborted => {+ self.fences.lock().unwrap().remove(&request.person_id);+ self.record(LeaderCall::ReleaseAborted {+ person_id: request.person_id,+ });+ Ok(ReleaseFenceResponse {})+ }+ ReleaseOutcome::Committed => {+ let Some(sealed_version) = request.sealed_version else {+ return Err(Status::invalid_argument(+ "sealed_version is required for a committed release",+ ));+ };+ if request.created_at <= 0 {+ return Err(Status::invalid_argument(+ "created_at is required for a committed release",+ ));+ }+ if Uuid::parse_str(&request.person_uuid).is_err() {+ return Err(Status::invalid_argument(+ "person_uuid must be a valid UUID for a committed release",+ ));+ }+ let mark_status = self+ .mark_status(op_id, request.team_id, request.person_id)+ .await;+ self.record(LeaderCall::ReleaseCommitted {+ person_id: request.person_id,+ sealed_version,+ mark_status_at_release: mark_status.clone(),+ });++ // A death document already exists: absorb the retry, like+ // the real leader's is_deleted cache entry does.+ if self.deaths.lock().unwrap().contains_key(&request.person_id) {+ self.fences.lock().unwrap().remove(&request.person_id);+ return Ok(ReleaseFenceResponse {});+ }++ match mark_status.as_deref() {+ Some("marked") | Some("sealed") => {}+ Some("deleted") => {+ self.fences.lock().unwrap().remove(&request.person_id);+ return Ok(ReleaseFenceResponse {});+ }+ _ => {+ return Err(semantic_refusal(+ "op holds no live mark for this person; \+ refusing to produce a death document",+ "release-unverified",+ ));+ }+ }++ let current = self.live_person(request.team_id, request.person_id).await;+ if let Some(person) = ¤t {+ if person.uuid != request.person_uuid {+ return Err(semantic_refusal(+ "person_uuid does not match the person being released",+ "uuid-mismatch",+ ));+ }+ }+ let base_version = current+ .as_ref()+ .map(|p| p.version)+ .unwrap_or(0)+ .max(sealed_version);+ self.deaths.lock().unwrap().insert(+ request.person_id,+ DeathDocument {+ person_id: request.person_id,+ person_uuid: request.person_uuid.clone(),+ version: base_version + 1,+ created_at: request.created_at,+ },+ );+ self.fences.lock().unwrap().remove(&request.person_id);+ Ok(ReleaseFenceResponse {})+ }+ ReleaseOutcome::Unspecified => {+ Err(Status::invalid_argument("outcome must be specified"))+ }+ }+ }++ async fn fold_person_document(+ &self,+ request: FoldPersonDocumentRequest,+ ) -> Result<FoldPersonDocumentResponse, Status> {+ if let Some(status) = self.take_scripted(Rpc::Fold, request.person_id) {+ return Err(status);+ }+ let op_id = Uuid::parse_str(&request.op_id)+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;+ if let Some(existing) = self.fence_for(request.person_id) {+ if existing.op_id != op_id {+ return Err(fenced_status(&existing));+ }+ }+ if self.deaths.lock().unwrap().contains_key(&request.person_id) {+ return Err(Status::not_found("person is destroyed"));+ }+ let Some(target) = self.live_person(request.team_id, request.person_id).await else {+ return Err(Status::not_found("person is destroyed"));+ };+ // The real leader refuses a fold unless the op holds a live+ // target mark.+ match self+ .target_mark_status(op_id, request.team_id, request.person_id)+ .await+ .as_deref()+ {+ Some("marked") => {}+ _ => {+ return Err(semantic_refusal(+ "op holds no live target mark for this person; refusing to fold",+ "fold-unverified",+ ));+ }+ }+ // The real fold: the target wins every key it has, snapshots fill+ // still-absent keys in ordinal order (the leader sorts, not the+ // caller), then the merge event's $set overrides and $set_once+ // fills; `last_seen_at` max-merges across the target and every+ // snapshot.+ let mut folded: serde_json::Map<String, serde_json::Value> =+ serde_json::from_slice(&target.properties).unwrap();+ let mut created_at = target.created_at;+ let mut max_sealed = 0;+ let mut snapshot_versions = Vec::new();+ let mut last_seen_at = target.last_seen_at;+ let mut ordered = request.sealed_snapshots.clone();+ ordered.sort_by_key(|snapshot| snapshot.ordinal);+ for snapshot in &ordered {+ let person = snapshot+ .person+ .as_ref()+ .ok_or_else(|| Status::invalid_argument("sealed snapshot is missing its person"))?;+ let properties: serde_json::Map<String, serde_json::Value> =+ serde_json::from_slice(&person.properties).unwrap();+ for (key, value) in properties {+ folded.entry(key).or_insert(value);+ }+ if person.created_at > 0 {+ created_at = created_at.min(person.created_at);+ }+ max_sealed = max_sealed.max(person.version);+ snapshot_versions.push(person.version);+ last_seen_at = last_seen_at.max(person.last_seen_at);+ }+ if !request.event_set.is_empty() {+ let event_set: serde_json::Map<String, serde_json::Value> =+ serde_json::from_slice(&request.event_set).unwrap();+ for (key, value) in event_set {+ folded.insert(key, value);+ }+ }+ if !request.event_set_once.is_empty() {+ let event_set_once: serde_json::Map<String, serde_json::Value> =+ serde_json::from_slice(&request.event_set_once).unwrap();+ for (key, value) in event_set_once {+ folded.entry(key).or_insert(value);+ }+ }+ self.record(LeaderCall::Fold {+ target_person_id: request.person_id,+ snapshot_versions,+ folded_last_seen_at: last_seen_at,+ });+ Ok(FoldPersonDocumentResponse {+ person: Some(Person {+ properties: serde_json::to_vec(&folded).unwrap(),+ created_at,+ version: target.version.max(max_sealed) + 1,+ is_identified: true,+ last_seen_at,+ ..target+ }),+ })+ }+}diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rsindex e100fedf6f9a..e6d44f1d42ce 100644--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs@@ -331,6 +331,77 @@ async fn a_person_marked_by_another_live_op_is_skipped() {ctx.cleanup().await.expect("cleanup");}+/// A mark can land on a corpse when a merge destroys the person between+/// the mark step's liveness filter and its insert. The seeded state is+/// what that window produces: a marked row whose person is already+/// tombstoned. The recheck must settle it as not_found without touching+/// the corpse again.+#[tokio::test]+async fn a_victim_destroyed_between_liveness_check_and_mark_settles_as_not_found() {+ let ctx = TestContext::new().await;+ let service = ctx.lifecycle_service();++ let live = ctx.insert_person_with_distinct_id("recheck-live").await;+ let corpse = ctx.insert_person_with_distinct_id("recheck-corpse").await;+ sqlx::query(+ "UPDATE posthog_person SET is_deleted = true, version = 5 WHERE team_id = $1 AND id = $2",+ )+ .bind(ctx.team_id as i32)+ .bind(corpse)+ .execute(&ctx.pool)+ .await+ .expect("tombstone the corpse");++ let op_id = Uuid::now_v7();+ sqlx::query(+ r#"+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at)+ VALUES ($1, 'delete', $2, 'started', $3, now() - interval '1 minute')+ "#,+ )+ .bind(op_id)+ .bind(ctx.team_id as i32)+ .bind(serde_json::json!({"person_ids": [corpse, live]}))+ .execute(&ctx.pool)+ .await+ .expect("insert 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(), 'victim', 'marked')",+ )+ .bind(op_id)+ .bind(ctx.team_id as i32)+ .bind(corpse)+ .execute(&ctx.pool)+ .await+ .expect("insert the corpse's mark");++ let response = service+ .delete_persons(Request::new(delete_request(+ ctx.team_id,+ vec![corpse, live],+ op_id,+ )))+ .await+ .expect("delete succeeds")+ .into_inner();++ assert_eq!(+ outcomes(&response),+ vec![+ (corpse, DeletePersonOutcome::NotFound),+ (live, DeletePersonOutcome::Deleted),+ ]+ );+ let (is_deleted, version, _) = ctx.person_state(corpse).await;+ assert!(is_deleted);+ assert_eq!(version, 5, "the corpse was never re-tombstoned");+ let (is_deleted, _, _) = ctx.person_state(live).await;+ assert!(is_deleted, "the live victim's delete proceeded normally");++ ctx.cleanup().await.expect("cleanup");+}+#[tokio::test]async fn a_retry_with_the_same_op_id_returns_the_recorded_outcome() {let ctx = TestContext::new().await;diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rsindex 58aaf23f51a5..b06a012065f5 100644--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs@@ -1,9 +1,15 @@//! Engine tests against a dummy op type: the engine must be generic over op-//! types, so these drive a two-step fake op (registered under 'merge', the-//! other op_type the schema's CHECK constraint allows — the real merge-//! driver does not exist yet) and assert the create-or-attach, lease, CAS-//! advance, recorded-outcome, and sweeper behaviors that every op type-//! shares.+//! types, so these drive a two-step fake op and assert the+//! create-or-attach, lease, CAS advance, recorded-outcome, and sweeper+//! behaviors that every op type shares.+//!+//! Isolation against the other test binaries sharing this database: the+//! dummy registers under 'merge' (the CHECK constraint allows nothing+//! else), which is safe because this file never sweeps. The suite's+//! single sweep test lives in lifecycle_merge_tests (where the sweeper+//! drives a real merge), and its one-hour-lease scan window cannot reach+//! this file's rows: every op this file inserts directly is live-leased,+//! fresh with a NULL lease, parked, or completed.mod common;@@ -15,6 +21,7 @@ use serde_json::json;use sqlx::postgres::PgPool;use uuid::Uuid;+use personhog_common::grpc::semantic_refusal;use personhog_identity::lifecycle::engine::{advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, STEP_COMPLETED,};@@ -71,6 +78,16 @@ impl OpDriver for DummyDriver {}}+async fn parked_state(pool: &PgPool, op_id: Uuid) -> (bool, Option<String>) {+ let row: (Option<chrono::DateTime<chrono::Utc>>, Option<String>) =+ sqlx::query_as("SELECT parked_at, parked_reason FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(pool)+ .await+ .expect("op row exists");+ (row.0.is_some(), row.1)+}+async fn op_row(ctx: &TestContext, op_id: Uuid) -> (String, i32, Option<serde_json::Value>, bool) {let row: (String,@@ -175,11 +192,13 @@ async fn resume_picks_up_an_op_from_its_saved_step() {let driver = DummyDriver::new();let op_id = Uuid::now_v7();- // An op abandoned mid-flight: past its first step, lease lapsed.+ // An op abandoned mid-flight: past its first step, lease released by+ // the crashed driver's error path (NULL, not expired — an expired+ // lease would make this row claimable by the sweep test's engine).sqlx::query(r#"- INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at)- VALUES ($1, 'merge', $2, 'half', '{}'::jsonb, now() - interval '1 minute')+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)+ VALUES ($1, 'merge', $2, 'half', '{}'::jsonb)"#,).bind(op_id)@@ -204,29 +223,16 @@ async fn resume_picks_up_an_op_from_its_saved_step() {}#[tokio::test]-async fn the_sweeper_resumes_abandoned_ops_and_gc_reaps_completed_ones() {+async fn gc_reaps_completed_ops_past_retention() {let ctx = TestContext::new().await;let engine = ctx.engine();let driver = DummyDriver::new();let op_id = Uuid::now_v7();- sqlx::query(- r#"- INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at)- VALUES ($1, 'merge', $2, 'started', '{}'::jsonb, now() - interval '1 minute')- "#,- )- .bind(op_id)- .bind(ctx.team_id as i32)- .execute(&ctx.pool)- .await- .expect("insert abandoned op");-- let resumed = engine.sweep(&[&driver]).await.expect("sweep runs");- assert!(resumed >= 1, "the abandoned op was resumed");- let (step, _, _, completed) = op_row(&ctx, op_id).await;- assert_eq!(step, STEP_COMPLETED);- assert!(completed);+ engine+ .execute(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect("op completes");// Backdate the completion past retention; GC reaps it (and cascades the// per-person rows) without touching other tests' fresh rows.@@ -442,3 +448,213 @@ async fn a_failing_driver_whose_lease_was_stolen_does_not_release_the_stealers_lctx.cleanup().await.expect("cleanup");}++/// Refuses its first `refusals` steps with a definitive leader refusal+/// (a semantic refusal, as classified by `SagaError::leader`), then+/// completes in one step.+struct RefusingDriver {+ refusals_left: AtomicUsize,+ steps_run: AtomicUsize,+}++impl RefusingDriver {+ fn new(refusals: usize) -> Self {+ Self {+ refusals_left: AtomicUsize::new(refusals),+ steps_run: AtomicUsize::new(0),+ }+ }+}++#[async_trait]+impl OpDriver for RefusingDriver {+ 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> {+ self.steps_run.fetch_add(1, Ordering::SeqCst);+ if self+ .refusals_left+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))+ .is_ok()+ {+ return Err(SagaError::leader(semantic_refusal(+ "injected refusal",+ "test-refusal",+ )));+ }+ let mut tx = pool.begin().await.map_err(SagaError::Db)?;+ let advanced =+ complete_op_in_tx(&mut tx, op.op_id, "started", STEP_COMPLETED, &json!({})).await?;+ if !advanced {+ tx.rollback().await.map_err(SagaError::Db)?;+ return Ok(());+ }+ tx.commit().await.map_err(SagaError::Db)?;+ Ok(())+ }+}++#[tokio::test]+async fn a_definitive_leader_refusal_parks_the_op() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let driver = RefusingDriver::new(1);+ let op_id = Uuid::now_v7();++ let err = engine+ .execute(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect_err("the refusal surfaces");+ assert!(matches!(err, SagaError::LeaderRefused(_)));++ let (parked, reason) = parked_state(&ctx.pool, op_id).await;+ assert!(parked, "a refused op is parked, not left for the sweeper");+ assert_eq!(reason.as_deref(), Some("test-refusal"));+ assert!(+ !lease_is_live(&ctx.pool, op_id).await,+ "parking drops the lease so an explicit retry need not wait it out"+ );+ let (step, _, _, completed) = op_row(&ctx, op_id).await;+ assert_eq!(step, "started", "the refused step made no progress");+ assert!(!completed);++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_explicit_retry_with_the_same_op_id_unparks_and_redrives() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let driver = RefusingDriver::new(1);+ let op_id = Uuid::now_v7();++ engine+ .execute(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect_err("first attempt is refused and parks");++ // The driver no longer refuses: an explicit retry with the same+ // op_id claims, un-parks, and completes.+ let row = engine+ .execute(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect("explicit retry completes the parked op");+ assert_eq!(row.step, STEP_COMPLETED);++ let (parked, reason) = parked_state(&ctx.pool, op_id).await;+ assert!(!parked, "claiming un-parks");+ assert_eq!(reason, None);+ assert_eq!(driver.steps_run.load(Ordering::SeqCst), 2);++ ctx.cleanup().await.expect("cleanup");+}++/// Steals the lease mid-step, then returns a definitive refusal: the+/// displaced driver's park must lose the `attempt` compare-and-swap.+struct StolenLeaseRefusingDriver;++#[async_trait]+impl OpDriver for StolenLeaseRefusingDriver {+ 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> {+ steal_lease(pool, op.op_id).await;+ Err(SagaError::leader(semantic_refusal(+ "injected refusal",+ "test-refusal",+ )))+ }+}++#[tokio::test]+async fn a_displaced_drivers_refusal_does_not_park_the_stealers_op() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let op_id = Uuid::now_v7();++ let err = engine+ .execute(&StolenLeaseRefusingDriver, op_id, ctx.team_id, &json!({}))+ .await+ .expect_err("the displaced driver cannot answer for the op");+ // Not the refusal: the stealer may re-drive the step against fresh+ // state and complete the op, so a displaced driver's refusal is+ // stale; the caller gets the retriable answer.+ assert!(matches!(err, SagaError::Busy));++ let (parked, _) = parked_state(&ctx.pool, op_id).await;+ assert!(+ !parked,+ "a displaced driver must not park an op another driver is actively driving"+ );+ assert!(+ lease_is_live(&ctx.pool, op_id).await,+ "the stealer's lease survives the displaced driver's park attempt"+ );++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn step_once_rejects_a_foreign_teams_op() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let driver = DummyDriver::new();+ let op_id = Uuid::now_v7();++ engine+ .create_or_attach(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect("create op");++ let err = engine+ .step_once(&driver, op_id, ctx.team_id + 1)+ .await+ .expect_err("a mismatched team cannot drive the op");+ assert!(matches!(err, SagaError::RequestMismatch(_)));+ assert_eq!(driver.steps_run.load(Ordering::SeqCst), 0);++ ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn resume_does_not_unpark() {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let driver = RefusingDriver::new(1);+ let op_id = Uuid::now_v7();++ engine+ .execute(&driver, op_id, ctx.team_id, &json!({}))+ .await+ .expect_err("first attempt is refused and parks");++ // The sweeper's entry point must not claim and un-park a parked op,+ // even reaching it directly as a scan-then-park race would; that+ // signal is reserved for an explicit retry.+ let err = engine+ .resume(&driver, op_id)+ .await+ .expect_err("resume cannot claim a parked op");+ assert!(matches!(err, SagaError::Busy));+ let (parked, _) = parked_state(&ctx.pool, op_id).await;+ assert!(parked, "the op stays parked");+ assert_eq!(+ driver.steps_run.load(Ordering::SeqCst),+ 1,+ "resume ran no step"+ );++ ctx.cleanup().await.expect("cleanup");+}diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rsnew file mode 100644index 000000000000..782ef15f4d92--- /dev/null+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs@@ -0,0 +1,1338 @@+//! End-to-end tests of the merge saga driver: the engine drives a+//! [`MergeDriver`] against real Postgres, with the leader surface+//! simulated behind [`LifecycleLeader`] by [`SimLeader`] (see+//! `common/sim_leader.rs`), which enforces the leader's admission rules —+//! fenced writes reject, a committed release needs a live mark, duplicate+//! releases absorb — so protocol violations fail tests instead of merely+//! being recorded. The walkthrough tests step the saga one transition at+//! a time via `Engine::step_once` and assert, at every state, what other+//! actors in the system can and cannot see.++mod common;++use std::collections::{HashMap, HashSet};+use std::sync::Arc;++use chrono::Utc;+use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};+use common::TestContext;+use personhog_common::grpc::semantic_refusal;+use serde_json::json;+use sqlx::postgres::PgPool;+use tonic::{Code, Status};+use uuid::Uuid;++use personhog_identity::lifecycle::engine::{+ Engine, OpRow, SagaError, STEP_ABORTED, STEP_COMPLETED,+};+use personhog_identity::lifecycle::merge::{+ MergeDriver, MergeOutcome, MergeRequest, MergeSourceEntry, OUTCOME_MERGED,+ OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,+ OUTCOME_SKIPPED_MOVE_LIMIT,+};+use personhog_proto::personhog::types::v1::LifecycleOpType;++struct MergeHarness {+ ctx: TestContext,+ engine: Engine,+ leader: Arc<SimLeader>,+ driver: MergeDriver,+}++impl MergeHarness {+ async fn new() -> Self {+ let ctx = TestContext::new().await;+ let engine = ctx.engine();+ let leader = Arc::new(SimLeader::new(ctx.pool.clone()));+ let driver = MergeDriver::new(leader.clone());+ Self {+ ctx,+ engine,+ leader,+ driver,+ }+ }++ async fn execute(+ &self,+ op_id: Uuid,+ request: &MergeRequest,+ ) -> Result<MergeOutcome, SagaError> {+ let frozen = serde_json::to_value(request).unwrap();+ let row = self+ .engine+ .execute(&self.driver, op_id, self.ctx.team_id, &frozen)+ .await?;+ Ok(serde_json::from_value(row.outcome.expect("terminal outcome")).unwrap())+ }++ /// Create (or attach to) the op without driving it — the walkthrough+ /// entry point, paired with [`step`].+ async fn create(&self, op_id: Uuid, request: &MergeRequest) -> OpRow {+ let frozen = serde_json::to_value(request).unwrap();+ self.engine+ .create_or_attach(&self.driver, op_id, self.ctx.team_id, &frozen)+ .await+ .expect("create or attach op")+ }++ /// Run exactly one saga step and return the reloaded row.+ async fn step(&self, op_id: Uuid) -> Result<OpRow, SagaError> {+ self.engine+ .step_once(&self.driver, op_id, self.ctx.team_id)+ .await+ }++ /// Adds another distinct id mapping to an existing person.+ async fn add_distinct_id(&self, person_id: i64, distinct_id: &str) {+ sqlx::query(+ r#"+ INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version)+ VALUES ($1, $2, $3, 0)+ "#,+ )+ .bind(self.ctx.team_id as i32)+ .bind(person_id)+ .bind(distinct_id)+ .execute(&self.ctx.pool)+ .await+ .expect("insert distinct id");+ }++ async fn set_person(&self, person_id: i64, properties: &str, version: i64, identified: bool) {+ sqlx::query(+ r#"+ UPDATE posthog_person+ SET properties = $3::jsonb, version = $4, is_identified = $5+ WHERE team_id = $1 AND id = $2+ "#,+ )+ .bind(self.ctx.team_id as i32)+ .bind(person_id)+ .bind(properties)+ .bind(version)+ .bind(identified)+ .execute(&self.ctx.pool)+ .await+ .expect("set person state");+ }++ /// A mark row held by a different (still-live) op.+ async fn foreign_mark(&self, person_id: i64) -> Uuid {+ let foreign_op = Uuid::now_v7();+ sqlx::query(+ r#"+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)+ VALUES ($1, 'delete', $2, 'marked', '{}'::jsonb)+ "#,+ )+ .bind(foreign_op)+ .bind(self.ctx.team_id as i32)+ .execute(&self.ctx.pool)+ .await+ .expect("insert foreign op");+ sqlx::query(+ r#"+ INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)+ VALUES ($1, $2, $3, $4, 'victim', 'marked')+ "#,+ )+ .bind(foreign_op)+ .bind(self.ctx.team_id as i32)+ .bind(person_id)+ .bind(Uuid::new_v4())+ .execute(&self.ctx.pool)+ .await+ .expect("insert foreign mark");+ foreign_op+ }++ /// (is_deleted, version, properties) of a person row.+ async fn person_state(&self, person_id: i64) -> (bool, i64, serde_json::Value) {+ sqlx::query_as(+ r#"+ SELECT is_deleted, COALESCE(version, 0), properties+ FROM posthog_person WHERE team_id = $1 AND id = $2+ "#,+ )+ .bind(self.ctx.team_id as i32)+ .bind(person_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("person row exists")+ }++ /// (person_id, is_deleted, version) of a distinct id row.+ async fn pdi_state(&self, distinct_id: &str) -> (i64, bool, i64) {+ sqlx::query_as(+ r#"+ SELECT person_id, is_deleted, COALESCE(version, 0)+ FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2+ "#,+ )+ .bind(self.ctx.team_id as i32)+ .bind(distinct_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("distinct id row exists")+ }++ async fn op_person_status(&self, op_id: Uuid, person_id: i64) -> String {+ sqlx::query_scalar(+ "SELECT status FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",+ )+ .bind(op_id)+ .bind(person_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("op person row exists")+ }++ /// The `sealed` payload of an op's per-person row (the fence snapshot+ /// for sources, the folded survivor for the target).+ async fn op_person_sealed(&self, op_id: Uuid, person_id: i64) -> Option<serde_json::Value> {+ sqlx::query_scalar(+ "SELECT sealed FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",+ )+ .bind(op_id)+ .bind(person_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("op person row exists")+ }++ /// The `moved` payload of an op's per-person row (the repointed+ /// mappings for sources, the claim record for the target).+ async fn op_person_moved(&self, op_id: Uuid, person_id: i64) -> Option<serde_json::Value> {+ sqlx::query_scalar(+ "SELECT moved FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",+ )+ .bind(op_id)+ .bind(person_id)+ .fetch_one(&self.ctx.pool)+ .await+ .expect("op person row exists")+ }++ fn assert_write_fenced(&self, err: Status, op_id: Uuid) {+ assert_eq!(err.code(), Code::FailedPrecondition);+ assert!(+ err.message().contains("PERSON_MERGING"),+ "expected the typed merge rejection, got: {}",+ err.message()+ );+ assert_eq!(+ err.metadata().get(FENCED_METADATA_KEY).unwrap(),+ "merge",+ "the x-person-fenced metadata carries the op type"+ );+ assert!(err.message().contains(&op_id.to_string()));+ }+}++fn merge_request(target: &str, sources: &[&str]) -> MergeRequest {+ MergeRequest {+ target_distinct_id: target.to_string(),+ sources: sources+ .iter()+ .map(|did| MergeSourceEntry {+ distinct_id: did.to_string(),+ event_uuid: Uuid::now_v7().to_string(),+ })+ .collect(),+ event_set: json!({}),+ event_set_once: json!({}),+ allow_identified_sources: false,+ move_limit: 1_000,+ }+}++fn result_map(outcome: &MergeOutcome) -> HashMap<String, String> {+ outcome+ .results+ .iter()+ .map(|r| (r.distinct_id.clone(), r.outcome.clone()))+ .collect()+}++#[tokio::test]+async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("merge-target").await;+ let source = h.ctx.insert_person_with_distinct_id("merge-source").await;+ h.add_distinct_id(source, "merge-source-alias").await;+ h.set_person(target, r#"{"a": "target"}"#, 3, false).await;+ h.set_person(source, r#"{"a": "source", "b": "source"}"#, 7, false)+ .await;+ // Satellite rows: the source's move, and a target-side hash-key+ // override that must win the dedupe.+ sqlx::query("INSERT INTO posthog_cohortpeople (cohort_id, person_id) VALUES (1, $1)")+ .bind(source)+ .execute(&h.ctx.pool)+ .await+ .unwrap();+ for (person, hash) in [(target, "target-hash"), (source, "source-hash")] {+ sqlx::query(+ r#"+ INSERT INTO posthog_featureflaghashkeyoverride+ (feature_flag_key, hash_key, person_id, team_id)+ VALUES ('flag', $2, $1, $3)+ "#,+ )+ .bind(person)+ .bind(hash)+ .bind(h.ctx.team_id as i32)+ .execute(&h.ctx.pool)+ .await+ .unwrap();+ }++ // The source was seen after the target: the fold must carry the max.+ h.leader.set_last_seen(target, 1_000);+ h.leader.set_last_seen(source, 2_000);++ let op_id = Uuid::now_v7();+ let mut request = merge_request("merge-target", &["merge-source"]);+ request.event_set = json!({"c": "event"});+ let outcome = h.execute(op_id, &request).await.expect("merge completes");++ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("merge-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ let survivor = outcome+ .survivor+ .expect("committed merges carry the survivor");+ assert_eq!(+ survivor["properties"],+ json!({"a": "target", "b": "source", "c": "event"}),+ "target wins, snapshot fills, event overrides"+ );+ assert_eq!(survivor["version"], json!(8), "max(target 3, sealed 7) + 1");+ assert_eq!(survivor["is_identified"], json!(true));++ // Both of the source's distinct ids now point at the target, above+ // their previous versions.+ for did in ["merge-source", "merge-source-alias"] {+ let (person_id, is_deleted, version) = h.pdi_state(did).await;+ assert_eq!(person_id, target, "{did} repointed");+ assert!(!is_deleted);+ assert_eq!(version, 1);+ }+ // The source person is a scrubbed tombstone at exactly sealed + 1; the+ // target's own row is untouched (the writer projects the fold).+ let (is_deleted, version, properties) = h.person_state(source).await;+ assert!(is_deleted);+ assert_eq!(version, 8);+ assert_eq!(properties, json!({}));+ let (target_deleted, target_version, _) = h.person_state(target).await;+ assert!(!target_deleted);+ assert_eq!(target_version, 3, "sync plane never writes the target");++ // Satellite rows moved; the target's own hash-key override won.+ let moved_cohort: i64 =+ sqlx::query_scalar("SELECT count(*) FROM posthog_cohortpeople WHERE person_id = $1")+ .bind(target)+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(moved_cohort, 1);+ let hash: String = sqlx::query_scalar(+ r#"+ SELECT hash_key FROM posthog_featureflaghashkeyoverride+ WHERE team_id = $1 AND person_id = $2 AND feature_flag_key = 'flag'+ "#,+ )+ .bind(h.ctx.team_id as i32)+ .bind(target)+ .fetch_one(&h.ctx.pool)+ .await+ .unwrap();+ assert_eq!(hash, "target-hash");++ // The leader protocol ran in order, and the committed release saw the+ // source's mark still live — the invariant the leader's death-document+ // verification depends on (the sim also enforces it).+ assert_eq!(+ h.leader.calls(),+ vec![+ LeaderCall::Fence {+ person_id: source,+ op_type: LifecycleOpType::Merge,+ },+ LeaderCall::Fold {+ target_person_id: target,+ snapshot_versions: vec![7],+ // The source's later last_seen_at survived the frozen+ // snapshot round-trip and won the max-merge.+ folded_last_seen_at: Some(2_000),+ },+ LeaderCall::ReleaseCommitted {+ person_id: source,+ sealed_version: 7,+ mark_status_at_release: Some("sealed".to_string()),+ },+ ]+ );++ // Marks settled: the target's cleared, the source's deleted.+ assert_eq!(h.op_person_status(op_id, target).await, "cleared");+ assert_eq!(h.op_person_status(op_id, source).await, "deleted");++ h.ctx.cleanup().await.expect("cleanup");+}++/// The state-machine walkthrough: one `step_once` per transition, with+/// the full invariant set asserted in every state — what is persisted,+/// which fences and marks are held, and what other actors (ordinary+/// writes, rival lifecycle ops) are allowed to do.+#[tokio::test]+async fn a_walkthrough_asserts_every_state_and_shields_it_from_other_actors() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let target = h.ctx.insert_person_with_distinct_id("walk-target").await;+ let source = h.ctx.insert_person_with_distinct_id("walk-source").await;+ h.add_distinct_id(source, "walk-source-alias").await;+ h.set_person(target, r#"{"a": "target"}"#, 3, false).await;+ h.set_person(source, r#"{"a": "source", "b": "source"}"#, 7, false)+ .await;++ let op_id = Uuid::now_v7();+ let request = merge_request("walk-target", &["walk-source"]);++ // State: started. Nothing claimed, nothing fenced, everyone writable.+ let row = h.create(op_id, &request).await;+ assert_eq!(row.step, "started");+ assert!(row.completed_at.is_none());+ assert!(h.leader.fence_for(source).is_none());+ h.leader+ .admit_write(team, source)+ .await+ .expect("source writable before the claim");++ // started → claimed: marks exist, but fences do not yet — the claim's+ // shield is the mark index, which blocks rival lifecycle ops.+ let row = h.step(op_id).await.expect("claim step");+ assert_eq!(row.step, "claimed");+ assert_eq!(h.op_person_status(op_id, target).await, "marked");+ assert_eq!(h.op_person_status(op_id, source).await, "marked");+ assert!(+ h.leader.fence_for(source).is_none(),+ "fences are installed at seal, not claim"+ );+ h.leader+ .admit_write(team, source)+ .await+ .expect("ordinary writes still flow between claim and seal");+ let rival = h+ .execute(+ Uuid::now_v7(),+ &merge_request("walk-source", &["walk-target"]),+ )+ .await+ .expect("rival op reaches a terminal step");+ assert!(+ rival.aborted,+ "the mark shields claimed persons from rival ops"+ );+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, "claimed", "the rival left our op untouched");+ assert!(!completed);+ assert_eq!(h.op_person_status(op_id, source).await, "marked");++ // claimed → sources_sealed: the fence goes up, the snapshot freezes,+ // and other actors' writes to the source start bouncing with the+ // typed rejection. The target is never fenced.+ let row = h.step(op_id).await.expect("seal step");+ assert_eq!(row.step, "sources_sealed");+ assert_eq!(h.op_person_status(op_id, source).await, "sealed");+ let fence = h.leader.fence_for(source).expect("fence installed");+ assert_eq!(fence.op_id, op_id);+ assert_eq!(fence.op_type, LifecycleOpType::Merge);+ let err = h.leader.admit_write(team, source).await.unwrap_err();+ h.assert_write_fenced(err, op_id);+ h.leader+ .admit_write(team, target)+ .await+ .expect("the merge target is never fenced");+ let sealed = h+ .op_person_sealed(op_id, source)+ .await+ .expect("seal snapshot persisted");+ assert_eq!(sealed["version"], json!(7));+ assert_eq!(sealed["is_identified"], json!(false));+ assert_eq!(sealed["properties"], json!({"a": "source", "b": "source"}));++ // sources_sealed → document_folded: the survivor document persists on+ // the target row; nothing in Postgres has been destroyed yet, and the+ // source stays shielded.+ let row = h.step(op_id).await.expect("fold step");+ assert_eq!(row.step, "document_folded");+ let survivor = h+ .op_person_sealed(op_id, target)+ .await+ .expect("survivor persisted on the target row");+ assert_eq!(+ survivor["properties"],+ json!({"a": "target", "b": "source"})+ );+ assert_eq!(survivor["version"], json!(8), "max(target 3, sealed 7) + 1");+ let (source_deleted, source_version, _) = h.person_state(source).await;+ assert!(!source_deleted, "the flip has not run yet");+ assert_eq!(source_version, 7);+ assert!(h.leader.fence_for(source).is_some());+ let err = h.leader.admit_write(team, source).await.unwrap_err();+ h.assert_write_fenced(err, op_id);++ // document_folded → flipped: Postgres is destroyed and repointed, but+ // the fence is STILL held — the half-dead source is never exposed as+ // writable, and no death document exists yet.+ let row = h.step(op_id).await.expect("flip step");+ assert_eq!(row.step, "flipped");+ for did in ["walk-source", "walk-source-alias"] {+ let (person_id, is_deleted, version) = h.pdi_state(did).await;+ assert_eq!(person_id, target, "{did} repointed");+ assert!(!is_deleted);+ assert_eq!(version, 1);+ }+ let (source_deleted, source_version, source_properties) = h.person_state(source).await;+ assert!(source_deleted, "the source is a scrubbed tombstone");+ assert_eq!(source_version, 8, "sealed 7 + 1");+ assert_eq!(source_properties, json!({}));+ let moved = h+ .op_person_moved(op_id, source)+ .await+ .expect("the repointed mappings are recorded on the source row");+ let moved_dids: HashSet<String> = moved+ .as_array()+ .expect("moved is an array")+ .iter()+ .map(|entry| {+ assert_eq!(entry["version"], json!(1));+ entry["distinct_id"].as_str().unwrap().to_string()+ })+ .collect();+ assert_eq!(+ moved_dids,+ HashSet::from(["walk-source".to_string(), "walk-source-alias".to_string()])+ );+ assert_eq!(+ h.op_person_status(op_id, target).await,+ "cleared",+ "the target is claimable again from here"+ );+ assert_eq!(+ h.op_person_status(op_id, source).await,+ "sealed",+ "the source mark is the fence's durable record until release"+ );+ assert!(+ h.leader.fence_for(source).is_some(),+ "fence held across the flip"+ );+ let err = h.leader.admit_write(team, source).await.unwrap_err();+ h.assert_write_fenced(err, op_id);+ assert!(h.leader.death_documents().is_empty());++ // flipped → completed: the death document is produced, the fence+ // released, the mark settled, and the outcome recorded. Only now does+ // the source answer not-found instead of fenced.+ let row = h.step(op_id).await.expect("complete step");+ assert_eq!(row.step, STEP_COMPLETED);+ assert!(row.completed_at.is_some());+ let outcome: MergeOutcome = serde_json::from_value(row.outcome.clone().unwrap()).unwrap();+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("walk-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ let deaths = h.leader.death_documents();+ assert_eq!(deaths.len(), 1);+ assert_eq!(deaths[0].person_id, source);+ assert_eq!(deaths[0].version, 8, "death document at sealed 7 + 1");+ assert!(deaths[0].created_at > 0);+ assert!(h.leader.fence_for(source).is_none());+ let err = h.leader.admit_write(team, source).await.unwrap_err();+ assert_eq!(err.code(), Code::NotFound);+ h.leader+ .admit_write(team, target)+ .await+ .expect("the merged person takes writes again");+ assert_eq!(h.op_person_status(op_id, source).await, "deleted");++ // A step on a terminal op is a no-op returning the recorded row.+ let again = h.step(op_id).await.expect("terminal step is a no-op");+ assert_eq!(again.step, STEP_COMPLETED);+ assert_eq!(again.outcome, row.outcome);++ h.ctx.cleanup().await.expect("cleanup");+}++/// A fence failure for one of two sources leaves the op re-drivable:+/// the already-installed fence stands (the source stays shielded), the+/// retry re-seals it idempotently, and the fold consumes the snapshots+/// in request order — first source wins contested keys.+#[tokio::test]+async fn a_partially_failed_seal_re_seals_and_sources_fold_in_request_order() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let _target = h.ctx.insert_person_with_distinct_id("prec-target").await;+ let s1 = h.ctx.insert_person_with_distinct_id("prec-s1").await;+ let s2 = h.ctx.insert_person_with_distinct_id("prec-s2").await;+ h.set_person(s1, r#"{"p": "s1", "q": "s1"}"#, 5, false)+ .await;+ h.set_person(s2, r#"{"p": "s2", "r": "s2"}"#, 9, false)+ .await;++ let op_id = Uuid::now_v7();+ let request = merge_request("prec-target", &["prec-s1", "prec-s2"]);+ h.leader.fail_next(+ Rpc::Fence,+ s2,+ Status::unavailable("injected fence failure"),+ );++ let row = h.create(op_id, &request).await;+ assert_eq!(row.step, "started");+ let row = h.step(op_id).await.expect("claim step");+ assert_eq!(row.step, "claimed");++ // The partial failure: s1's fence installed, s2's failed, the step+ // did not advance and no snapshot was persisted.+ let err = h.step(op_id).await.expect_err("injected failure surfaces");+ assert!(matches!(err, SagaError::Leader(_)));+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, "claimed");+ assert!(!completed);+ assert_eq!(h.leader.fence_for(s1).expect("s1 fenced").op_id, op_id);+ assert!(h.leader.fence_for(s2).is_none());+ assert_eq!(h.op_person_status(op_id, s1).await, "marked");+ assert_eq!(h.op_person_status(op_id, s2).await, "marked");+ assert!(h.op_person_sealed(op_id, s1).await.is_none());+ // The installed fence stands through the retry window: s1 stays+ // shielded even while the op is between attempts.+ let fenced = h.leader.admit_write(team, s1).await.unwrap_err();+ h.assert_write_fenced(fenced, op_id);++ // The retry re-seals s1 (a same-op re-fence) and fences s2.+ let row = h.step(op_id).await.expect("seal retry");+ assert_eq!(row.step, "sources_sealed");+ assert_eq!(+ h.leader.fence_for(s1).expect("s1 still fenced").op_id,+ op_id+ );+ assert_eq!(h.leader.fence_for(s2).expect("s2 fenced").op_id, op_id);+ assert_eq!(+ h.op_person_sealed(op_id, s1).await.unwrap()["version"],+ json!(5)+ );+ assert_eq!(+ h.op_person_sealed(op_id, s2).await.unwrap()["version"],+ json!(9)+ );++ let outcome = h.execute(op_id, &request).await.expect("merge completes");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([+ ("prec-s1".to_string(), OUTCOME_MERGED.to_string()),+ ("prec-s2".to_string(), OUTCOME_MERGED.to_string()),+ ])+ );+ // Precedence: the target has nothing, s1 (ordinal 0) fills p and q,+ // s2 only gets keys s1 did not take.+ let survivor = outcome.survivor.expect("survivor");+ assert_eq!(+ survivor["properties"],+ json!({"p": "s1", "q": "s1", "r": "s2"}),+ "earlier sources take precedence in the fold"+ );+ let deaths = h.leader.death_documents();+ assert_eq!(deaths.len(), 2);+ assert_eq!(deaths[0].version, 6, "s1 death at sealed 5 + 1");+ assert_eq!(deaths[1].version, 10, "s2 death at sealed 9 + 1");++ h.ctx.cleanup().await.expect("cleanup");+}++/// A fold failure keeps every fence and mark in place — the sources stay+/// shielded while the op waits — and the retry completes from the saved+/// step without re-fencing.+#[tokio::test]+async fn a_fold_failure_holds_the_fences_until_the_retry_completes() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let target = h.ctx.insert_person_with_distinct_id("fold-target").await;+ let source = h.ctx.insert_person_with_distinct_id("fold-source").await;+ h.set_person(source, r#"{"k": "v"}"#, 2, false).await;++ let op_id = Uuid::now_v7();+ let request = merge_request("fold-target", &["fold-source"]);+ h.leader.fail_next(+ Rpc::Fold,+ target,+ Status::unavailable("injected fold failure"),+ );++ let err = h+ .execute(op_id, &request)+ .await+ .expect_err("injected fold failure surfaces");+ assert!(matches!(err, SagaError::Leader(_)));+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(+ step, "sources_sealed",+ "the seal committed; the fold did not"+ );+ assert!(!completed);+ assert!(h.leader.fence_for(source).is_some());+ let fenced = h.leader.admit_write(team, source).await.unwrap_err();+ h.assert_write_fenced(fenced, op_id);+ assert!(h.op_person_sealed(op_id, target).await.is_none());+ assert!(h.leader.death_documents().is_empty());+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(!source_deleted);++ let outcome = h.execute(op_id, &request).await.expect("retry completes");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("fold-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ // The retry did not re-fence: one fence call for the whole op.+ let fence_calls = h+ .leader+ .calls()+ .iter()+ .filter(|c| matches!(c, LeaderCall::Fence { .. }))+ .count();+ assert_eq!(fence_calls, 1);+ assert!(h.leader.fence_for(source).is_none());+ assert_eq!(h.leader.death_documents().len(), 1);++ h.ctx.cleanup().await.expect("cleanup");+}++/// A release failure for one of two sources: the other's death document+/// is already produced, and the retry converges to exactly one death+/// document per source — the duplicate release is absorbed, never+/// re-produced — while the failed source stays fenced in between.+#[tokio::test]+async fn a_partial_release_failure_retries_to_one_death_document_each() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let target = h.ctx.insert_person_with_distinct_id("rel-target").await;+ let a = h.ctx.insert_person_with_distinct_id("rel-a").await;+ let b = h.ctx.insert_person_with_distinct_id("rel-b").await;+ h.set_person(a, r#"{"a": "a"}"#, 2, false).await;+ h.set_person(b, r#"{"b": "b"}"#, 4, false).await;++ let op_id = Uuid::now_v7();+ let request = merge_request("rel-target", &["rel-a", "rel-b"]);+ h.leader.fail_next(+ Rpc::Release,+ b,+ Status::unavailable("injected release failure"),+ );++ let err = h+ .execute(op_id, &request)+ .await+ .expect_err("injected release failure surfaces");+ assert!(matches!(err, SagaError::Leader(_)));+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, "flipped", "the flip committed; the release did not");+ assert!(!completed);+ // A's release landed: death produced, fence gone. B's did not: no+ // death, fence held, still shielded — even though its Postgres row is+ // already a tombstone, other actors see "fenced", never a half-dead+ // person.+ let deaths = h.leader.death_documents();+ assert_eq!(deaths.len(), 1, "only A's death document exists so far");+ assert_eq!(deaths[0].person_id, a);+ assert_eq!(deaths[0].version, 3, "A's death at sealed 2 + 1");+ assert!(h.leader.fence_for(a).is_none());+ assert!(h.leader.fence_for(b).is_some());+ let fenced = h.leader.admit_write(team, b).await.unwrap_err();+ h.assert_write_fenced(fenced, op_id);+ // Neither mark settled: the settle transaction runs only after every+ // release acks, because a settled mark would make the leader refuse+ // the retry's death document.+ assert_eq!(h.op_person_status(op_id, a).await, "sealed");+ assert_eq!(h.op_person_status(op_id, b).await, "sealed");+ assert!(+ !parked_state(&h.ctx.pool, op_id).await.0,+ "a transient failure leaves the op to the sweeper instead of parking it"+ );++ let outcome = h.execute(op_id, &request).await.expect("retry completes");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([+ ("rel-a".to_string(), OUTCOME_MERGED.to_string()),+ ("rel-b".to_string(), OUTCOME_MERGED.to_string()),+ ])+ );+ // Convergence, not duplication: A was released twice (the retry+ // re-releases every sealed source) but its death document was+ // absorbed, not re-produced.+ let a_releases = h+ .leader+ .calls()+ .iter()+ .filter(|c| matches!(c, LeaderCall::ReleaseCommitted { person_id, .. } if *person_id == a))+ .count();+ assert_eq!(a_releases, 2, "the retry re-released A");+ let deaths = h.leader.death_documents();+ assert_eq!(deaths.len(), 2, "exactly one death document per source");+ assert_eq!(+ deaths[0].version, 3,+ "A's death version unchanged by the retry"+ );+ assert_eq!(deaths[1].version, 5, "B's death at sealed 4 + 1");+ assert_eq!(h.op_person_status(op_id, a).await, "deleted");+ assert_eq!(h.op_person_status(op_id, b).await, "deleted");+ assert!(h.leader.fence_for(b).is_none());+ let err = h.leader.admit_write(team, a).await.unwrap_err();+ assert_eq!(err.code(), Code::NotFound);+ let (target_deleted, _, _) = h.person_state(target).await;+ assert!(!target_deleted);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_leader_refusal_at_release_parks_the_op_until_an_explicit_retry() {+ let h = MergeHarness::new().await;+ let source = h.ctx.insert_person_with_distinct_id("park-source").await;+ h.ctx.insert_person_with_distinct_id("park-target").await;+ h.set_person(source, r#"{"s": "s"}"#, 2, false).await;++ let op_id = Uuid::now_v7();+ let request = merge_request("park-target", &["park-source"]);+ // A definitive verification refusal in the real leader's+ // release-unverified shape, marker metadata included.+ h.leader.fail_next(+ Rpc::Release,+ source,+ semantic_refusal("injected verification refusal", "release-unverified"),+ );++ let err = h+ .execute(op_id, &request)+ .await+ .expect_err("the refusal surfaces");+ assert!(matches!(err, SagaError::LeaderRefused(_)));+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(+ step, "flipped",+ "the flip committed; the refused release did not"+ );+ assert!(!completed);+ let (parked, reason) = parked_state(&h.ctx.pool, op_id).await;+ assert!(parked, "a definitive refusal parks the op");+ assert_eq!(reason.as_deref(), Some("release-unverified"));++ // The refusal was scripted once, so it is gone: an explicit retry+ // with the same op_id un-parks, re-drives, and completes.+ let outcome = h.execute(op_id, &request).await.expect("retry completes");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("park-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ assert!(+ !parked_state(&h.ctx.pool, op_id).await.0,+ "claiming un-parks"+ );+ assert_eq!(h.leader.death_documents().len(), 1);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_leader_refusal_at_fold_aborts_and_releases_the_fences() {+ 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 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).+ 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)+ .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);+ assert!(+ !parked_state(&h.ctx.pool, op_id).await.0,+ "a pre-flip refusal aborts; it never parks"+ );++ // 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!(h.leader.death_documents().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++/// An abandoned merge op is driven through `sweep()`/`resume()` to a+/// merged outcome, while a parked op sitting next to it is skipped.+///+/// Isolation: this is the suite's single sweep call (see the engine+/// tests' header). Its one-hour lease keeps concurrent tests' fresh+/// NULL-lease ops outside the "never claimed" window, and the only+/// expired-lease rows in the suite are seeded here.+#[tokio::test]+async fn the_sweeper_drives_an_abandoned_merge_to_completion() {+ let h = MergeHarness::new().await;+ let source = h.ctx.insert_person_with_distinct_id("sweep-source").await;+ h.ctx.insert_person_with_distinct_id("sweep-target").await;++ // Created but never driven: the RPC died right after create-or-attach.+ let op_id = Uuid::now_v7();+ let request = merge_request("sweep-target", &["sweep-source"]);+ h.create(op_id, &request).await;+ sqlx::query("UPDATE lifecycle_op SET created_at = now() - interval '2 hours' WHERE op_id = $1")+ .bind(op_id)+ .execute(&h.ctx.pool)+ .await+ .expect("backdate the abandoned op");++ // A parked op that would otherwise be prime sweeper bait (expired+ // lease): a definitive leader refusal means automatic retry cannot+ // succeed, so the sweep must leave it alone.+ let parked_op_id = Uuid::now_v7();+ sqlx::query(+ r#"+ INSERT INTO lifecycle_op+ (op_id, op_type, team_id, step, request, lease_expires_at, parked_at, parked_reason)+ VALUES ($1, 'merge', $2, 'started', '{}'::jsonb, now() - interval '1 minute', now(), 'test-refusal')+ "#,+ )+ .bind(parked_op_id)+ .bind(h.ctx.team_id as i32)+ .execute(&h.ctx.pool)+ .await+ .expect("insert parked op");++ let sweep_engine = Engine::new(+ h.ctx.pool.clone(),+ personhog_identity::lifecycle::engine::EngineConfig {+ lease: std::time::Duration::from_secs(3600),+ execute_timeout: std::time::Duration::from_secs(10),+ poll_interval: std::time::Duration::from_millis(25),+ attempt_alert_threshold: 5,+ },+ );+ let resumed = sweep_engine.sweep(&[&h.driver]).await.expect("sweep runs");+ assert!(resumed >= 1, "the abandoned merge was resumed");++ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, STEP_COMPLETED);+ assert!(completed);+ let outcome: MergeOutcome = serde_json::from_value(+ sqlx::query_scalar::<_, serde_json::Value>(+ "SELECT outcome FROM lifecycle_op WHERE op_id = $1",+ )+ .bind(op_id)+ .fetch_one(&h.ctx.pool)+ .await+ .expect("outcome recorded"),+ )+ .expect("outcome parses");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("sweep-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ // Full-protocol effects, scoped to this test's persons because the+ // sweep's scan is global and may also touch rows other tests seeded.+ let (source_deleted, _, _) = h.person_state(source).await;+ assert!(source_deleted);+ assert!(!h.pdi_state("sweep-source").await.1);+ assert_eq!(+ h.leader+ .death_documents()+ .iter()+ .filter(|d| d.person_id == source)+ .count(),+ 1+ );+ assert!(h.leader.fence_for(source).is_none());++ let (step, completed) = op_row_state(&h.ctx.pool, parked_op_id).await;+ assert_eq!(step, "started", "the sweep skipped the parked op");+ assert!(!completed);+ assert!(parked_state(&h.ctx.pool, parked_op_id).await.0);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_fold_without_a_live_target_mark_is_refused_and_the_op_aborts() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let source = h.ctx.insert_person_with_distinct_id("tmark-source").await;+ h.ctx.insert_person_with_distinct_id("tmark-target").await;++ let op_id = Uuid::now_v7();+ let request = merge_request("tmark-target", &["tmark-source"]);+ h.create(op_id, &request).await;+ let row = h.step(op_id).await.expect("claim");+ assert_eq!(row.step, "claimed");+ let row = h.step(op_id).await.expect("seal");+ assert_eq!(row.step, "sources_sealed");++ // The target mark vanishes under a live op (manual surgery, a settle+ // bug). Unlike a scripted status, this refusal comes from the sim's+ // own verification, the same check the real leader runs.+ sqlx::query(+ "UPDATE lifecycle_op_person SET status = 'cleared' WHERE op_id = $1 AND role = 'target'",+ )+ .bind(op_id)+ .execute(&h.ctx.pool)+ .await+ .expect("clear the target mark");++ let row = h+ .step(op_id)+ .await+ .expect("the refused fold aborts cleanly");+ assert_eq!(row.step, STEP_ABORTED);+ assert!(row.completed_at.is_some());+ assert!(!parked_state(&h.ctx.pool, op_id).await.0);+ assert!(+ h.leader.fence_for(source).is_none(),+ "the abort released the fence"+ );+ h.leader+ .admit_write(team, source)+ .await+ .expect("the source unfroze");+ assert!(h.leader.death_documents().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_leader_refusal_at_fence_aborts_instead_of_parking() {+ let h = MergeHarness::new().await;+ let team = h.ctx.team_id;+ let source_a = h.ctx.insert_person_with_distinct_id("sabort-a").await;+ let source_b = h.ctx.insert_person_with_distinct_id("sabort-b").await;+ h.ctx.insert_person_with_distinct_id("sabort-target").await;++ let op_id = Uuid::now_v7();+ let request = merge_request("sabort-target", &["sabort-a", "sabort-b"]);+ // FencePerson has no refusals of its own (this one is scripted);+ // pins the policy that any pre-flip refusal backs the op out.+ h.leader.fail_next(+ Rpc::Fence,+ source_b,+ semantic_refusal("injected fence refusal", "test-refusal"),+ );++ let outcome = h+ .execute(op_id, &request)+ .await+ .expect("the refusal aborts the op cleanly");+ assert!(outcome.aborted);+ assert!(!parked_state(&h.ctx.pool, op_id).await.0);+ // The sibling's fence from the same fan-out was released by the+ // unwind; the refused source never had one.+ assert!(h.leader.fence_for(source_a).is_none());+ assert!(h.leader.fence_for(source_b).is_none());+ h.leader+ .admit_write(team, source_a)+ .await+ .expect("the fenced sibling unfroze");+ assert!(h.leader.death_documents().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn claim_classification_settles_each_source_without_touching_it() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("cls-target").await;+ h.add_distinct_id(target, "cls-target-alias").await;+ let identified = h.ctx.insert_person_with_distinct_id("cls-identified").await;+ h.set_person(identified, "{}", 0, true).await;+ let oversized = h.ctx.insert_person_with_distinct_id("cls-oversized").await;+ h.add_distinct_id(oversized, "cls-oversized-2").await;+ h.add_distinct_id(oversized, "cls-oversized-3").await;+ let mergeable = h.ctx.insert_person_with_distinct_id("cls-mergeable").await;++ let mut request = merge_request(+ "cls-target",+ &[+ "cls-target-alias", // resolves to the target person+ "cls-missing", // resolves to nothing+ "cls-identified",+ "cls-oversized",+ "cls-mergeable",+ ],+ );+ request.move_limit = 2;+ let outcome = h+ .execute(Uuid::now_v7(), &request)+ .await+ .expect("merge completes");++ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([+ (+ "cls-target-alias".to_string(),+ OUTCOME_NOOP_SAME_PERSON.to_string()+ ),+ (+ "cls-missing".to_string(),+ OUTCOME_SKIPPED_CONFLICT.to_string()+ ),+ (+ "cls-identified".to_string(),+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string()+ ),+ (+ "cls-oversized".to_string(),+ OUTCOME_SKIPPED_MOVE_LIMIT.to_string()+ ),+ ("cls-mergeable".to_string(), OUTCOME_MERGED.to_string()),+ ])+ );++ // Skipped persons are untouched — live, ids where they were.+ for (person, did) in [(identified, "cls-identified"), (oversized, "cls-oversized")] {+ let (is_deleted, _, _) = h.person_state(person).await;+ assert!(!is_deleted);+ assert_eq!(h.pdi_state(did).await.0, person);+ }+ let (mergeable_deleted, _, _) = h.person_state(mergeable).await;+ assert!(mergeable_deleted);+ assert_eq!(h.pdi_state("cls-mergeable").await.0, target);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_target_held_by_another_op_aborts_before_mutating_anything() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("held-target").await;+ let source = h.ctx.insert_person_with_distinct_id("held-source").await;+ let foreign_op = h.foreign_mark(target).await;++ let op_id = Uuid::now_v7();+ let outcome = h+ .execute(op_id, &merge_request("held-target", &["held-source"]))+ .await+ .expect("op reaches a terminal step");++ assert!(outcome.aborted);+ assert!(outcome.survivor.is_none());+ assert_eq!(+ result_map(&outcome),+ HashMap::from([(+ "held-source".to_string(),+ OUTCOME_SKIPPED_CONFLICT.to_string()+ )])+ );+ let (step, _) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, STEP_ABORTED);++ // The world is unchanged: both persons live, ids in place, the foreign+ // op's mark untouched, no leader call ever made.+ for (person, did) in [(target, "held-target"), (source, "held-source")] {+ let (is_deleted, _, _) = h.person_state(person).await;+ assert!(!is_deleted);+ assert_eq!(h.pdi_state(did).await.0, person);+ }+ assert_eq!(h.op_person_status(foreign_op, target).await, "marked");+ assert!(h.leader.calls().is_empty());++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_source_held_by_another_op_is_skipped_while_the_rest_merge() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("part-target").await;+ let held = h.ctx.insert_person_with_distinct_id("part-held").await;+ let free = h.ctx.insert_person_with_distinct_id("part-free").await;+ h.foreign_mark(held).await;++ let outcome = h+ .execute(+ Uuid::now_v7(),+ &merge_request("part-target", &["part-held", "part-free"]),+ )+ .await+ .expect("merge completes");++ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([+ (+ "part-held".to_string(),+ OUTCOME_SKIPPED_CONFLICT.to_string()+ ),+ ("part-free".to_string(), OUTCOME_MERGED.to_string()),+ ])+ );+ let (held_deleted, _, _) = h.person_state(held).await;+ assert!(!held_deleted);+ let (free_deleted, _, _) = h.person_state(free).await;+ assert!(free_deleted);+ assert_eq!(h.pdi_state("part-held").await.0, held);+ assert_eq!(h.pdi_state("part-free").await.0, target);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn a_leader_failure_is_retried_from_the_saved_step() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("retry-target").await;+ let source = h.ctx.insert_person_with_distinct_id("retry-source").await;+ h.set_person(source, r#"{"k": "v"}"#, 2, false).await;++ let op_id = Uuid::now_v7();+ let request = merge_request("retry-target", &["retry-source"]);++ h.leader.fail_next(+ Rpc::Fence,+ source,+ Status::unavailable("injected fence failure"),+ );+ let err = h+ .execute(op_id, &request)+ .await+ .expect_err("the injected fence failure surfaces");+ assert!(matches!(err, SagaError::Leader(_)));+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, "claimed", "the claim committed; the seal did not");+ assert!(!completed);+ // The source stays claimed across the failure: the mark is the op's+ // durable hold on it.+ assert_eq!(h.op_person_status(op_id, source).await, "marked");++ let outcome = h+ .execute(op_id, &request)+ .await+ .expect("the retry drives the op home");+ assert!(!outcome.aborted);+ assert_eq!(+ result_map(&outcome),+ HashMap::from([("retry-source".to_string(), OUTCOME_MERGED.to_string())])+ );+ let (step, completed) = op_row_state(&h.ctx.pool, op_id).await;+ assert_eq!(step, STEP_COMPLETED);+ assert!(completed);+ assert_eq!(h.pdi_state("retry-source").await.0, target);++ h.ctx.cleanup().await.expect("cleanup");+}++#[tokio::test]+async fn an_identified_source_detected_at_seal_time_drops_with_a_released_fence() {+ let h = MergeHarness::new().await;+ let target = h.ctx.insert_person_with_distinct_id("seal-target").await;+ let source = h.ctx.insert_person_with_distinct_id("seal-source").await;+ // Postgres still says unidentified — only the leader's sealed state+ // carries the flip. The claim's cheap pre-filter must not catch it;+ // the seal's authoritative re-check must.+ h.leader.set_sealed_identified(source, true);++ let op_id = Uuid::now_v7();+ let outcome = h+ .execute(op_id, &merge_request("seal-target", &["seal-source"]))+ .await+ .expect("op reaches a terminal step");++ assert!(+ outcome.aborted,+ "the only source dropped, so the op aborted"+ );+ assert_eq!(+ result_map(&outcome),+ HashMap::from([(+ "seal-source".to_string(),+ OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string()+ )])+ );+ // The fence was installed, then released without a death document; the+ // source lives on, unmerged and writable again.+ let calls = h.leader.calls();+ assert!(calls.contains(&LeaderCall::Fence {+ person_id: source,+ op_type: LifecycleOpType::Merge,+ }));+ assert!(calls+ .iter()+ .any(|c| matches!(c, LeaderCall::ReleaseAborted { person_id } if *person_id == source)));+ assert!(!calls+ .iter()+ .any(|c| matches!(c, LeaderCall::ReleaseCommitted { .. })));+ assert!(h.leader.death_documents().is_empty());+ assert!(h.leader.fence_for(source).is_none());+ h.leader+ .admit_write(h.ctx.team_id, source)+ .await+ .expect("the dropped source takes writes again");+ let (is_deleted, _, _) = h.person_state(source).await;+ assert!(!is_deleted);+ let (target_deleted, _, _) = h.person_state(target).await;+ assert!(!target_deleted);+ assert_eq!(h.pdi_state("seal-source").await.0, source);++ h.ctx.cleanup().await.expect("cleanup");+}++async fn op_row_state(pool: &PgPool, op_id: Uuid) -> (String, bool) {+ let row: (String, Option<chrono::DateTime<Utc>>) =+ sqlx::query_as("SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(pool)+ .await+ .expect("op row exists");+ (row.0, row.1.is_some())+}++async fn parked_state(pool: &PgPool, op_id: Uuid) -> (bool, Option<String>) {+ let row: (Option<chrono::DateTime<Utc>>, Option<String>) =+ sqlx::query_as("SELECT parked_at, parked_reason FROM lifecycle_op WHERE op_id = $1")+ .bind(op_id)+ .fetch_one(pool)+ .await+ .expect("op row exists");+ (row.0.is_some(), row.1)+}diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rsindex 041a36f45e60..40cd7254ff0a 100644--- a/rust/personhog-leader/src/fence.rs+++ b/rust/personhog-leader/src/fence.rs@@ -17,9 +17,13 @@//! The leader never reclaims a fence on its own, and deliberately so.//! personhog-identity owns lifecycle correctness: every op is driven to a//! terminal state (lease steal, sweeper resumption), so a `ReleaseFence`-//! always eventually arrives. An entry that outlives a crashed saga is-//! not stale — the mark is still live, the op really is unfinished, and-//! the person really should stay frozen. For that guarantee to hold, a+//! always eventually arrives, with one exception: an op whose committed+//! release this leader definitively refused (a semantic refusal) is+//! parked by the saga engine and stops retrying, so its fences hold+//! until an operator re-drives it. The person stays frozen rather than+//! half-destroyed. An entry that outlives a crashed saga is not stale —+//! the mark is still live, the op really is unfinished, and the person+//! really should stay frozen. For that guarantee to hold, a//! release must never *vacuously* succeed: both fence RPCs verify this//! pod serves the partition, so a misrouted call fails and identity's//! retry reaches the pod whose map actually gates the writes.@@ -74,15 +78,7 @@ pub const FENCED_OP_ID_METADATA_KEY: &str = "x-person-fenced-op-id";/// retry loop; the marker (see/// `personhog_common::grpc::SEMANTIC_REFUSAL_METADATA_KEY`) makes the/// refusal survive the trip.-pub fn semantic_refusal(message: impl Into<String>, reason: &'static str) -> Status {- let mut status = Status::failed_precondition(message.into());- if let Ok(value) = reason.parse() {- status- .metadata_mut()- .insert(personhog_common::grpc::SEMANTIC_REFUSAL_METADATA_KEY, value);- }- status-}+pub use personhog_common::grpc::semantic_refusal;/// The typed rejection for a write to a fenced person: PERSON_DELETING //// PERSON_MERGING per the RFC, encoded as FAILED_PRECONDITION plusdiff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex aff08a819e20..291fd34e6d13 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -1605,9 +1605,17 @@ impl PersonHogLeader for PersonHogLeaderService {let refence = if let Some(entry) = self.fences.get(&cache_key) {if entry.op_id != op_id {+ let holder = *entry.value();+ drop(entry);// At most one lifecycle op holds a person; the loser backs- // off or aborts.- return Err(fenced_status(entry.value()));+ // off or aborts. The holder may also be a ghost (its op+ // settled without this leader hearing); kick the lazy heal+ // like the write paths do, since on a low-traffic person+ // no other caller will.+ if let Some(healer) = &self.fence_healer {+ healer.maybe_heal(cache_key.clone(), holder);+ }+ return Err(fenced_status(&holder));}true} else {diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rsindex b2b26cb2f27f..3414fd2e2d34 100644--- a/rust/personhog-leader/tests/fence_integration.rs+++ b/rust/personhog-leader/tests/fence_integration.rs@@ -772,6 +772,162 @@ async fn a_ghost_fence_heals_after_a_rejected_write() {}}+/// A contender's FencePerson bouncing on a ghost must trigger the same+/// lazy heal as a rejected write: on a low-traffic person no other+/// caller ever observes the ghost, so the contending op would retry+/// forever.+#[tokio::test]+async fn a_ghost_fence_heals_after_a_rejected_fence_attempt() {+ let pool = common::create_persons_pool().await;+ let mut harness = start_fence_harness(+ test_cached_person(),+ Some(PgFallback {+ pool: pool.clone(),+ table: "posthog_person".to_string(),+ }),+ )+ .await;+ let team_id = harness.team_id;+ let partition = harness.partition;+ let person_id = harness.person_id;+ let ghost_op = Uuid::now_v7();+ let contender_op = Uuid::now_v7();++ sqlx::query(+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",+ )+ .bind(ghost_op)+ .bind(team_id as i32)+ .execute(&pool)+ .await+ .expect("insert 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(), 'victim', 'sealed')",+ )+ .bind(ghost_op)+ .bind(team_id as i32)+ .bind(person_id)+ .execute(&pool)+ .await+ .expect("insert mark");++ harness+ .client+ .fence_person(with_partition(+ fence_request(team_id, person_id, &ghost_op),+ partition,+ ))+ .await+ .expect("fence succeeds");++ // The op settles (release acked to the saga, mark rows cleaned up)+ // without this leader hearing about it — the ghost scenario.+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")+ .bind(ghost_op)+ .execute(&pool)+ .await+ .expect("settle the op");++ let status = harness+ .client+ .fence_person(with_partition(+ fence_request(team_id, person_id, &contender_op),+ partition,+ ))+ .await+ .expect_err("the first fence attempt still bounces on the ghost");+ assert_eq!(status.code(), Code::FailedPrecondition);++ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);+ loop {+ match harness+ .client+ .fence_person(with_partition(+ fence_request(team_id, person_id, &contender_op),+ partition,+ ))+ .await+ {+ Ok(_) => break,+ Err(status) if status.code() == Code::FailedPrecondition => {+ assert!(+ tokio::time::Instant::now() < deadline,+ "the ghost fence was never healed"+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ Err(other) => panic!("unexpected rejection: {other}"),+ }+ }+}++/// The heal's safety half: a fence whose op holds a live mark is not a+/// ghost, and heal checks triggered by a contender's rejected fence+/// attempts must never clear it.+#[tokio::test]+async fn a_live_marked_fence_survives_heal_attempts() {+ let pool = common::create_persons_pool().await;+ let mut harness = start_fence_harness(+ test_cached_person(),+ Some(PgFallback {+ pool: pool.clone(),+ table: "posthog_person".to_string(),+ }),+ )+ .await;+ let team_id = harness.team_id;+ let partition = harness.partition;+ let person_id = harness.person_id;+ let holder_op = Uuid::now_v7();+ let contender_op = Uuid::now_v7();++ sqlx::query(+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",+ )+ .bind(holder_op)+ .bind(team_id as i32)+ .execute(&pool)+ .await+ .expect("insert 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(), 'victim', 'sealed')",+ )+ .bind(holder_op)+ .bind(team_id as i32)+ .bind(person_id)+ .execute(&pool)+ .await+ .expect("insert live mark");++ harness+ .client+ .fence_person(with_partition(+ fence_request(team_id, person_id, &holder_op),+ partition,+ ))+ .await+ .expect("fence succeeds");++ // A wrong clear would let a later attempt succeed and fail the loop.+ let deadline = tokio::time::Instant::now() + Duration::from_millis(500);+ while tokio::time::Instant::now() < deadline {+ let status = harness+ .client+ .fence_person(with_partition(+ fence_request(team_id, person_id, &contender_op),+ partition,+ ))+ .await+ .expect_err("the live fence keeps rejecting the contender");+ assert_eq!(status.code(), Code::FailedPrecondition);+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+}+/// The fail-closed half of the committed release: the request — even with/// a fence the caller installed itself — is never enough to destroy a/// person. Without a live mark row vouching for the op, the release isdiff --git a/rust/persons_migrations/20260811000001_add_lifecycle_op_parking.sql b/rust/persons_migrations/20260811000001_add_lifecycle_op_parking.sqlnew file mode 100644index 000000000000..75ceae4f30f7--- /dev/null+++ b/rust/persons_migrations/20260811000001_add_lifecycle_op_parking.sql@@ -0,0 +1,14 @@+-- Parking for lifecycle ops the leader has definitively refused.+--+-- A semantic refusal (the leader rejecting the request itself) cannot be+-- outlived by retries: the sweeper skips parked ops instead of retrying+-- them forever, and an explicit retry with the same op_id claims,+-- un-parks, and re-drives once the cause is fixed.+--+-- SAFE: adds nullable columns to a small saga-state table; takes only a+-- brief ACCESS EXCLUSIVE lock with no rewrite. Idempotent and safe to+-- re-run.++ALTER TABLE lifecycle_op+ ADD COLUMN IF NOT EXISTS parked_at TIMESTAMP WITH TIME ZONE,+ ADD COLUMN IF NOT EXISTS parked_reason TEXT;