Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(personhog): add delete saga engine and DeletePersons endpoint flow (#77360)

José Sequeira262ef757a0a0
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index f2d0bba8ec6f..bec5bfc8e641 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8508,7 +8508,10 @@ dependencies = [
"personhog-common",
"personhog-proto",
"rand 0.8.5",
+ "serde",
+ "serde_json",
"sqlx",
+ "thiserror 2.0.18",
"tokio",
"tonic 0.12.3",
"tracing",
diff --git a/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json b/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json
new file mode 100644
index 000000000000..4f19428017a2
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person lop\n SET status = $3, sealed = jsonb_build_object('version', COALESCE(p.version, 0) + $4)\n FROM posthog_person p\n WHERE lop.op_id = $1 AND lop.status IN ('marked', 'sealed')\n AND p.team_id = $2 AND p.id = lop.person_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0"
+}
diff --git a/rust/personhog-identity/.sqlx/query-1d9bbbca7e556ac4851177dbc0b9a9ada897a718ec0f1f551b83f126a0b6fddb.json b/rust/personhog-identity/.sqlx/query-1d9bbbca7e556ac4851177dbc0b9a9ada897a718ec0f1f551b83f126a0b6fddb.json
new file mode 100644
index 000000000000..d98a6ed618c1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-1d9bbbca7e556ac4851177dbc0b9a9ada897a718ec0f1f551b83f126a0b6fddb.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id FROM lifecycle_op_person\n WHERE op_id = $1 AND status = 'sealed'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "1d9bbbca7e556ac4851177dbc0b9a9ada897a718ec0f1f551b83f126a0b6fddb"
+}
diff --git a/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.json b/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.json
new file mode 100644
index 000000000000..2905cf603e1d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-23001ff81d561bbae2ee9ae52baaf3cd8be4da1f992c66b1ce35e370edbf1efc.json
@@ -0,0 +1,23 @@
+{
+ "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-2f8a0f781254ae29766530ce387bd4aef256d4a4c8a4ed74b0a0e75b104a41be.json b/rust/personhog-identity/.sqlx/query-2f8a0f781254ae29766530ce387bd4aef256d4a4c8a4ed74b0a0e75b104a41be.json
new file mode 100644
index 000000000000..4de6c6b16ee1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-2f8a0f781254ae29766530ce387bd4aef256d4a4c8a4ed74b0a0e75b104a41be.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2f8a0f781254ae29766530ce387bd4aef256d4a4c8a4ed74b0a0e75b104a41be"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.json b/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.json
new file mode 100644
index 000000000000..04282525f4fd
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op\n WHERE completed_at IS NOT NULL\n AND completed_at < now() - make_interval(secs => $1)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Float8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3139ffa959123d9cbbf2d4858669b6de8a9df7a59cf0826fc2c1557f95982f48"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json b/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json
new file mode 100644
index 000000000000..372315eefe5d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE posthog_persondistinctid\n SET is_deleted = true, version = COALESCE(version, 0) + 1\n WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false\n RETURNING person_id, distinct_id, version as \"version!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "version!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc"
+}
diff --git a/rust/personhog-identity/.sqlx/query-360abbc4844a3656861cb3f1f9b716f88b618aba70dce5fa5d8bb05f3290651a.json b/rust/personhog-identity/.sqlx/query-360abbc4844a3656861cb3f1f9b716f88b618aba70dce5fa5d8bb05f3290651a.json
new file mode 100644
index 000000000000..91feee30cfcb
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-360abbc4844a3656861cb3f1f9b716f88b618aba70dce5fa5d8bb05f3290651a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op SET step = $3 WHERE op_id = $1 AND step = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "360abbc4844a3656861cb3f1f9b716f88b618aba70dce5fa5d8bb05f3290651a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json b/rust/personhog-identity/.sqlx/query-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json
new file mode 100644
index 000000000000..bf110aedfd96
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json
@@ -0,0 +1,15 @@
+{
+ "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.status = 'sealed'\n AND p.team_id = $2 AND p.id = lop.person_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-4aa59a46f66aef31f0ca7f4384fec8da471bc5948d6cae950ae013227fba4b3a.json b/rust/personhog-identity/.sqlx/query-4aa59a46f66aef31f0ca7f4384fec8da471bc5948d6cae950ae013227fba4b3a.json
new file mode 100644
index 000000000000..9d387bb906d8
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-4aa59a46f66aef31f0ca7f4384fec8da471bc5948d6cae950ae013227fba4b3a.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op\n SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL\n WHERE op_id = $1 AND step = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4aa59a46f66aef31f0ca7f4384fec8da471bc5948d6cae950ae013227fba4b3a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-5358edf9ca67bc42fb9692da3c73af78562e8de0e90709aad4934cdb88c8e6f3.json b/rust/personhog-identity/.sqlx/query-5358edf9ca67bc42fb9692da3c73af78562e8de0e90709aad4934cdb88c8e6f3.json
new file mode 100644
index 000000000000..27c4a5ec6a7f
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-5358edf9ca67bc42fb9692da3c73af78562e8de0e90709aad4934cdb88c8e6f3.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM posthog_cohortpeople WHERE person_id = ANY($1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5358edf9ca67bc42fb9692da3c73af78562e8de0e90709aad4934cdb88c8e6f3"
+}
diff --git a/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json b/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json
new file mode 100644
index 000000000000..751246ca3c31
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, uuid FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2) AND is_deleted = false\n ORDER BY id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uuid",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e"
+}
diff --git a/rust/personhog-identity/.sqlx/query-5bbcabb838ac3962a7f9f39f8086e37172d9d42f85f35040e65a58f1b7735982.json b/rust/personhog-identity/.sqlx/query-5bbcabb838ac3962a7f9f39f8086e37172d9d42f85f35040e65a58f1b7735982.json
new file mode 100644
index 000000000000..88e058de3fb1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-5bbcabb838ac3962a7f9f39f8086e37172d9d42f85f35040e65a58f1b7735982.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM posthog_featureflaghashkeyoverride WHERE team_id = $1 AND person_id = ANY($2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5bbcabb838ac3962a7f9f39f8086e37172d9d42f85f35040e65a58f1b7735982"
+}
diff --git a/rust/personhog-identity/.sqlx/query-7384ba223d7166ffde1e59fe6f565e866415007b9564e09b91ef09343e605b34.json b/rust/personhog-identity/.sqlx/query-7384ba223d7166ffde1e59fe6f565e866415007b9564e09b91ef09343e605b34.json
new file mode 100644
index 000000000000..51c6ccf76206
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-7384ba223d7166ffde1e59fe6f565e866415007b9564e09b91ef09343e605b34.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7384ba223d7166ffde1e59fe6f565e866415007b9564e09b91ef09343e605b34"
+}
diff --git a/rust/personhog-identity/.sqlx/query-867fbc06ae766c181011a8a95527f8396c8866c06f8f0a567dc1f1bf699abd0a.json b/rust/personhog-identity/.sqlx/query-867fbc06ae766c181011a8a95527f8396c8866c06f8f0a567dc1f1bf699abd0a.json
new file mode 100644
index 000000000000..9d7237de7a7e
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-867fbc06ae766c181011a8a95527f8396c8866c06f8f0a567dc1f1bf699abd0a.json
@@ -0,0 +1,18 @@
+{
+ "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, 'victim', $5\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"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "867fbc06ae766c181011a8a95527f8396c8866c06f8f0a567dc1f1bf699abd0a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-91ab82990658e82d4daaf03fe215e2a9558f83aeffe1ea18a0d82a16bd37e816.json b/rust/personhog-identity/.sqlx/query-91ab82990658e82d4daaf03fe215e2a9558f83aeffe1ea18a0d82a16bd37e816.json
new file mode 100644
index 000000000000..166f0e8b84b6
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-91ab82990658e82d4daaf03fe215e2a9558f83aeffe1ea18a0d82a16bd37e816.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT count(*) as \"count!\" FROM lifecycle_op_person\n WHERE op_id = $1 AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "91ab82990658e82d4daaf03fe215e2a9558f83aeffe1ea18a0d82a16bd37e816"
+}
diff --git a/rust/personhog-identity/.sqlx/query-95afd2d938db6c6053af6011ae04f7622a8c540b13e44574022568dcbc283fbc.json b/rust/personhog-identity/.sqlx/query-95afd2d938db6c6053af6011ae04f7622a8c540b13e44574022568dcbc283fbc.json
new file mode 100644
index 000000000000..fde4150c5c78
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-95afd2d938db6c6053af6011ae04f7622a8c540b13e44574022568dcbc283fbc.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": "95afd2d938db6c6053af6011ae04f7622a8c540b13e44574022568dcbc283fbc"
+}
diff --git a/rust/personhog-identity/.sqlx/query-9b92df4f0a2c7a80eaccf250d8324737b0a64d7f8809bf5a4aa8bae924b69605.json b/rust/personhog-identity/.sqlx/query-9b92df4f0a2c7a80eaccf250d8324737b0a64d7f8809bf5a4aa8bae924b69605.json
new file mode 100644
index 000000000000..c8244ad4fe8e
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-9b92df4f0a2c7a80eaccf250d8324737b0a64d7f8809bf5a4aa8bae924b69605.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (op_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int4",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9b92df4f0a2c7a80eaccf250d8324737b0a64d7f8809bf5a4aa8bae924b69605"
+}
diff --git a/rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.json b/rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.json
new file mode 100644
index 000000000000..99607b642919
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\", completed_at\n FROM lifecycle_op\n WHERE op_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "op_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "step",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "attempt",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 5,
+ "name": "request: Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "outcome: Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "a405d45d85f1d2f405205b42a7fab52c9ebd8421453af66d5c13c6fdd7adf87d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-a4e12b7721e50cb9d26c91de4ffdd37687e4b60c37159bd0b6f35b1210ed12a5.json b/rust/personhog-identity/.sqlx/query-a4e12b7721e50cb9d26c91de4ffdd37687e4b60c37159bd0b6f35b1210ed12a5.json
new file mode 100644
index 000000000000..58e8fe7099b1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a4e12b7721e50cb9d26c91de4ffdd37687e4b60c37159bd0b6f35b1210ed12a5.json
@@ -0,0 +1,16 @@
+{
+ "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 AND attempt = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Float8",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a4e12b7721e50cb9d26c91de4ffdd37687e4b60c37159bd0b6f35b1210ed12a5"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b4b6b473788270dd01cfc772b2885faeae60b225c63cb6329b2a17e8349275ca.json b/rust/personhog-identity/.sqlx/query-b4b6b473788270dd01cfc772b2885faeae60b225c63cb6329b2a17e8349275ca.json
new file mode 100644
index 000000000000..d5f62af68118
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b4b6b473788270dd01cfc772b2885faeae60b225c63cb6329b2a17e8349275ca.json
@@ -0,0 +1,26 @@
+{
+ "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, 'victim', $5\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\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",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b4b6b473788270dd01cfc772b2885faeae60b225c63cb6329b2a17e8349275ca"
+}
diff --git a/rust/personhog-identity/.sqlx/query-c17bc9977f44ae4790a0deb637076ec701a74f4b5f99a8d0476509226d930f96.json b/rust/personhog-identity/.sqlx/query-c17bc9977f44ae4790a0deb637076ec701a74f4b5f99a8d0476509226d930f96.json
new file mode 100644
index 000000000000..51d840fc22fc
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-c17bc9977f44ae4790a0deb637076ec701a74f4b5f99a8d0476509226d930f96.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "status",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "c17bc9977f44ae4790a0deb637076ec701a74f4b5f99a8d0476509226d930f96"
+}
diff --git a/rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.json b/rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.json
new file mode 100644
index 000000000000..c7831ac77a21
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a.json
@@ -0,0 +1,29 @@
+{
+ "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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "op_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Float8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "d67138afa1b5b102a19e113b20cefc09fcd3edce204fb6bd662f59f0e8e8ec4a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e30146cb33d6e652c0341094a6665c064de4a7e59511684d322965a7b996aea0.json b/rust/personhog-identity/.sqlx/query-e30146cb33d6e652c0341094a6665c064de4a7e59511684d322965a7b996aea0.json
new file mode 100644
index 000000000000..1758984d15cf
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e30146cb33d6e652c0341094a6665c064de4a7e59511684d322965a7b996aea0.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e30146cb33d6e652c0341094a6665c064de4a7e59511684d322965a7b996aea0"
+}
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
index 6dcfd6e1a2bd..9e3198fd851f 100644
--- a/rust/personhog-identity/Cargo.toml
+++ b/rust/personhog-identity/Cargo.toml
@@ -17,7 +17,10 @@ axum = { workspace = true }
chrono = { workspace = true }
envconfig = { workspace = true }
futures = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
sqlx = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index e2fd1a44abbc..33fc9f61f092 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -91,6 +91,40 @@ pub struct Config {
/// so the caller retries on another pod. 0 = disabled.
#[envconfig(default = "0")]
pub max_concurrent_requests: usize,
+
+ /// How long one claim of a lifecycle op lasts before another instance
+ /// may steal it (seconds).
+ #[envconfig(default = "15")]
+ pub lifecycle_lease_secs: u64,
+
+ /// How long a DeletePersons call keeps driving (or waiting on another
+ /// driver's lease) before returning UNAVAILABLE (seconds).
+ #[envconfig(default = "30")]
+ pub lifecycle_execute_timeout_secs: u64,
+
+ /// How often a non-owning driver re-checks a leased op for completion (ms).
+ #[envconfig(default = "250")]
+ pub lifecycle_poll_interval_ms: u64,
+
+ /// Warn when an op's attempt counter reaches this value.
+ #[envconfig(default = "5")]
+ pub lifecycle_attempt_alert_threshold: i32,
+
+ /// Run the background sweeper + GC loop for abandoned lifecycle ops.
+ /// One sweeper per fleet is enough; every instance running it is also
+ /// fine (the lease arbitrates), so this is a plain per-pod toggle.
+ #[envconfig(default = "false")]
+ pub lifecycle_sweeper_enabled: bool,
+
+ /// Interval between sweeper passes (seconds).
+ #[envconfig(default = "30")]
+ pub lifecycle_sweep_interval_secs: u64,
+
+ /// How long completed op rows are retained for op_id idempotency before
+ /// GC (hours). The durable deletion shield is the person tombstone row,
+ /// not the op row.
+ #[envconfig(default = "24")]
+ pub lifecycle_op_retention_hours: u64,
}
impl Config {
@@ -149,4 +183,21 @@ impl Config {
Some(Duration::from_secs(self.grpc_max_connection_age_secs))
}
}
+
+ pub fn lifecycle_engine_config(&self) -> crate::lifecycle::engine::EngineConfig {
+ crate::lifecycle::engine::EngineConfig {
+ lease: Duration::from_secs(self.lifecycle_lease_secs),
+ execute_timeout: Duration::from_secs(self.lifecycle_execute_timeout_secs),
+ poll_interval: Duration::from_millis(self.lifecycle_poll_interval_ms),
+ attempt_alert_threshold: self.lifecycle_attempt_alert_threshold,
+ }
+ }
+
+ pub fn lifecycle_sweep_interval(&self) -> Duration {
+ Duration::from_secs(self.lifecycle_sweep_interval_secs)
+ }
+
+ pub fn lifecycle_op_retention(&self) -> Duration {
+ Duration::from_secs(self.lifecycle_op_retention_hours * 3600)
+ }
}
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
new file mode 100644
index 000000000000..30ba41995c29
--- /dev/null
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -0,0 +1,542 @@
+//! The delete saga's step handlers: `started → marked → sealed → unmapped →
+//! completed`, with `aborted` reachable only from `started` (before anything
+//! was mutated). Each step is one transaction that commits its work together
+//! with the step advance — see the engine's correctness model.
+//!
+//! Pre-leader-fencing mode: the leader's `FencePerson` / `ReleaseFence` RPCs
+//! have not landed yet, so this driver runs the saga without a fence.
+//! Sealing reads the person's version from Postgres and adds
+//! [`SEAL_VERSION_MARGIN`] (the same margin the legacy delete path uses) so
+//! the death version outranks any write that lands between the seal and the
+//! tombstone. The unmapped transaction writes the person tombstone directly
+//! — once the leader produces death documents and the writer projects them
+//! (RFC stages 6–7), that direct write becomes the fence-gated fallback and
+//! the leader/writer path takes over ClickHouse emission. Until then the
+//! distinct-id rows tombstoned by an op are recorded in each victim row's
+//! `moved` column, so nothing needed for later emission is lost.
+
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sqlx::postgres::PgPool;
+use uuid::Uuid;
+
+use crate::lifecycle::engine::{
+ advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
+ STEP_COMPLETED,
+};
+
+pub const OP_TYPE_DELETE: &str = "delete";
+
+/// The delete saga's non-terminal steps, in order. Stored as text in
+/// `lifecycle_op.step` (the engine is generic over op types, so its API is
+/// stringly-typed); parsed back exactly once, at step dispatch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DeleteStep {
+ Started,
+ Marked,
+ Sealed,
+ Unmapped,
+}
+
+impl DeleteStep {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ DeleteStep::Started => "started",
+ DeleteStep::Marked => "marked",
+ DeleteStep::Sealed => "sealed",
+ DeleteStep::Unmapped => "unmapped",
+ }
+ }
+
+ fn parse(step: &str) -> Option<Self> {
+ match step {
+ "started" => Some(DeleteStep::Started),
+ "marked" => Some(DeleteStep::Marked),
+ "sealed" => Some(DeleteStep::Sealed),
+ "unmapped" => Some(DeleteStep::Unmapped),
+ _ => None,
+ }
+ }
+}
+
+/// Added to the person's Postgres version at seal time. Without a fence a
+/// concurrent write can still bump the version between the seal and the
+/// tombstone; the margin parks the death version far above anything such a
+/// write can reach, exactly like the legacy delete path's +100. Once sealing
+/// goes through `FencePerson` no write can follow the seal and the margin
+/// can drop to zero.
+pub const SEAL_VERSION_MARGIN: i64 = 100;
+
+/// The frozen `lifecycle_op.request` payload for a delete op.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DeleteRequest {
+ pub person_ids: Vec<i64>,
+}
+
+/// The recorded `lifecycle_op.outcome` payload: one entry per requested
+/// person id, in request order.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DeleteOutcome {
+ pub results: Vec<DeletePersonRecord>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DeletePersonRecord {
+ pub person_id: i64,
+ pub outcome: String,
+}
+
+pub const OUTCOME_DELETED: &str = "deleted";
+pub const OUTCOME_SKIPPED_CONFLICT: &str = "skipped_conflict";
+pub const OUTCOME_NOT_FOUND: &str = "not_found";
+
+/// Per-person row statuses this driver writes.
+const STATUS_MARKED: &str = "marked";
+const STATUS_SEALED: &str = "sealed";
+const STATUS_DELETED: &str = "deleted";
+const STATUS_SKIPPED_CONFLICT: &str = "skipped_conflict";
+
+const STEPS_TOTAL: &str = "personhog_lifecycle_delete_steps_total";
+const OUTCOMES_TOTAL: &str = "personhog_lifecycle_delete_outcomes_total";
+
+/// Call after a step's transaction commits — a commit means the step CAS was
+/// won, so each transition is counted exactly once across concurrent drivers.
+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,
+ );
+}
+
+/// Call after the terminal transaction commits: one count per person,
+/// labeled with its recorded outcome.
+fn record_outcomes(outcome: &Value) {
+ let Ok(parsed) = serde_json::from_value::<DeleteOutcome>(outcome.clone()) else {
+ return;
+ };
+ for label in [OUTCOME_DELETED, OUTCOME_SKIPPED_CONFLICT, OUTCOME_NOT_FOUND] {
+ 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,
+ );
+ }
+ }
+}
+
+pub struct DeleteDriver;
+
+#[async_trait]
+impl OpDriver for DeleteDriver {
+ fn op_type(&self) -> &'static str {
+ OP_TYPE_DELETE
+ }
+
+ fn initial_step(&self) -> &'static str {
+ DeleteStep::Started.as_str()
+ }
+
+ async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ let step = DeleteStep::parse(&op.step).ok_or_else(|| {
+ SagaError::CorruptState(format!(
+ "delete op {} is on unknown step '{}'",
+ op.op_id, op.step
+ ))
+ })?;
+ match step {
+ DeleteStep::Started => mark(pool, op).await,
+ DeleteStep::Marked => seal(pool, op).await,
+ DeleteStep::Sealed => unmap(pool, op).await,
+ DeleteStep::Unmapped => complete(pool, op).await,
+ }
+ }
+}
+
+fn parse_request(op: &OpRow) -> Result<DeleteRequest, SagaError> {
+ serde_json::from_value(op.request.clone()).map_err(|e| {
+ SagaError::CorruptState(format!(
+ "delete op {} has a malformed request: {e}",
+ op.op_id
+ ))
+ })
+}
+
+/// `started → marked`: claim the victims. One row per live victim in
+/// `lifecycle_op_person`; the partial unique mark index makes a conflicting
+/// insert a no-op, and a victim we could not claim is recorded as
+/// `skipped_conflict`. Requested ids with no live person row get no row at
+/// all — they surface as `not_found` in the outcome. If nothing was claimed
+/// the op aborts here, before anything was mutated.
+async fn mark(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?;
+
+ // Rows from a previous attempt of this op (crash between the insert and
+ // the advance): whatever they claimed stays claimed.
+ let existing: Vec<i64> = sqlx::query_scalar!(
+ "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1",
+ op.op_id
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+
+ // Sorted + deduped by the mark's conflict key so concurrent ops touching
+ // the same persons take row locks in the same order.
+ let mut to_claim: Vec<i64> = request
+ .person_ids
+ .iter()
+ .copied()
+ .filter(|id| !existing.contains(id))
+ .collect();
+ to_claim.sort_unstable();
+ to_claim.dedup();
+
+ let live = sqlx::query!(
+ r#"
+ SELECT id, uuid FROM posthog_person
+ WHERE team_id = $1 AND id = ANY($2) AND is_deleted = false
+ ORDER BY id
+ "#,
+ team_id,
+ &to_claim,
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+ let live_ids: Vec<i64> = live.iter().map(|p| p.id).collect();
+ let live_uuids: Vec<Uuid> = live.iter().map(|p| p.uuid).collect();
+
+ // The mark: inserting the row is claiming the person; a unique violation
+ // on the partial mark index IS the conflict with another live op.
+ let marked: Vec<i64> = sqlx::query_scalar!(
+ 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, 'victim', $5
+ FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
+ ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING
+ RETURNING person_id
+ "#,
+ op.op_id,
+ team_id,
+ &live_ids,
+ &live_uuids,
+ STATUS_MARKED,
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+
+ // Victims 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 to the insert.
+ let conflicted_ids: Vec<i64> = live_ids
+ .iter()
+ .copied()
+ .filter(|id| !marked.contains(id))
+ .collect();
+ let conflicted_uuids: Vec<Uuid> = live
+ .iter()
+ .filter(|p| conflicted_ids.contains(&p.id))
+ .map(|p| p.uuid)
+ .collect();
+ if !conflicted_ids.is_empty() {
+ 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, 'victim', $5
+ 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,
+ STATUS_SKIPPED_CONFLICT,
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ let claims: i64 = sqlx::query_scalar!(
+ r#"
+ SELECT count(*) as "count!" FROM lifecycle_op_person
+ WHERE op_id = $1 AND status IN ('marked', 'sealed')
+ "#,
+ op.op_id
+ )
+ .fetch_one(&mut *tx)
+ .await?;
+
+ let mut abort_outcome: Option<Value> = None;
+ let advanced = if claims == 0 {
+ // Every requested person was conflicted or missing: nothing was (or
+ // will be) mutated, so the op ends here as aborted.
+ let outcome = build_outcome(&mut tx, op.op_id, &request.person_ids).await?;
+ let advanced = complete_op_in_tx(
+ &mut tx,
+ op.op_id,
+ DeleteStep::Started.as_str(),
+ STEP_ABORTED,
+ &outcome,
+ )
+ .await?;
+ abort_outcome = Some(outcome);
+ advanced
+ } else {
+ advance_step_in_tx(
+ &mut tx,
+ op.op_id,
+ DeleteStep::Started.as_str(),
+ DeleteStep::Marked.as_str(),
+ )
+ .await?
+ };
+ if !advanced {
+ tx.rollback().await?;
+ return Ok(());
+ }
+ tx.commit().await?;
+ match abort_outcome {
+ Some(outcome) => {
+ record_transition(DeleteStep::Started.as_str(), STEP_ABORTED);
+ record_outcomes(&outcome);
+ }
+ None => record_transition(DeleteStep::Started.as_str(), DeleteStep::Marked.as_str()),
+ }
+ Ok(())
+}
+
+/// `marked → sealed`: freeze each victim's final version. Pre-fence this
+/// reads the version from Postgres and adds [`SEAL_VERSION_MARGIN`]; with
+/// leader fencing (RFC stage 6) this becomes a `FencePerson` call per victim
+/// and the sealed version is exact.
+async fn seal(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ let team_id = op.team_id as i32;
+ let mut tx = pool.begin().await?;
+
+ sqlx::query!(
+ r#"
+ UPDATE lifecycle_op_person lop
+ SET status = $3, sealed = jsonb_build_object('version', COALESCE(p.version, 0) + $4)
+ FROM posthog_person p
+ WHERE lop.op_id = $1 AND lop.status IN ('marked', 'sealed')
+ AND p.team_id = $2 AND p.id = lop.person_id
+ "#,
+ op.op_id,
+ team_id,
+ STATUS_SEALED,
+ SEAL_VERSION_MARGIN,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ if !advance_step_in_tx(
+ &mut tx,
+ op.op_id,
+ DeleteStep::Marked.as_str(),
+ DeleteStep::Sealed.as_str(),
+ )
+ .await?
+ {
+ tx.rollback().await?;
+ return Ok(());
+ }
+ tx.commit().await?;
+ record_transition(DeleteStep::Marked.as_str(), DeleteStep::Sealed.as_str());
+ Ok(())
+}
+
+/// `sealed → unmapped`: the destroying transaction. Tombstone the victims'
+/// distinct-id rows (recording each new version in `moved`, in the same
+/// commit that bumps them), clear cohort membership and feature-flag
+/// hash-key overrides, and tombstone the person rows themselves — properties
+/// scrubbed (the GDPR erasure; the retained uuid is not PII), version parked
+/// at sealed + 1 so the tombstone outranks every write the old incarnation
+/// ever produced. Revival (a later create on the same key) upserts above
+/// this version.
+async fn unmap(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ let team_id = op.team_id as i32;
+ let mut tx = pool.begin().await?;
+
+ let mut victims: Vec<i64> = sqlx::query_scalar!(
+ r#"
+ SELECT person_id FROM lifecycle_op_person
+ WHERE op_id = $1 AND status = 'sealed'
+ "#,
+ op.op_id
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+ victims.sort_unstable();
+
+ let tombstoned = sqlx::query!(
+ r#"
+ UPDATE posthog_persondistinctid
+ SET is_deleted = true, version = COALESCE(version, 0) + 1
+ WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false
+ RETURNING person_id, distinct_id, version as "version!"
+ "#,
+ team_id,
+ &victims,
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+
+ // Record the tombstoned mappings per victim in the same commit — this is
+ // what a later ClickHouse emission (or an operator) reads back.
+ let mut moved_ids: Vec<i64> = Vec::new();
+ let mut moved_json: Vec<Value> = Vec::new();
+ for victim in &victims {
+ let rows: Vec<Value> = tombstoned
+ .iter()
+ .filter(|r| r.person_id == *victim)
+ .map(|r| serde_json::json!({"distinct_id": r.distinct_id, "version": r.version}))
+ .collect();
+ if !rows.is_empty() {
+ moved_ids.push(*victim);
+ moved_json.push(Value::Array(rows));
+ }
+ }
+ if !moved_ids.is_empty() {
+ 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?;
+ }
+
+ sqlx::query!(
+ "DELETE FROM posthog_cohortpeople WHERE person_id = ANY($1)",
+ &victims
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ sqlx::query!(
+ "DELETE FROM posthog_featureflaghashkeyoverride WHERE team_id = $1 AND person_id = ANY($2)",
+ team_id,
+ &victims
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ 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.status = 'sealed'
+ AND p.team_id = $2 AND p.id = lop.person_id
+ "#,
+ op.op_id,
+ team_id,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ if !advance_step_in_tx(
+ &mut tx,
+ op.op_id,
+ DeleteStep::Sealed.as_str(),
+ DeleteStep::Unmapped.as_str(),
+ )
+ .await?
+ {
+ tx.rollback().await?;
+ return Ok(());
+ }
+ tx.commit().await?;
+ record_transition(DeleteStep::Sealed.as_str(), DeleteStep::Unmapped.as_str());
+ Ok(())
+}
+
+/// `unmapped → completed`: settle the per-person rows to `deleted` (which
+/// releases their marks), record the outcome, and stamp completion. With
+/// leader fencing (RFC stage 6) the per-victim `ReleaseFence(committed)`
+/// calls — the leader producing each death document — happen before this
+/// transaction.
+async fn complete(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ let request = parse_request(op)?;
+ let mut tx = pool.begin().await?;
+
+ sqlx::query!(
+ "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
+ op.op_id,
+ STATUS_DELETED,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ let outcome = build_outcome(&mut tx, op.op_id, &request.person_ids).await?;
+ if !complete_op_in_tx(
+ &mut tx,
+ op.op_id,
+ DeleteStep::Unmapped.as_str(),
+ STEP_COMPLETED,
+ &outcome,
+ )
+ .await?
+ {
+ tx.rollback().await?;
+ return Ok(());
+ }
+ tx.commit().await?;
+ record_transition(DeleteStep::Unmapped.as_str(), STEP_COMPLETED);
+ record_outcomes(&outcome);
+ Ok(())
+}
+
+/// 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`.
+async fn build_outcome(
+ tx: &mut Tx<'_>,
+ op_id: Uuid,
+ requested: &[i64],
+) -> Result<Value, SagaError> {
+ let rows = sqlx::query!(
+ "SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1",
+ op_id
+ )
+ .fetch_all(&mut **tx)
+ .await?;
+
+ let results = requested
+ .iter()
+ .map(|person_id| {
+ let outcome = match rows.iter().find(|r| r.person_id == *person_id) {
+ Some(row) if row.status == STATUS_DELETED => OUTCOME_DELETED,
+ Some(row) if row.status == STATUS_SKIPPED_CONFLICT => OUTCOME_SKIPPED_CONFLICT,
+ _ => OUTCOME_NOT_FOUND,
+ };
+ DeletePersonRecord {
+ person_id: *person_id,
+ outcome: outcome.to_string(),
+ }
+ })
+ .collect();
+
+ serde_json::to_value(DeleteOutcome { results })
+ .map_err(|e| SagaError::CorruptState(format!("failed to serialize delete outcome: {e}")))
+}
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
new file mode 100644
index 000000000000..3ab214830722
--- /dev/null
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -0,0 +1,430 @@
+//! The saga engine: op persistence, lease, and the drive loop. Generic over
+//! op type — an [`OpDriver`] supplies the step handlers, the engine supplies
+//! everything an op type shares: create-or-attach by op_id, lease
+//! claim/renew/steal by `lease_expires_at`, the run loop, the sweeper scan,
+//! and GC. Delete registers one driver; merge later registers another
+//! without engine changes.
+//!
+//! Correctness model: the lease is a throttle, not a lock — an expired lease
+//! can be stolen while the old driver is still running, so two drivers may
+//! run the same step concurrently. Steps stay correct anyway because every
+//! step commits its work and its step advance (a compare-and-swap on
+//! `lifecycle_op.step`) in one transaction: the loser's CAS fails, its
+//! transaction rolls back, and its work evaporates. A saved step therefore
+//! always means "everything up to and including this step really happened,
+//! exactly once". A claim's bumped `attempt` doubles as a fencing token:
+//! renew/release match only while `attempt` is unchanged, so a displaced
+//! driver cannot extend or clear a stealer's lease.
+
+use std::time::Duration;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use serde_json::Value;
+use sqlx::postgres::PgPool;
+use tonic::Status;
+use uuid::Uuid;
+
+/// Terminal step: the op ran to the end.
+pub const STEP_COMPLETED: &str = "completed";
+/// Terminal step: the op backed out before mutating anything.
+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";
+
+/// How many abandoned ops one sweep pass will pick up.
+const SWEEP_BATCH_SIZE: i64 = 100;
+
+pub type Tx<'a> = sqlx::Transaction<'a, sqlx::Postgres>;
+
+#[derive(Debug, thiserror::Error)]
+pub enum SagaError {
+ #[error("database error: {0}")]
+ Db(#[from] sqlx::Error),
+ /// The op_id already exists with a different op type, team, or request.
+ #[error("op_id reused with a different request: {0}")]
+ RequestMismatch(String),
+ /// Another instance held the lease past our deadline.
+ #[error("another instance is driving this operation")]
+ Busy,
+ /// State this engine or driver cannot interpret.
+ #[error("corrupt saga state: {0}")]
+ CorruptState(String),
+}
+
+impl From<SagaError> for Status {
+ fn from(err: SagaError) -> Status {
+ match err {
+ SagaError::Db(e) => Status::internal(format!("database error: {e}")),
+ SagaError::RequestMismatch(msg) => Status::failed_precondition(msg),
+ SagaError::Busy => Status::unavailable(
+ "another instance is driving this operation; retry with the same op_id",
+ ),
+ SagaError::CorruptState(msg) => Status::internal(msg),
+ }
+ }
+}
+
+/// One row of `lifecycle_op`: the complete checkpoint of an operation.
+#[derive(Debug, Clone)]
+pub struct OpRow {
+ pub op_id: Uuid,
+ pub op_type: String,
+ pub team_id: i64,
+ pub step: String,
+ pub attempt: i32,
+ pub request: Value,
+ pub outcome: Option<Value>,
+ pub completed_at: Option<DateTime<Utc>>,
+}
+
+/// Step handlers for one op type. The engine calls [`run_step`] with the
+/// current row until the row reaches a terminal step.
+///
+/// Contract for `run_step`: do the current step's work and, in the same
+/// transaction as that work, advance `lifecycle_op.step` with
+/// [`advance_step_in_tx`] (or finish with [`complete_op_in_tx`]). If the
+/// advance reports the step already moved, roll the transaction back and
+/// return Ok — the engine reloads and continues from the fresh row. Every
+/// step must be safe to repeat.
+///
+/// [`run_step`]: OpDriver::run_step
+#[async_trait]
+pub trait OpDriver: Send + Sync {
+ fn op_type(&self) -> &'static str;
+ /// The step a freshly created op row starts on.
+ fn initial_step(&self) -> &'static str;
+ async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError>;
+}
+
+#[derive(Clone, Debug)]
+pub struct EngineConfig {
+ /// How long one claim of an op lasts before another instance may steal it.
+ pub lease: Duration,
+ /// How long `execute`/`resume` keeps driving (or waiting on another
+ /// driver's lease) before giving up with `Busy`.
+ pub execute_timeout: Duration,
+ /// How often a non-owning driver re-checks a leased op for completion.
+ pub poll_interval: Duration,
+ /// Log a warning when an op's attempt counter reaches this value.
+ pub attempt_alert_threshold: i32,
+}
+
+pub struct Engine {
+ pool: PgPool,
+ config: EngineConfig,
+}
+
+impl Engine {
+ pub fn new(pool: PgPool, config: EngineConfig) -> Self {
+ Self { pool, config }
+ }
+
+ pub fn pool(&self) -> &PgPool {
+ &self.pool
+ }
+
+ /// Create the op if it is new, then drive it to a terminal step and
+ /// return the terminal row. A retry with the same op_id attaches to the
+ /// existing op: completed → returns the recorded row without running
+ /// anything; live → waits for or steals the lease and resumes from the
+ /// saved step.
+ pub async fn execute(
+ &self,
+ driver: &dyn OpDriver,
+ op_id: Uuid,
+ team_id: i64,
+ request: &Value,
+ ) -> Result<OpRow, SagaError> {
+ sqlx::query!(
+ r#"
+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (op_id) DO NOTHING
+ "#,
+ op_id,
+ driver.op_type(),
+ team_id as i32,
+ driver.initial_step(),
+ request,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ let row = self.load(op_id).await?.ok_or_else(|| {
+ SagaError::CorruptState(format!("op {op_id} vanished right after create-or-attach"))
+ })?;
+ if row.op_type != driver.op_type() || row.team_id != team_id || row.request != *request {
+ return Err(SagaError::RequestMismatch(format!(
+ "op {op_id} already exists with a different request"
+ )));
+ }
+
+ self.drive(driver, op_id, true).await
+ }
+
+ /// Drive an existing op (sweeper entry point — no create, no request
+ /// verification). Does not wait on another driver's live lease: to the
+ /// sweeper a live lease means "not abandoned", so this bails with `Busy`
+ /// instead of polling out the execute timeout.
+ pub async fn resume(&self, driver: &dyn OpDriver, op_id: Uuid) -> Result<OpRow, SagaError> {
+ self.drive(driver, op_id, false).await
+ }
+
+ async fn drive(
+ &self,
+ driver: &dyn OpDriver,
+ op_id: Uuid,
+ wait_for_lease: bool,
+ ) -> Result<OpRow, SagaError> {
+ let deadline = tokio::time::Instant::now() + self.config.execute_timeout;
+ // The attempt number returned by our claim, used as a fencing token:
+ // renew/release only touch the lease while `attempt` still matches,
+ // so a driver whose lease was stolen (the stealer bumped `attempt`)
+ // cannot extend or clear the stealer's lease.
+ let mut claim_attempt: Option<i32> = None;
+
+ loop {
+ let Some(row) = self.load(op_id).await? else {
+ return Err(SagaError::CorruptState(format!(
+ "op {op_id} vanished while being driven"
+ )));
+ };
+ if row.completed_at.is_some() {
+ if claim_attempt.is_some() {
+ // We drove it over the line (vs attaching to an op that
+ // was already done).
+ common_metrics::inc(
+ OPS_COMPLETED_TOTAL,
+ &[
+ ("op_type".to_string(), row.op_type.clone()),
+ ("final_step".to_string(), row.step.clone()),
+ ],
+ 1,
+ );
+ }
+ return Ok(row);
+ }
+ if tokio::time::Instant::now() >= deadline {
+ if let Some(attempt) = claim_attempt {
+ self.release_lease(op_id, attempt).await.ok();
+ }
+ return Err(SagaError::Busy);
+ }
+
+ match claim_attempt {
+ Some(attempt) => {
+ if !self.renew_lease(op_id, attempt).await? {
+ // Another driver stole the lease; go back to
+ // claiming instead of running a step we would lose.
+ claim_attempt = None;
+ continue;
+ }
+ }
+ None => match self.try_claim(op_id).await? {
+ Some(attempt) => {
+ claim_attempt = Some(attempt);
+ if attempt >= self.config.attempt_alert_threshold {
+ tracing::warn!(
+ op_id = %op_id,
+ op_type = %row.op_type,
+ step = %row.step,
+ attempt,
+ "lifecycle op has been claimed unusually often; it may be stuck"
+ );
+ }
+ }
+ None => {
+ if !wait_for_lease {
+ return Err(SagaError::Busy);
+ }
+ // Someone else holds the lease; wait for them to
+ // finish or for the lease to lapse.
+ tokio::time::sleep(self.config.poll_interval).await;
+ continue;
+ }
+ },
+ }
+
+ if let Err(err) = driver.run_step(&self.pool, &row).await {
+ // 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();
+ }
+ return Err(err);
+ }
+ }
+ }
+
+ async fn load(&self, op_id: Uuid) -> Result<Option<OpRow>, sqlx::Error> {
+ sqlx::query_as!(
+ OpRow,
+ r#"
+ SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,
+ request as "request: Value", outcome as "outcome: Value", completed_at
+ FROM lifecycle_op
+ WHERE op_id = $1
+ "#,
+ op_id
+ )
+ .fetch_optional(&self.pool)
+ .await
+ }
+
+ /// 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> {
+ sqlx::query_scalar!(
+ r#"
+ UPDATE lifecycle_op
+ SET lease_expires_at = now() + make_interval(secs => $2),
+ attempt = attempt + 1
+ WHERE op_id = $1 AND completed_at IS NULL
+ AND (lease_expires_at IS NULL OR lease_expires_at < now())
+ RETURNING attempt
+ "#,
+ op_id,
+ self.config.lease.as_secs_f64(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ }
+
+ /// 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> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE lifecycle_op
+ SET lease_expires_at = now() + make_interval(secs => $2)
+ WHERE op_id = $1 AND completed_at IS NULL AND attempt = $3
+ "#,
+ op_id,
+ self.config.lease.as_secs_f64(),
+ attempt,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn release_lease(&self, op_id: Uuid, attempt: i32) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ "UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
+ op_id,
+ attempt,
+ )
+ .execute(&self.pool)
+ .await?;
+ 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.
+ pub async fn sweep(&self, drivers: &[&dyn OpDriver]) -> Result<u32, SagaError> {
+ let abandoned = sqlx::query!(
+ r#"
+ SELECT op_id, op_type
+ FROM lifecycle_op
+ WHERE completed_at IS NULL
+ AND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))
+ OR lease_expires_at < now())
+ ORDER BY created_at
+ LIMIT $2
+ "#,
+ self.config.lease.as_secs_f64(),
+ SWEEP_BATCH_SIZE,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ let mut resumed = 0u32;
+ for op in abandoned {
+ let Some(driver) = drivers.iter().find(|d| d.op_type() == op.op_type) else {
+ tracing::error!(op_id = %op.op_id, op_type = %op.op_type,
+ "sweeper found an op with no registered driver");
+ continue;
+ };
+ match self.resume(*driver, op.op_id).await {
+ Ok(_) => {
+ 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.
+ Err(SagaError::Busy) => {}
+ Err(err) => {
+ tracing::warn!(op_id = %op.op_id, error = %err,
+ "sweeper failed to resume op; will retry next pass");
+ }
+ }
+ }
+ Ok(resumed)
+ }
+
+ /// Delete completed op rows past retention (per-person rows cascade).
+ /// The retention window exists only for op_id idempotency — the durable
+ /// deletion shield is the person tombstone row, not the op row.
+ pub async fn gc(&self, retention: Duration) -> Result<u64, SagaError> {
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM lifecycle_op
+ WHERE completed_at IS NOT NULL
+ AND completed_at < now() - make_interval(secs => $1)
+ "#,
+ retention.as_secs_f64(),
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(result.rows_affected())
+ }
+}
+
+/// Compare-and-swap the op's step inside the step's own transaction, so the
+/// work and the advance commit together. Returns false when the row is no
+/// longer on `from` — another driver already advanced it; the caller must
+/// roll back its transaction and let the engine reload.
+pub async fn advance_step_in_tx(
+ tx: &mut Tx<'_>,
+ op_id: Uuid,
+ from: &str,
+ to: &str,
+) -> Result<bool, sqlx::Error> {
+ let result = sqlx::query!(
+ "UPDATE lifecycle_op SET step = $3 WHERE op_id = $1 AND step = $2",
+ op_id,
+ from,
+ to
+ )
+ .execute(&mut **tx)
+ .await?;
+ Ok(result.rows_affected() == 1)
+}
+
+/// Terminal flavor of [`advance_step_in_tx`]: record the outcome, stamp
+/// `completed_at`, and drop the lease in the same compare-and-swap.
+pub async fn complete_op_in_tx(
+ tx: &mut Tx<'_>,
+ op_id: Uuid,
+ from: &str,
+ final_step: &str,
+ outcome: &Value,
+) -> Result<bool, sqlx::Error> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE lifecycle_op
+ SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL
+ WHERE op_id = $1 AND step = $2
+ "#,
+ op_id,
+ from,
+ final_step,
+ outcome,
+ )
+ .execute(&mut **tx)
+ .await?;
+ Ok(result.rows_affected() == 1)
+}
diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rs
index 6f118d5cf216..2c7341af9739 100644
--- a/rust/personhog-identity/src/lifecycle/mod.rs
+++ b/rust/personhog-identity/src/lifecycle/mod.rs
@@ -3,29 +3,84 @@
//! the persons primary. Self-contained on purpose — no imports from the
//! get-or-create side; anything shared belongs in personhog-common.
//!
-//! This module currently carries the service surface and request validation
-//! only. The saga engine (op persistence, lease, step advance, sweeper, GC)
-//! and the delete step handlers land next; until then DeletePersons validates
-//! and returns UNIMPLEMENTED.
+//! The [`engine`] carries everything op types share (op persistence, lease,
+//! drive loop, sweeper, GC); [`delete`] carries the delete saga's step
+//! handlers. The service here is dispatch-only: validate, hand the request
+//! to the engine, and translate the recorded outcome back to the proto
+//! contract.
+pub mod delete;
+pub mod engine;
pub mod validation;
+use std::sync::Arc;
+
use tonic::{Request, Response, Status};
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
-use personhog_proto::personhog::lifecycle::v1::{DeletePersonsRequest, DeletePersonsResponse};
+use personhog_proto::personhog::lifecycle::v1::{
+ DeletePersonOutcome, DeletePersonResult, DeletePersonsRequest, DeletePersonsResponse,
+};
+use crate::lifecycle::delete::{
+ DeleteDriver, DeleteOutcome, OUTCOME_DELETED, OUTCOME_NOT_FOUND, OUTCOME_SKIPPED_CONFLICT,
+};
+use crate::lifecycle::engine::{Engine, OpRow, SagaError};
use crate::lifecycle::validation::validate_delete_persons;
-#[derive(Default)]
-pub struct PersonHogLifecycleService {}
+pub struct PersonHogLifecycleService {
+ engine: Arc<Engine>,
+ delete_driver: DeleteDriver,
+}
impl PersonHogLifecycleService {
- pub fn new() -> Self {
- Self {}
+ pub fn new(engine: Arc<Engine>) -> Self {
+ Self {
+ engine,
+ delete_driver: DeleteDriver,
+ }
}
}
+/// Translate a terminal op row's recorded outcome into the proto response.
+/// The recorded outcome is the single source of truth — a retried call gets
+/// byte-for-byte the same answer the original run recorded.
+// tonic Status is a large Err variant; boxing here would diverge from the
+// tonic handler signatures this feeds into.
+#[allow(clippy::result_large_err)]
+fn delete_response(row: &OpRow) -> Result<DeletePersonsResponse, Status> {
+ let Some(outcome) = &row.outcome else {
+ return Err(Status::internal(format!(
+ "op {} is terminal but has no recorded outcome",
+ row.op_id
+ )));
+ };
+ let outcome: DeleteOutcome = serde_json::from_value(outcome.clone())
+ .map_err(|e| Status::internal(format!("op {} outcome is malformed: {e}", row.op_id)))?;
+
+ let results = outcome
+ .results
+ .into_iter()
+ .map(|record| {
+ let outcome = match record.outcome.as_str() {
+ OUTCOME_DELETED => DeletePersonOutcome::Deleted,
+ OUTCOME_SKIPPED_CONFLICT => DeletePersonOutcome::SkippedConflict,
+ OUTCOME_NOT_FOUND => DeletePersonOutcome::NotFound,
+ _ => DeletePersonOutcome::Unspecified,
+ };
+ DeletePersonResult {
+ person_id: record.person_id,
+ outcome: outcome.into(),
+ }
+ })
+ .collect();
+
+ Ok(DeletePersonsResponse {
+ op_id: row.op_id.to_string(),
+ results,
+ })
+}
+
#[tonic::async_trait]
impl PersonHogLifecycle for PersonHogLifecycleService {
async fn delete_persons(
@@ -33,10 +88,24 @@ impl PersonHogLifecycle for PersonHogLifecycleService {
request: Request<DeletePersonsRequest>,
) -> Result<Response<DeletePersonsResponse>, Status> {
let request = request.into_inner();
- validate_delete_persons(&request)?;
+ let op_id = validate_delete_persons(&request)?;
+
+ let frozen = serde_json::to_value(delete::DeleteRequest {
+ person_ids: request.person_ids,
+ })
+ .map_err(|e| Status::internal(format!("failed to freeze request: {e}")))?;
+
+ let row = self
+ .engine
+ .execute(&self.delete_driver, op_id, request.team_id, &frozen)
+ .await
+ .map_err(|err| {
+ if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {
+ tracing::error!(op_id = %op_id, error = %err, "DeletePersons failed");
+ }
+ Status::from(err)
+ })?;
- Err(Status::unimplemented(
- "DeletePersons is not enabled yet: the delete saga engine has not landed",
- ))
+ Ok(Response::new(delete_response(&row)?))
}
}
diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rs
index 0f1f8bcd982e..ff4839480d0f 100644
--- a/rust/personhog-identity/src/lifecycle/validation.rs
+++ b/rust/personhog-identity/src/lifecycle/validation.rs
@@ -10,7 +10,8 @@ pub const MAX_DELETE_BATCH_SIZE: usize = 250;
// tonic Status is a large Err variant; boxing here would diverge from the
// tonic handler signatures these feed into.
#[allow(clippy::result_large_err)]
-pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<(), Status> {
+/// Validates the request and returns the parsed op_id.
+pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<Uuid, Status> {
// The persons DB stores team_id as int4 and the storage layer narrows
// with `as i32` — an unchecked value above i32::MAX would wrap and read
// or write another tenant's rows.
@@ -33,8 +34,6 @@ pub fn validate_delete_persons(request: &DeletePersonsRequest) -> Result<(), Sta
"person_ids must be positive integers",
));
}
- if Uuid::parse_str(&request.op_id).is_err() {
- return Err(Status::invalid_argument("op_id must be a valid UUID"));
- }
- Ok(())
+ Uuid::parse_str(&request.op_id)
+ .map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))
}
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 4996eb424385..b33df02c7870 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -20,6 +20,8 @@ use tracing_subscriber::EnvFilter;
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::PersonHogLifecycleService;
use personhog_identity::service::PersonHogIdentityService;
use personhog_identity::storage::postgres::PostgresIdentityStorage;
@@ -78,6 +80,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"metrics_server",
ComponentOptions::new().is_observability(true),
);
+ // Registered here because components must exist before monitoring
+ // starts; the sweeper task itself is spawned later, once the engine
+ // exists. Supervision matters: with one sweeper per fleet, a silently
+ // dead loop means abandoned ops are never resumed.
+ let sweeper_handle = config
+ .lifecycle_sweeper_enabled
+ .then(|| manager.register("lifecycle_sweeper", ComponentOptions::new()));
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
@@ -169,10 +178,49 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
RouterClient::new(&config.router_url, config.leader_request_timeout())
.expect("Invalid router URL"),
);
+ let engine = Arc::new(Engine::new(
+ storage.primary_pool.clone(),
+ config.lifecycle_engine_config(),
+ ));
+ if let Some(sweeper_handle) = sweeper_handle {
+ let sweeper_engine = engine.clone();
+ let sweep_interval = config.lifecycle_sweep_interval();
+ let retention = config.lifecycle_op_retention();
+ tracing::info!(
+ interval_secs = sweep_interval.as_secs(),
+ retention_hours = retention.as_secs() / 3600,
+ "Lifecycle sweeper enabled"
+ );
+ tokio::spawn(async move {
+ // The scope guard tells the manager if this task dies (e.g. a
+ // panic in a sweep pass), so the pod restarts instead of running
+ // on with no resumer.
+ let _guard = sweeper_handle.process_scope();
+ let mut ticker = tokio::time::interval(sweep_interval);
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ tokio::select! {
+ _ = sweeper_handle.shutdown_recv() => break,
+ _ = ticker.tick() => {}
+ }
+ match sweeper_engine.sweep(&[&DeleteDriver]).await {
+ Ok(resumed) if resumed > 0 => {
+ tracing::info!(resumed, "Lifecycle sweeper resumed abandoned ops")
+ }
+ Ok(_) => {}
+ Err(e) => tracing::warn!(error = %e, "Lifecycle sweep pass failed"),
+ }
+ if let Err(e) = sweeper_engine.gc(retention).await {
+ tracing::warn!(error = %e, "Lifecycle GC pass failed");
+ }
+ }
+ });
+ }
+
let service = PersonHogIdentityService::new(storage, property_writer, config.request_limits());
// Separate proto service co-served on the same server so lifecycle
// callers are insulated from any future split.
- let lifecycle_service = PersonHogLifecycleService::new();
+ let lifecycle_service = PersonHogLifecycleService::new(engine);
let grpc_addr = config.grpc_address;
let keepalive_interval = config.grpc_keepalive_interval();
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 18269c699860..28ee7f7a7099 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -1,3 +1,7 @@
+// Shared by every integration-test binary; each binary compiles its own copy
+// and none of them uses every helper.
+#![allow(dead_code)]
+
use std::sync::Arc;
use rand::Rng;
@@ -61,7 +65,25 @@ 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.
+ 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),
+ execute_timeout: std::time::Duration::from_secs(10),
+ poll_interval: std::time::Duration::from_millis(25),
+ attempt_alert_threshold: 5,
+ },
+ )
+ }
+
pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
+ sqlx::query("DELETE FROM lifecycle_op WHERE team_id = $1")
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
.bind(self.team_id as i32)
.execute(&self.pool)
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
new file mode 100644
index 000000000000..e100fedf6f9a
--- /dev/null
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -0,0 +1,460 @@
+//! End-to-end tests of the DeletePersons endpoint flow: the RPC drives the
+//! delete saga to a terminal step and the response is the recorded outcome.
+
+mod common;
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use common::TestContext;
+use tonic::Request;
+use uuid::Uuid;
+
+use personhog_identity::lifecycle::delete::SEAL_VERSION_MARGIN;
+use personhog_identity::lifecycle::PersonHogLifecycleService;
+use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};
+use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
+use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePersonsRequest};
+
+/// Storage-assertion helpers used only by this test binary.
+impl TestContext {
+ fn lifecycle_service(&self) -> PersonHogLifecycleService {
+ PersonHogLifecycleService::new(Arc::new(self.engine()))
+ }
+
+ /// (is_deleted, version, properties) of a person row.
+ async fn person_state(&self, person_id: i64) -> (bool, i64, String) {
+ sqlx::query_as(
+ r#"
+ SELECT is_deleted, version, properties::text
+ FROM posthog_person WHERE team_id = $1 AND id = $2
+ "#,
+ )
+ .bind(self.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&self.pool)
+ .await
+ .expect("person row exists")
+ }
+
+ /// (is_deleted, version) of a distinct id row.
+ async fn pdi_state(&self, distinct_id: &str) -> (bool, i64) {
+ sqlx::query_as(
+ r#"
+ SELECT is_deleted, version
+ FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2
+ "#,
+ )
+ .bind(self.team_id as i32)
+ .bind(distinct_id)
+ .fetch_one(&self.pool)
+ .await
+ .expect("distinct id row exists")
+ }
+
+ async fn set_person_properties(&self, person_id: i64, properties: &str) {
+ sqlx::query(
+ "UPDATE posthog_person SET properties = $3::jsonb WHERE team_id = $1 AND id = $2",
+ )
+ .bind(self.team_id as i32)
+ .bind(person_id)
+ .bind(properties)
+ .execute(&self.pool)
+ .await
+ .expect("set properties");
+ }
+
+ async fn insert_cohort_and_hash_key_rows(&self, person_id: i64) {
+ sqlx::query("INSERT INTO posthog_cohortpeople (cohort_id, person_id) VALUES (1, $1)")
+ .bind(person_id)
+ .execute(&self.pool)
+ .await
+ .expect("insert cohortpeople row");
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_featureflaghashkeyoverride
+ (feature_flag_key, hash_key, person_id, team_id)
+ VALUES ('flag', 'hash', $1, $2)
+ "#,
+ )
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("insert hash key override row");
+ }
+
+ async fn count_cohort_and_hash_key_rows(&self, person_id: i64) -> (i64, i64) {
+ let cohort: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM posthog_cohortpeople WHERE person_id = $1")
+ .bind(person_id)
+ .fetch_one(&self.pool)
+ .await
+ .expect("count cohortpeople");
+ let hash_key: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM posthog_featureflaghashkeyoverride WHERE person_id = $1",
+ )
+ .bind(person_id)
+ .fetch_one(&self.pool)
+ .await
+ .expect("count hash key overrides");
+ (cohort, hash_key)
+ }
+
+ /// (step, has_completed_at) of an op row.
+ async fn op_state(&self, 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(&self.pool)
+ .await
+ .expect("op row exists");
+ (row.0, row.1.is_some())
+ }
+
+ /// Creates a person through the real stub-creation path, so its uuid is
+ /// the deterministic uuidv5 and a post-delete re-create of the same
+ /// distinct id conflicts with (and revives) the tombstone.
+ async fn create_person_via_stub(&self, distinct_id: &str) -> i64 {
+ let outcomes = self
+ .storage
+ .create_person_stubs(&[PersonStub {
+ team_id: self.team_id,
+ distinct_id: distinct_id.to_string(),
+ extra_distinct_ids: vec![],
+ created_at: Utc::now(),
+ is_identified: false,
+ }])
+ .await
+ .expect("stub creation succeeds");
+ match &outcomes[0] {
+ StubOutcome::Committed { person, .. } => person.id,
+ StubOutcome::LostRace => panic!("no concurrent writers in this test"),
+ }
+ }
+}
+
+fn delete_request(team_id: i64, person_ids: Vec<i64>, op_id: Uuid) -> DeletePersonsRequest {
+ DeletePersonsRequest {
+ team_id,
+ person_ids,
+ op_id: op_id.to_string(),
+ }
+}
+
+fn outcomes(
+ response: &personhog_proto::personhog::lifecycle::v1::DeletePersonsResponse,
+) -> Vec<(i64, DeletePersonOutcome)> {
+ response
+ .results
+ .iter()
+ .map(|r| (r.person_id, r.outcome()))
+ .collect()
+}
+
+#[tokio::test]
+async fn delete_destroys_the_person_and_its_satellite_rows() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+
+ let person_id = ctx.insert_person_with_distinct_id("victim-primary").await;
+ sqlx::query(
+ "INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version) VALUES ('victim-extra', $1, $2, 1)",
+ )
+ .bind(person_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert extra distinct id");
+ ctx.set_person_properties(person_id, r#"{"email": "[email protected]"}"#)
+ .await;
+ ctx.insert_cohort_and_hash_key_rows(person_id).await;
+
+ let op_id = Uuid::now_v7();
+ let response = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![person_id],
+ op_id,
+ )))
+ .await
+ .expect("delete succeeds")
+ .into_inner();
+
+ assert_eq!(response.op_id, op_id.to_string());
+ assert_eq!(
+ outcomes(&response),
+ vec![(person_id, DeletePersonOutcome::Deleted)]
+ );
+
+ // The person: tombstoned at sealed + 1 (version 0 at seal time), scrubbed.
+ let (is_deleted, version, properties) = ctx.person_state(person_id).await;
+ assert!(is_deleted);
+ assert_eq!(version, SEAL_VERSION_MARGIN + 1);
+ assert_eq!(properties, "{}");
+
+ // The mappings: tombstoned one version above their previous one.
+ assert_eq!(ctx.pdi_state("victim-primary").await, (true, 1));
+ assert_eq!(ctx.pdi_state("victim-extra").await, (true, 2));
+
+ // Cohort membership and hash-key overrides: cleared.
+ assert_eq!(ctx.count_cohort_and_hash_key_rows(person_id).await, (0, 0));
+
+ // The op: completed, with the per-person row settled and the tombstoned
+ // mappings recorded in `moved`.
+ assert_eq!(ctx.op_state(op_id).await, ("completed".to_string(), true));
+ let (status, moved): (String, Option<serde_json::Value>) = sqlx::query_as(
+ "SELECT status, moved FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",
+ )
+ .bind(op_id)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("per-person row exists");
+ assert_eq!(status, "deleted");
+ let moved = moved.expect("moved recorded");
+ let moved_ids: Vec<&str> = moved
+ .as_array()
+ .expect("moved is an array")
+ .iter()
+ .map(|m| m["distinct_id"].as_str().expect("distinct_id"))
+ .collect();
+ assert_eq!(moved_ids.len(), 2);
+ assert!(moved_ids.contains(&"victim-primary") && moved_ids.contains(&"victim-extra"));
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn outcomes_follow_request_order_and_missing_persons_are_not_found() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+
+ let person_id = ctx.insert_person_with_distinct_id("mixed-batch").await;
+ let missing_id = person_id + 1_000_000;
+
+ let response = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![missing_id, person_id],
+ Uuid::now_v7(),
+ )))
+ .await
+ .expect("delete succeeds")
+ .into_inner();
+
+ assert_eq!(
+ outcomes(&response),
+ vec![
+ (missing_id, DeletePersonOutcome::NotFound),
+ (person_id, DeletePersonOutcome::Deleted),
+ ]
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn an_all_missing_batch_aborts_before_mutating_anything() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+ let op_id = Uuid::now_v7();
+
+ let response = service
+ .delete_persons(Request::new(delete_request(ctx.team_id, vec![1, 2], op_id)))
+ .await
+ .expect("aborting is still an OK response")
+ .into_inner();
+
+ assert_eq!(
+ outcomes(&response),
+ vec![
+ (1, DeletePersonOutcome::NotFound),
+ (2, DeletePersonOutcome::NotFound),
+ ]
+ );
+ assert_eq!(ctx.op_state(op_id).await, ("aborted".to_string(), true));
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_person_marked_by_another_live_op_is_skipped() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+
+ let contested = ctx.insert_person_with_distinct_id("contested").await;
+ let free = ctx.insert_person_with_distinct_id("free").await;
+
+ // Another live op (a merge, say) holds the contested person's mark.
+ let other_op = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, lease_expires_at) VALUES ($1, 'merge', $2, 'claimed', '{}'::jsonb, now() + interval '1 hour')",
+ )
+ .bind(other_op)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert other op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) VALUES ($1, $2, $3, gen_random_uuid(), 'source', 'marked')",
+ )
+ .bind(other_op)
+ .bind(ctx.team_id as i32)
+ .bind(contested)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert other op's mark");
+
+ let response = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![contested, free],
+ Uuid::now_v7(),
+ )))
+ .await
+ .expect("delete succeeds")
+ .into_inner();
+
+ assert_eq!(
+ outcomes(&response),
+ vec![
+ (contested, DeletePersonOutcome::SkippedConflict),
+ (free, DeletePersonOutcome::Deleted),
+ ]
+ );
+ // The contested person is untouched.
+ let (is_deleted, version, _) = ctx.person_state(contested).await;
+ assert!(!is_deleted);
+ assert_eq!(version, 0);
+
+ 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;
+ let service = ctx.lifecycle_service();
+
+ let person_id = ctx.insert_person_with_distinct_id("retried").await;
+ let op_id = Uuid::now_v7();
+ let request = delete_request(ctx.team_id, vec![person_id], op_id);
+
+ let first = service
+ .delete_persons(Request::new(request.clone()))
+ .await
+ .expect("delete succeeds")
+ .into_inner();
+ assert_eq!(
+ outcomes(&first),
+ vec![(person_id, DeletePersonOutcome::Deleted)]
+ );
+
+ // The person no longer exists as a live row, but the retry still answers
+ // DELETED — the recorded outcome, not a fresh evaluation.
+ let retry = service
+ .delete_persons(Request::new(request))
+ .await
+ .expect("retry succeeds")
+ .into_inner();
+ assert_eq!(
+ outcomes(&retry),
+ vec![(person_id, DeletePersonOutcome::Deleted)]
+ );
+
+ // A fresh op for the same (now tombstoned) person finds nothing to delete.
+ let fresh = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![person_id],
+ Uuid::now_v7(),
+ )))
+ .await
+ .expect("fresh op succeeds")
+ .into_inner();
+ assert_eq!(
+ outcomes(&fresh),
+ vec![(person_id, DeletePersonOutcome::NotFound)]
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_caller_retry_resumes_an_abandoned_op_from_its_saved_step() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+
+ let person_id = ctx.insert_person_with_distinct_id("resumed").await;
+ let op_id = Uuid::now_v7();
+
+ // The op crashed right after creating its row: step 'started', nothing
+ // else persisted, lease lapsed.
+ 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": [person_id]}))
+ .execute(&ctx.pool)
+ .await
+ .expect("insert abandoned op");
+
+ let response = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![person_id],
+ op_id,
+ )))
+ .await
+ .expect("retry drives the op home")
+ .into_inner();
+
+ assert_eq!(
+ outcomes(&response),
+ vec![(person_id, DeletePersonOutcome::Deleted)]
+ );
+ let (is_deleted, _, _) = ctx.person_state(person_id).await;
+ assert!(is_deleted);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_recreated_distinct_id_revives_above_the_death_version() {
+ let ctx = TestContext::new().await;
+ let service = ctx.lifecycle_service();
+
+ // Created through the real stub path so the person carries the uuidv5
+ // key a re-create will collide with.
+ let person_id = ctx.create_person_via_stub("reborn").await;
+
+ let response = service
+ .delete_persons(Request::new(delete_request(
+ ctx.team_id,
+ vec![person_id],
+ Uuid::now_v7(),
+ )))
+ .await
+ .expect("delete succeeds")
+ .into_inner();
+ assert_eq!(
+ outcomes(&response),
+ vec![(person_id, DeletePersonOutcome::Deleted)]
+ );
+ let (_, death_version, _) = ctx.person_state(person_id).await;
+
+ // The same distinct id comes back: the create revives the tombstone one
+ // version above the death document, so ClickHouse collapses toward the
+ // new incarnation.
+ let revived_id = ctx.create_person_via_stub("reborn").await;
+ assert_eq!(revived_id, person_id, "revival reuses the tombstoned row");
+ let (is_deleted, version, _) = ctx.person_state(person_id).await;
+ assert!(!is_deleted);
+ assert_eq!(version, death_version + 1);
+
+ ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
new file mode 100644
index 000000000000..58aaf23f51a5
--- /dev/null
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -0,0 +1,444 @@
+//! 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.
+
+mod common;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use async_trait::async_trait;
+use common::TestContext;
+use serde_json::json;
+use sqlx::postgres::PgPool;
+use uuid::Uuid;
+
+use personhog_identity::lifecycle::engine::{
+ advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, STEP_COMPLETED,
+};
+
+/// Two-step dummy op: `started → half → completed`. Counts step executions
+/// so tests can prove what did (or did not) re-run.
+struct DummyDriver {
+ steps_run: AtomicUsize,
+}
+
+impl DummyDriver {
+ fn new() -> Self {
+ Self {
+ steps_run: AtomicUsize::new(0),
+ }
+ }
+}
+
+#[async_trait]
+impl OpDriver for DummyDriver {
+ 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);
+ let mut tx = pool.begin().await.map_err(SagaError::Db)?;
+ let advanced = match op.step.as_str() {
+ "started" => advance_step_in_tx(&mut tx, op.op_id, "started", "half").await?,
+ "half" => {
+ complete_op_in_tx(
+ &mut tx,
+ op.op_id,
+ "half",
+ STEP_COMPLETED,
+ &json!({"ok": true}),
+ )
+ .await?
+ }
+ other => {
+ return Err(SagaError::CorruptState(format!("unknown step {other}")));
+ }
+ };
+ if !advanced {
+ tx.rollback().await.map_err(SagaError::Db)?;
+ return Ok(());
+ }
+ tx.commit().await.map_err(SagaError::Db)?;
+ Ok(())
+ }
+}
+
+async fn op_row(ctx: &TestContext, op_id: Uuid) -> (String, i32, Option<serde_json::Value>, bool) {
+ let row: (
+ String,
+ i32,
+ Option<serde_json::Value>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ ) = sqlx::query_as(
+ "SELECT step, attempt, outcome, completed_at FROM lifecycle_op WHERE op_id = $1",
+ )
+ .bind(op_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("op row exists");
+ (row.0, row.1, row.2, row.3.is_some())
+}
+
+#[tokio::test]
+async fn a_new_op_is_driven_to_completion_and_records_its_outcome() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ let row = engine
+ .execute(&driver, op_id, ctx.team_id, &json!({"work": 1}))
+ .await
+ .expect("op completes");
+
+ assert_eq!(row.step, STEP_COMPLETED);
+ assert_eq!(row.outcome, Some(json!({"ok": true})));
+ assert!(row.completed_at.is_some());
+ assert_eq!(driver.steps_run.load(Ordering::SeqCst), 2);
+
+ let (step, attempt, _, completed) = op_row(&ctx, op_id).await;
+ assert_eq!(step, STEP_COMPLETED);
+ assert_eq!(attempt, 1, "one claim by the driving call");
+ assert!(completed);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_retry_with_the_same_op_id_returns_the_recorded_outcome_without_rerunning() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+ let request = json!({"work": 2});
+
+ engine
+ .execute(&driver, op_id, ctx.team_id, &request)
+ .await
+ .expect("op completes");
+ let steps_after_first = driver.steps_run.load(Ordering::SeqCst);
+
+ let row = engine
+ .execute(&driver, op_id, ctx.team_id, &request)
+ .await
+ .expect("retry attaches");
+
+ assert_eq!(row.outcome, Some(json!({"ok": true})));
+ assert_eq!(
+ driver.steps_run.load(Ordering::SeqCst),
+ steps_after_first,
+ "a completed op never re-runs"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn an_op_id_reused_with_a_different_request_is_rejected() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ engine
+ .execute(&driver, op_id, ctx.team_id, &json!({"work": 3}))
+ .await
+ .expect("op completes");
+
+ let err = engine
+ .execute(&driver, op_id, ctx.team_id, &json!({"work": 999}))
+ .await
+ .expect_err("different request must not attach");
+ assert!(matches!(err, SagaError::RequestMismatch(_)));
+
+ let err = engine
+ .execute(&driver, op_id, ctx.team_id + 1, &json!({"work": 3}))
+ .await
+ .expect_err("different team must not attach");
+ assert!(matches!(err, SagaError::RequestMismatch(_)));
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn resume_picks_up_an_op_from_its_saved_step() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ // An op abandoned mid-flight: past its first step, lease lapsed.
+ 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')
+ "#,
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert abandoned op");
+
+ let row = engine
+ .resume(&driver, op_id)
+ .await
+ .expect("resume completes");
+
+ assert_eq!(row.step, STEP_COMPLETED);
+ assert_eq!(
+ driver.steps_run.load(Ordering::SeqCst),
+ 1,
+ "only the remaining step runs"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn the_sweeper_resumes_abandoned_ops_and_gc_reaps_completed_ones() {
+ 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);
+
+ // Backdate the completion past retention; GC reaps it (and cascades the
+ // per-person rows) without touching other tests' fresh rows.
+ sqlx::query(
+ "UPDATE lifecycle_op SET completed_at = now() - interval '2 hours' WHERE op_id = $1",
+ )
+ .bind(op_id)
+ .execute(&ctx.pool)
+ .await
+ .expect("backdate completion");
+ engine
+ .gc(std::time::Duration::from_secs(3600))
+ .await
+ .expect("gc runs");
+ let gone: Option<(String,)> = sqlx::query_as("SELECT step FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .fetch_optional(&ctx.pool)
+ .await
+ .expect("query runs");
+ assert!(gone.is_none(), "completed op past retention is deleted");
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_live_lease_blocks_a_second_driver_until_it_lapses() {
+ let ctx = TestContext::new().await;
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ // Held by "another instance" for longer than the test engine's execute
+ // timeout would wait — but we assert Busy well before that.
+ 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 hour')
+ "#,
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert leased op");
+
+ let short_engine = personhog_identity::lifecycle::engine::Engine::new(
+ ctx.pool.clone(),
+ personhog_identity::lifecycle::engine::EngineConfig {
+ lease: std::time::Duration::from_secs(5),
+ execute_timeout: std::time::Duration::from_millis(200),
+ poll_interval: std::time::Duration::from_millis(25),
+ attempt_alert_threshold: 5,
+ },
+ );
+ let err = short_engine
+ .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .await
+ .expect_err("cannot steal a live lease");
+ assert!(matches!(err, SagaError::Busy));
+ assert_eq!(
+ driver.steps_run.load(Ordering::SeqCst),
+ 0,
+ "no step ran while another instance held the lease"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn resume_bails_immediately_when_another_driver_holds_the_lease() {
+ let ctx = TestContext::new().await;
+ // The default test engine's 10s execute timeout: a resume that waits
+ // out a live lease instead of bailing would blow the elapsed assertion.
+ 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 hour')
+ "#,
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert leased op");
+
+ let started = std::time::Instant::now();
+ let err = engine
+ .resume(&driver, op_id)
+ .await
+ .expect_err("live lease means not abandoned");
+
+ assert!(matches!(err, SagaError::Busy));
+ assert_eq!(driver.steps_run.load(Ordering::SeqCst), 0);
+ assert!(
+ started.elapsed() < std::time::Duration::from_secs(5),
+ "resume must skip a live lease, not poll out the execute timeout"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+/// Simulates another instance stealing the op mid-step: bumps `attempt` and
+/// takes a one-hour lease, exactly what a concurrent `try_claim` does.
+async fn steal_lease(pool: &PgPool, op_id: Uuid) {
+ sqlx::query(
+ "UPDATE lifecycle_op SET attempt = attempt + 1, lease_expires_at = now() + interval '1 hour' WHERE op_id = $1",
+ )
+ .bind(op_id)
+ .execute(pool)
+ .await
+ .expect("steal lease");
+}
+
+async fn lease_is_live(pool: &PgPool, op_id: Uuid) -> bool {
+ sqlx::query_scalar("SELECT lease_expires_at > now() FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .fetch_one(pool)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or(false)
+}
+
+/// Driver whose first step gets its lease stolen mid-run. `fail_after_steal`
+/// picks the exit: Err exercises the engine's release path, Ok without
+/// advancing (a lost CAS) exercises the renew path.
+struct StolenLeaseDriver {
+ steps_run: AtomicUsize,
+ fail_after_steal: bool,
+}
+
+#[async_trait]
+impl OpDriver for StolenLeaseDriver {
+ 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);
+ steal_lease(pool, op.op_id).await;
+ if self.fail_after_steal {
+ Err(SagaError::CorruptState("simulated step failure".into()))
+ } else {
+ Ok(())
+ }
+ }
+}
+
+#[tokio::test]
+async fn a_driver_whose_lease_was_stolen_stops_running_steps_instead_of_renewing() {
+ let ctx = TestContext::new().await;
+ let driver = StolenLeaseDriver {
+ steps_run: AtomicUsize::new(0),
+ fail_after_steal: false,
+ };
+ let op_id = Uuid::now_v7();
+
+ let short_engine = personhog_identity::lifecycle::engine::Engine::new(
+ ctx.pool.clone(),
+ personhog_identity::lifecycle::engine::EngineConfig {
+ lease: std::time::Duration::from_secs(5),
+ execute_timeout: std::time::Duration::from_millis(200),
+ poll_interval: std::time::Duration::from_millis(25),
+ attempt_alert_threshold: 5,
+ },
+ );
+ let err = short_engine
+ .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .await
+ .expect_err("waits on the stealer's lease until the deadline");
+
+ assert!(matches!(err, SagaError::Busy));
+ assert_eq!(
+ driver.steps_run.load(Ordering::SeqCst),
+ 1,
+ "no step ran after the lease was stolen"
+ );
+ assert!(
+ lease_is_live(&ctx.pool, op_id).await,
+ "the displaced driver must not have renewed or cleared the stealer's lease"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_failing_driver_whose_lease_was_stolen_does_not_release_the_stealers_lease() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = StolenLeaseDriver {
+ steps_run: AtomicUsize::new(0),
+ fail_after_steal: true,
+ };
+ let op_id = Uuid::now_v7();
+
+ let err = engine
+ .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .await
+ .expect_err("step failure propagates");
+
+ assert!(matches!(err, SagaError::CorruptState(_)));
+ assert!(
+ lease_is_live(&ctx.pool, op_id).await,
+ "the stale driver's error-path release must not clear the stealer's lease"
+ );
+
+ ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rs
index c0c51492d26a..31761c2e60c3 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -1,5 +1,10 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use sqlx::postgres::PgPoolOptions;
use tonic::{Code, Request};
+use personhog_identity::lifecycle::engine::{Engine, EngineConfig};
use personhog_identity::lifecycle::validation::MAX_DELETE_BATCH_SIZE;
use personhog_identity::lifecycle::PersonHogLifecycleService;
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
@@ -13,12 +18,26 @@ fn valid_request() -> DeletePersonsRequest {
}
}
+/// Validation rejects before the engine touches storage, so a lazy pool that
+/// never connects is enough to construct the service.
async fn delete_status(request: DeletePersonsRequest) -> Code {
- let service = PersonHogLifecycleService::new();
+ let pool = PgPoolOptions::new()
+ .connect_lazy("postgres://unused:unused@localhost:1/unused")
+ .expect("lazy pool never connects");
+ let engine = Arc::new(Engine::new(
+ pool,
+ EngineConfig {
+ lease: Duration::from_secs(1),
+ execute_timeout: Duration::from_secs(1),
+ poll_interval: Duration::from_millis(10),
+ attempt_alert_threshold: 5,
+ },
+ ));
+ let service = PersonHogLifecycleService::new(engine);
service
.delete_persons(Request::new(request))
.await
- .expect_err("skeleton service never returns Ok")
+ .expect_err("invalid requests are rejected")
.code()
}
@@ -77,8 +96,3 @@ async fn invalid_requests_are_rejected_before_the_saga() {
);
}
}
-
-#[tokio::test]
-async fn valid_request_reports_unimplemented_until_the_engine_lands() {
- assert_eq!(delete_status(valid_request()).await, Code::Unimplemented);
-}