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): make the identity table set configurable (#80966)

José Sequeiraeb164782973f
diff --git a/rust/personhog-common/src/persons.rs b/rust/personhog-common/src/persons.rs
index 95b7da93933e..5f41f55c87ce 100644
--- a/rust/personhog-common/src/persons.rs
+++ b/rust/personhog-common/src/persons.rs
@@ -20,6 +20,15 @@ pub fn person_uuid(team_id: i64, distinct_id: &str) -> Uuid {
)
}
+/// Validate a configured table identifier before it is interpolated into
+/// SQL (identifiers cannot be bound as parameters).
+pub fn validate_table_name(table: &str) -> Result<(), String> {
+ if table.is_empty() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ return Err(format!("invalid table name: {table:?}"));
+ }
+ Ok(())
+}
+
#[derive(Debug, Clone)]
pub struct Person {
pub id: i64,
diff --git a/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.json b/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.json
deleted file mode 100644
index 63713a73ee7e..000000000000
--- a/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.json
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO posthog_person\n (created_at, properties, properties_last_updated_at, properties_last_operation,\n team_id, is_identified, uuid, version, last_seen_at)\n SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,\n u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)\n FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])\n AS u(created_at, team_id, is_identified, uuid)\n ON CONFLICT (team_id, uuid) DO UPDATE SET\n is_deleted = false,\n version = COALESCE(posthog_person.version, 0) + 1,\n properties = '{}'::jsonb,\n properties_last_updated_at = '{}'::jsonb,\n properties_last_operation = '{}'::jsonb,\n created_at = EXCLUDED.created_at,\n is_identified = EXCLUDED.is_identified,\n last_seen_at = EXCLUDED.last_seen_at\n WHERE posthog_person.is_deleted = true\n RETURNING id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties?\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Int8"
- },
- {
- "ordinal": 1,
- "name": "uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "team_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 3,
- "name": "properties?",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "properties_last_updated_at?",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "properties_last_operation?",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "created_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "version",
- "type_info": "Int8"
- },
- {
- "ordinal": 8,
- "name": "is_identified",
- "type_info": "Bool"
- },
- {
- "ordinal": 9,
- "name": "is_user_id",
- "type_info": "Bool"
- },
- {
- "ordinal": 10,
- "name": "last_seen_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "TimestamptzArray",
- "Int4Array",
- "BoolArray",
- "UuidArray"
- ]
- },
- "nullable": [
- false,
- false,
- null,
- null,
- null,
- null,
- false,
- true,
- false,
- null,
- true
- ]
- },
- "hash": "05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0"
-}
diff --git a/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.json b/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.json
deleted file mode 100644
index d13c7ce49e0a..000000000000
--- a/rust/personhog-identity/.sqlx/query-14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM lifecycle_op_person lop\n WHERE lop.op_id = $1 AND lop.status = 'marked'\n AND NOT EXISTS (\n SELECT 1 FROM posthog_person p\n WHERE p.team_id = $2 AND p.id = lop.person_id AND p.is_deleted = false\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Int4"
- ]
- },
- "nullable": []
- },
- "hash": "14e1e46d7be53d8e0a74b5ea8e91fb35225aee2a555e86d620e2f31c8d0a869f"
-}
diff --git a/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json b/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json
deleted file mode 100644
index 4f19428017a2..000000000000
--- a/rust/personhog-identity/.sqlx/query-18b53f55aa60c59ef104c5871654e15453f8913b5b674d58907734f9412c85f0.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "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-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.json b/rust/personhog-identity/.sqlx/query-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.json
deleted file mode 100644
index b08a3186c18d..000000000000
--- a/rust/personhog-identity/.sqlx/query-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.json
+++ /dev/null
@@ -1,95 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT k.team_id as \"key_team_id!\", k.distinct_id as \"key_distinct_id!\",\n p.id as \"id!\", p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n p.properties::text as \"properties?\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"is_identified!\",\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,\n p.last_seen_at\n FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN posthog_persondistinctid pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n AND pdi.is_deleted = false\n JOIN posthog_person p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n AND p.is_deleted = false\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "key_team_id!",
- "type_info": "Int4"
- },
- {
- "ordinal": 1,
- "name": "key_distinct_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 3,
- "name": "uuid!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 4,
- "name": "team_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 5,
- "name": "properties?",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "properties_last_updated_at?",
- "type_info": "Text"
- },
- {
- "ordinal": 7,
- "name": "properties_last_operation?",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "version",
- "type_info": "Int8"
- },
- {
- "ordinal": 10,
- "name": "is_identified!",
- "type_info": "Bool"
- },
- {
- "ordinal": 11,
- "name": "is_user_id",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "last_seen_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Int4Array",
- "TextArray"
- ]
- },
- "nullable": [
- null,
- null,
- false,
- false,
- null,
- null,
- null,
- null,
- false,
- true,
- false,
- null,
- true
- ]
- },
- "hash": "1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9"
-}
diff --git a/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.json b/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.json
deleted file mode 100644
index 7834b1bf7347..000000000000
--- a/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_persondistinctid\n SET is_deleted = true, version = COALESCE(version, 0) + 1\n WHERE team_id = $1 AND distinct_id = ANY($2)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266"
-}
diff --git a/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.json b/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.json
deleted file mode 100644
index 09a9a2db1c17..000000000000
--- a/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_person\n SET is_deleted = true, version = COALESCE(version, 0) + 1,\n properties = '{}'::jsonb\n WHERE team_id = $1 AND id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5"
-}
diff --git a/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.json b/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.json
deleted file mode 100644
index 8897cd94df0c..000000000000
--- a/rust/personhog-identity/.sqlx/query-2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_persondistinctid pdi\n SET person_id = $3, version = COALESCE(pdi.version, 0) + 1\n FROM posthog_persondistinctid old\n WHERE old.id = pdi.id\n AND pdi.team_id = $1 AND pdi.person_id = ANY($2) AND pdi.is_deleted = false\n RETURNING old.person_id as \"old_person_id!\", pdi.distinct_id, pdi.version as \"version!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "old_person_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 1,
- "name": "distinct_id",
- "type_info": "Varchar"
- },
- {
- "ordinal": 2,
- "name": "version!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Int4",
- "Int8Array",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- true
- ]
- },
- "hash": "2e5d55f82546ef0053983bb57e91c6d8d1b3f32d267dc9f9c3baf484d160f90a"
-}
diff --git a/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json b/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json
deleted file mode 100644
index 372315eefe5d..000000000000
--- a/rust/personhog-identity/.sqlx/query-3146a582b269dd52291f84dd64565beba7b9502474eda263f205101eb57c44fc.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "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-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json b/rust/personhog-identity/.sqlx/query-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json
deleted file mode 100644
index bf110aedfd96..000000000000
--- a/rust/personhog-identity/.sqlx/query-42cd5bff8c315064987b53785698e7bf5d92e92cea749e78d58fdac630fbf51c.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "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-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json b/rust/personhog-identity/.sqlx/query-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json
deleted file mode 100644
index 588fa587a66c..000000000000
--- a/rust/personhog-identity/.sqlx/query-4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "4501d897722f15a3966ba862b7c2dd8117edcc4aaddd4eee6e169c151e7ac56d"
-}
diff --git a/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json b/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json
deleted file mode 100644
index 751246ca3c31..000000000000
--- a/rust/personhog-identity/.sqlx/query-58278a379b8ba65a379c9c95530e7f8b28d23f8f1788c77ef088e3d0a9a11e6e.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "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
deleted file mode 100644
index 88e058de3fb1..000000000000
--- a/rust/personhog-identity/.sqlx/query-5bbcabb838ac3962a7f9f39f8086e37172d9d42f85f35040e65a58f1b7735982.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "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-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.json b/rust/personhog-identity/.sqlx/query-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.json
deleted file mode 100644
index 314ced701d82..000000000000
--- a/rust/personhog-identity/.sqlx/query-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2 AND is_deleted = false",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "person_id",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Int4",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47"
-}
diff --git a/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.json b/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.json
deleted file mode 100644
index 3570dca72cdb..000000000000
--- a/rust/personhog-identity/.sqlx/query-68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT d.distinct_id, d.person_id as \"person_id!\", p.uuid as \"person_uuid!\",\n p.is_identified as \"is_identified!\"\n FROM posthog_persondistinctid d\n JOIN posthog_person p ON p.team_id = d.team_id AND p.id = d.person_id\n WHERE d.team_id = $1 AND d.distinct_id = ANY($2)\n AND d.is_deleted = false AND p.is_deleted = false\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "distinct_id",
- "type_info": "Varchar"
- },
- {
- "ordinal": 1,
- "name": "person_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 2,
- "name": "person_uuid!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "is_identified!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Int4",
- "TextArray"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false
- ]
- },
- "hash": "68c4844b1034525f6e9da24f2ea60a4e46a8c56541d5e7bcae2708774aeb6b32"
-}
diff --git a/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json b/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json
deleted file mode 100644
index a401cf2a632b..000000000000
--- a/rust/personhog-identity/.sqlx/query-8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false\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": "8432c495e71b8f42f55c7f9338d6718e108ec2c4baf1e73555bf22588aaa9640"
-}
diff --git a/rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.json b/rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.json
deleted file mode 100644
index a5fa478c87fa..000000000000
--- a/rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.json
+++ /dev/null
@@ -1,83 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT p.id as \"id!\", p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n p.properties::text as \"properties?\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"is_identified!\",\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,\n p.last_seen_at\n FROM posthog_person p\n JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)\n ON p.team_id = k.team_id AND p.uuid = k.uuid\n WHERE p.is_deleted = false\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 1,
- "name": "uuid!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "team_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 3,
- "name": "properties?",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "properties_last_updated_at?",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "properties_last_operation?",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "version",
- "type_info": "Int8"
- },
- {
- "ordinal": 8,
- "name": "is_identified!",
- "type_info": "Bool"
- },
- {
- "ordinal": 9,
- "name": "is_user_id",
- "type_info": "Bool"
- },
- {
- "ordinal": 10,
- "name": "last_seen_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Int4Array",
- "UuidArray"
- ]
- },
- "nullable": [
- false,
- false,
- null,
- null,
- null,
- null,
- false,
- true,
- false,
- null,
- true
- ]
- },
- "hash": "a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83"
-}
diff --git a/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.json b/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.json
deleted file mode 100644
index 5e535536bba6..000000000000
--- a/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)\n SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])\n AS u(d, p, t, v)\n ON CONFLICT (team_id, distinct_id) DO UPDATE SET\n person_id = EXCLUDED.person_id,\n version = COALESCE(posthog_persondistinctid.version, 0) + 1,\n is_deleted = false\n WHERE posthog_persondistinctid.is_deleted = true\n RETURNING team_id::bigint as \"team_id!\", distinct_id, person_id,\n (xmax = 0) as \"inserted!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "team_id!",
- "type_info": "Int8"
- },
- {
- "ordinal": 1,
- "name": "distinct_id",
- "type_info": "Varchar"
- },
- {
- "ordinal": 2,
- "name": "person_id",
- "type_info": "Int8"
- },
- {
- "ordinal": 3,
- "name": "inserted!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "TextArray",
- "Int8Array",
- "Int4Array",
- "Int8Array"
- ]
- },
- "nullable": [
- null,
- false,
- false,
- null
- ]
- },
- "hash": "bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d"
-}
diff --git a/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.json b/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.json
deleted file mode 100644
index 2305705fef8a..000000000000
--- a/rust/personhog-identity/.sqlx/query-c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH removed AS (\n DELETE FROM posthog_featureflaghashkeyoverride\n WHERE team_id = $1 AND person_id = ANY($2)\n RETURNING feature_flag_key, hash_key\n )\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT $1, $3, feature_flag_key, hash_key FROM removed\n ON CONFLICT (team_id, person_id, feature_flag_key) DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "Int8Array",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "c5d4d3301045ddeb8bcbdbe1d8d705104970588af1811f77fa57dc37d78e6431"
-}
diff --git a/rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.json b/rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.json
deleted file mode 100644
index 5579abc7e0f2..000000000000
--- a/rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2 AND is_deleted = false",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8"
-}
diff --git a/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.json b/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.json
deleted file mode 100644
index ff26aea95a1f..000000000000
--- a/rust/personhog-identity/.sqlx/query-d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_person p\n SET is_deleted = true,\n properties = '{}'::jsonb,\n properties_last_updated_at = '{}'::jsonb,\n properties_last_operation = '{}'::jsonb,\n version = (lop.sealed->>'version')::bigint + 1\n FROM lifecycle_op_person lop\n WHERE lop.op_id = $1 AND lop.role = $3 AND lop.status = $4\n AND p.team_id = $2 AND p.id = lop.person_id\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Int4",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "d2f838d0412f0f0139461c8b0a7e7feaf899a374ceacb6c429d9b95963e329b2"
-}
diff --git a/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.json b/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.json
deleted file mode 100644
index f5703b1e44e4..000000000000
--- a/rust/personhog-identity/.sqlx/query-da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT c.person_id AS \"person_id!\"\n FROM unnest($2::bigint[]) AS c(person_id)\n WHERE (\n SELECT count(*)\n FROM (\n SELECT 1\n FROM posthog_persondistinctid d\n WHERE d.team_id = $1\n AND d.person_id = c.person_id\n AND d.is_deleted = false\n LIMIT $3::bigint + 1\n ) capped\n ) > $3::bigint\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "person_id!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Int4",
- "Int8Array",
- "Int8"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "da2dc456aea98e0ebc76504327dffd80e50c876890cec7aa1b72873a1ebe37ef"
-}
diff --git a/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json b/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json
deleted file mode 100644
index 03bea104c9bb..000000000000
--- a/rust/personhog-identity/.sqlx/query-e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT l.person_id, l.distinct_id, l.version\n FROM UNNEST($2::bigint[]) AS pid(id)\n CROSS JOIN LATERAL (\n SELECT capped.person_id, capped.distinct_id, capped.version\n FROM (\n SELECT person_id, distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id AND is_deleted = false\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ) l\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",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- true
- ]
- },
- "hash": "e14a76228d22554c12b6b837fb8db1bb890726b380eba0255855b15427a926f3"
-}
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 33fc9f61f092..6bc7ced779d2 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -12,6 +12,28 @@ pub struct Config {
#[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
pub primary_database_url: String,
+ /// Person table every identity query reads and writes (stub creation,
+ /// resolution, and the delete saga's person mutations). Must pair with
+ /// the leader's FALLBACK_TABLE and the writer's PG_TARGET_TABLE so the
+ /// three services agree on where person rows live. Defaults to the
+ /// validation table, matching the writer; set to "posthog_person" at
+ /// production cutover — and flip all three services together.
+ #[envconfig(default = "personhog_person_tmp")]
+ pub person_table: String,
+
+ /// Distinct id table paired with PERSON_TABLE. Person ids come from the
+ /// person table's own sequence, so the mapping must live in the same
+ /// namespace (and posthog_persondistinctid's FK rejects ids that are not
+ /// in posthog_person). Set to "posthog_persondistinctid" at cutover.
+ #[envconfig(default = "personhog_persondistinctid_tmp")]
+ pub person_distinct_id_table: String,
+
+ /// Feature-flag hash-key-override table the delete saga clears by
+ /// person_id — same namespace rule as the distinct id table. Set to
+ /// "posthog_featureflaghashkeyoverride" at cutover.
+ #[envconfig(default = "personhog_featureflaghashkeyoverride_tmp")]
+ pub ff_hash_key_override_table: String,
+
#[envconfig(default = "10")]
pub max_pg_connections: u32,
@@ -127,7 +149,59 @@ pub struct Config {
pub lifecycle_op_retention_hours: u64,
}
+/// The paired table set identity operates on: the person table plus the
+/// tables it writes rows into (or clears rows from) keyed by that table's
+/// person ids. The three must come from the same namespace — mixing the
+/// validation set with the real set cross-contaminates id spaces.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct IdentityTables {
+ pub person: String,
+ pub person_distinct_id: String,
+ pub ff_hash_key_override: String,
+}
+
+impl IdentityTables {
+ pub fn real() -> Self {
+ Self {
+ person: "posthog_person".to_string(),
+ person_distinct_id: "posthog_persondistinctid".to_string(),
+ ff_hash_key_override: "posthog_featureflaghashkeyoverride".to_string(),
+ }
+ }
+
+ pub fn validation() -> Self {
+ Self {
+ person: "personhog_person_tmp".to_string(),
+ person_distinct_id: "personhog_persondistinctid_tmp".to_string(),
+ ff_hash_key_override: "personhog_featureflaghashkeyoverride_tmp".to_string(),
+ }
+ }
+
+ /// Only the two complete namespaces are accepted: a partial override
+ /// (one table flipped, the others left on defaults) would pair person
+ /// ids from one sequence with rows keyed by another, which is exactly
+ /// the cross-contamination this config exists to prevent.
+ pub fn validate(&self) -> Result<(), String> {
+ if *self == Self::real() || *self == Self::validation() {
+ return Ok(());
+ }
+ Err(format!(
+ "mixed identity table set {self:?}: set PERSON_TABLE, PERSON_DISTINCT_ID_TABLE, \
+ and FF_HASH_KEY_OVERRIDE_TABLE together, to either the full real set or the \
+ full validation set"
+ ))
+ }
+}
+
impl Config {
+ pub fn tables(&self) -> IdentityTables {
+ IdentityTables {
+ person: self.person_table.clone(),
+ person_distinct_id: self.person_distinct_id_table.clone(),
+ ff_hash_key_override: self.ff_hash_key_override_table.clone(),
+ }
+ }
+
pub fn request_limits(&self) -> crate::service::validation::RequestLimits {
crate::service::validation::RequestLimits {
max_batch_size: self.max_batch_size,
@@ -201,3 +275,26 @@ impl Config {
Duration::from_secs(self.lifecycle_op_retention_hours * 3600)
}
}
+
+// A mixed table set pairs person ids from one sequence with rows keyed by
+// another; validation must refuse it rather than let a partial env override
+// through.
+#[cfg(test)]
+mod tests {
+ use super::IdentityTables;
+
+ #[test]
+ fn complete_table_sets_pass_validation() {
+ assert!(IdentityTables::real().validate().is_ok());
+ assert!(IdentityTables::validation().validate().is_ok());
+ }
+
+ #[test]
+ fn a_mixed_table_set_is_refused() {
+ let mixed = IdentityTables {
+ person: "posthog_person".to_string(),
+ ..IdentityTables::validation()
+ };
+ assert!(mixed.validate().is_err());
+ }
+}
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index b3bcbe433c09..4976c78ce7f0 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -23,6 +23,7 @@ use uuid::Uuid;
use personhog_proto::personhog::types::v1::LifecycleOpType;
+use crate::config::IdentityTables;
use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
@@ -135,7 +136,16 @@ fn record_outcomes(outcome: &Value) {
}
}
-pub struct DeleteDriver;
+pub struct DeleteDriver {
+ tables: IdentityTables,
+}
+
+impl DeleteDriver {
+ pub fn new(tables: IdentityTables) -> Self {
+ tables.validate().expect("invalid identity table set");
+ Self { tables }
+ }
+}
#[async_trait]
impl OpDriver for DeleteDriver {
@@ -155,9 +165,9 @@ impl OpDriver for DeleteDriver {
))
})?;
match step {
- DeleteStep::Started => mark(pool, op).await,
- DeleteStep::Marked => seal(pool, op).await,
- DeleteStep::Sealed => unmap(pool, op).await,
+ DeleteStep::Started => mark(pool, &self.tables.person, op).await,
+ DeleteStep::Marked => seal(pool, &self.tables.person, op).await,
+ DeleteStep::Sealed => unmap(pool, &self.tables, op).await,
DeleteStep::Unmapped => complete(pool, op).await,
}
}
@@ -178,7 +188,7 @@ fn parse_request(op: &OpRow) -> Result<DeleteRequest, SagaError> {
/// `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> {
+async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
let mut tx = pool.begin().await?;
@@ -203,19 +213,20 @@ async fn mark(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
to_claim.sort_unstable();
to_claim.dedup();
- let live = sqlx::query!(
+ let live_sql = format!(
r#"
- SELECT id, uuid FROM posthog_person
+ SELECT id, uuid FROM {person_table}
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();
+ "#
+ );
+ let live: Vec<(i64, Uuid)> = sqlx::query_as(&live_sql)
+ .bind(team_id)
+ .bind(&to_claim)
+ .fetch_all(&mut *tx)
+ .await?;
+ let live_ids: Vec<i64> = live.iter().map(|(id, _)| *id).collect();
+ let live_uuids: Vec<Uuid> = live.iter().map(|(_, uuid)| *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.
@@ -246,8 +257,8 @@ async fn mark(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
.collect();
let conflicted_uuids: Vec<Uuid> = live
.iter()
- .filter(|p| conflicted_ids.contains(&p.id))
- .map(|p| p.uuid)
+ .filter(|(id, _)| conflicted_ids.contains(id))
+ .map(|(_, uuid)| *uuid)
.collect();
if !conflicted_ids.is_empty() {
sqlx::query!(
@@ -272,20 +283,21 @@ async fn mark(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
// and the insert lands on a corpse. Remove such marks here, in the
// same transaction: the person reports as not_found and is never
// touched again. From here on the mark keeps every held person alive.
- sqlx::query!(
+ let corpse_sql = format!(
r#"
DELETE FROM lifecycle_op_person lop
WHERE lop.op_id = $1 AND lop.status = 'marked'
AND NOT EXISTS (
- SELECT 1 FROM posthog_person p
+ SELECT 1 FROM {person_table} p
WHERE p.team_id = $2 AND p.id = lop.person_id AND p.is_deleted = false
)
- "#,
- op.op_id,
- team_id,
- )
- .execute(&mut *tx)
- .await?;
+ "#
+ );
+ sqlx::query(&corpse_sql)
+ .bind(op.op_id)
+ .bind(team_id)
+ .execute(&mut *tx)
+ .await?;
let claims: i64 = sqlx::query_scalar!(
r#"
@@ -340,25 +352,26 @@ async fn mark(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
/// 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> {
+async fn seal(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
let mut tx = pool.begin().await?;
- sqlx::query!(
+ let seal_sql = format!(
r#"
UPDATE lifecycle_op_person lop
SET status = $3, sealed = jsonb_build_object('version', COALESCE(p.version, 0) + $4)
- FROM posthog_person p
+ FROM {person_table} 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?;
+ "#
+ );
+ sqlx::query(&seal_sql)
+ .bind(op.op_id)
+ .bind(team_id)
+ .bind(STATUS_SEALED)
+ .bind(SEAL_VERSION_MARGIN)
+ .execute(&mut *tx)
+ .await?;
if !advance_step_in_tx(
&mut tx,
@@ -384,7 +397,7 @@ async fn seal(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
/// 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> {
+async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
let mut tx = pool.begin().await?;
@@ -399,18 +412,20 @@ async fn unmap(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
.await?;
victims.sort_unstable();
- let tombstoned = sqlx::query!(
+ let tombstone_pdi_sql = format!(
r#"
- UPDATE posthog_persondistinctid
+ UPDATE {pdi_table}
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!"
+ RETURNING person_id, distinct_id, version
"#,
- team_id,
- &victims,
- )
- .fetch_all(&mut *tx)
- .await?;
+ pdi_table = tables.person_distinct_id,
+ );
+ let tombstoned: Vec<(i64, String, i64)> = sqlx::query_as(&tombstone_pdi_sql)
+ .bind(team_id)
+ .bind(&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.
@@ -419,8 +434,10 @@ async fn unmap(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
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}))
+ .filter(|(person_id, _, _)| person_id == victim)
+ .map(|(_, distinct_id, version)| {
+ serde_json::json!({"distinct_id": distinct_id, "version": version})
+ })
.collect();
if !rows.is_empty() {
moved_ids.push(*victim);
@@ -443,38 +460,48 @@ async fn unmap(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
.await?;
}
- sqlx::query!(
- "DELETE FROM posthog_cohortpeople WHERE person_id = ANY($1)",
- &victims
- )
- .execute(&mut *tx)
- .await?;
+ // posthog_cohortpeople has no shadow mirror and no team_id column, so it
+ // is only addressable by real posthog_person ids. On any other person
+ // table the victim ids come from that table's own sequence and would
+ // collide with unrelated persons' cohort rows — skip the clear entirely.
+ if tables.person == "posthog_person" {
+ 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?;
+ let delete_overrides_sql = format!(
+ "DELETE FROM {} WHERE team_id = $1 AND person_id = ANY($2)",
+ tables.ff_hash_key_override
+ );
+ sqlx::query(&delete_overrides_sql)
+ .bind(team_id)
+ .bind(&victims)
+ .execute(&mut *tx)
+ .await?;
- sqlx::query!(
+ let tombstone_sql = format!(
r#"
- UPDATE posthog_person p
+ UPDATE {person_table} p
SET is_deleted = true,
- properties = '{}'::jsonb,
- properties_last_updated_at = '{}'::jsonb,
- properties_last_operation = '{}'::jsonb,
+ 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?;
+ person_table = tables.person,
+ );
+ sqlx::query(&tombstone_sql)
+ .bind(op.op_id)
+ .bind(team_id)
+ .execute(&mut *tx)
+ .await?;
if !advance_step_in_tx(
&mut tx,
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 83544f10d79c..4e434754aabe 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -47,6 +47,7 @@ use personhog_proto::personhog::types::v1::{
ReleaseOutcome, SealedSourceSnapshot,
};
+use crate::config::IdentityTables;
use crate::leader::LifecycleLeader;
use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
@@ -237,11 +238,13 @@ struct SealedSnapshot {
pub struct MergeDriver {
leader: Arc<dyn LifecycleLeader>,
+ tables: IdentityTables,
}
impl MergeDriver {
- pub fn new(leader: Arc<dyn LifecycleLeader>) -> Self {
- Self { leader }
+ pub fn new(leader: Arc<dyn LifecycleLeader>, tables: IdentityTables) -> Self {
+ tables.validate().expect("invalid identity table set");
+ Self { leader, tables }
}
}
@@ -266,7 +269,7 @@ impl OpDriver for MergeDriver {
MergeStep::Started => self.claim(pool, op).await,
MergeStep::Claimed => self.seal(pool, op).await,
MergeStep::SourcesSealed => self.fold(pool, op).await,
- MergeStep::DocumentFolded => flip(pool, op).await,
+ MergeStep::DocumentFolded => flip(pool, &self.tables, op).await,
MergeStep::Flipped => self.complete(pool, op).await,
}
}
@@ -340,32 +343,35 @@ fn reconcile_pending_claims(
async fn resolve_dids(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
team_id: i32,
dids: &[String],
) -> Result<HashMap<String, Resolution>, SagaError> {
- let rows = sqlx::query!(
+ let resolve_sql = format!(
r#"
- SELECT d.distinct_id, d.person_id as "person_id!", p.uuid as "person_uuid!",
- p.is_identified as "is_identified!"
- FROM posthog_persondistinctid d
- JOIN posthog_person p ON p.team_id = d.team_id AND p.id = d.person_id
+ SELECT d.distinct_id, d.person_id, p.uuid, p.is_identified
+ FROM {pdi_table} d
+ JOIN {person_table} p ON p.team_id = d.team_id AND p.id = d.person_id
WHERE d.team_id = $1 AND d.distinct_id = ANY($2)
AND d.is_deleted = false AND p.is_deleted = false
"#,
- team_id,
- dids,
- )
- .fetch_all(&mut **tx)
- .await?;
+ pdi_table = tables.person_distinct_id,
+ person_table = tables.person,
+ );
+ let rows: Vec<(String, i64, Uuid, bool)> = sqlx::query_as(&resolve_sql)
+ .bind(team_id)
+ .bind(dids)
+ .fetch_all(&mut **tx)
+ .await?;
Ok(rows
.into_iter()
- .map(|r| {
+ .map(|(distinct_id, person_id, person_uuid, is_identified)| {
(
- r.distinct_id,
+ distinct_id,
Resolution {
- person_id: r.person_id,
- person_uuid: r.person_uuid,
- is_identified: r.is_identified,
+ person_id,
+ person_uuid,
+ is_identified,
},
)
})
@@ -390,7 +396,7 @@ impl MergeDriver {
all_dids.extend(request.sources.iter().map(|s| s.distinct_id.clone()));
all_dids.sort_unstable();
all_dids.dedup();
- let resolved = resolve_dids(&mut tx, team_id, &all_dids).await?;
+ let resolved = resolve_dids(&mut tx, &self.tables, team_id, &all_dids).await?;
let Some(target) = resolved.get(&request.target_distinct_id) else {
// The target person vanished between classification and now. The
@@ -464,15 +470,15 @@ impl MergeDriver {
// candidate's scan at limit+1 rows, so an oversized person cannot
// blow the statement timeout.
let candidate_ids: Vec<i64> = claim_persons.iter().map(|(id, _, _)| *id).collect();
- let over: Vec<i64> = sqlx::query_scalar!(
+ let over_sql = format!(
r#"
- SELECT c.person_id AS "person_id!"
+ SELECT c.person_id
FROM unnest($2::bigint[]) AS c(person_id)
WHERE (
SELECT count(*)
FROM (
SELECT 1
- FROM posthog_persondistinctid d
+ FROM {pdi_table} d
WHERE d.team_id = $1
AND d.person_id = c.person_id
AND d.is_deleted = false
@@ -480,12 +486,14 @@ impl MergeDriver {
) capped
) > $3::bigint
"#,
- team_id,
- &candidate_ids,
- request.move_limit,
- )
- .fetch_all(&mut *tx)
- .await?;
+ pdi_table = self.tables.person_distinct_id,
+ );
+ let over: Vec<i64> = sqlx::query_scalar(&over_sql)
+ .bind(team_id)
+ .bind(&candidate_ids)
+ .bind(request.move_limit)
+ .fetch_all(&mut *tx)
+ .await?;
if !over.is_empty() {
claim_persons.retain(|(id, _, _)| !over.contains(id));
for d in dispositions.iter_mut() {
@@ -596,7 +604,7 @@ impl MergeDriver {
// mapping stability; after it, mark + liveness hold in one snapshot
// and nothing can destroy or re-map a claimed person (the mark
// blocks every lifecycle op and identity mutation).
- let fresh = resolve_dids(&mut tx, team_id, &all_dids).await?;
+ let fresh = resolve_dids(&mut tx, &self.tables, team_id, &all_dids).await?;
let target_still_live = fresh
.get(&request.target_distinct_id)
.is_some_and(|r| r.person_id == target_person_id);
@@ -1233,7 +1241,7 @@ fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {
/// hash-key overrides target-wins, scrub and tombstone the source person
/// rows at their exact death versions, and clear the target's mark. The
/// source marks stay: they are the fences' durable record until release.
-async fn flip(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
let mut tx = pool.begin().await?;
@@ -1260,11 +1268,11 @@ async fn flip(pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
.await?;
sources.sort_unstable();
- let repointed = repoint_distinct_ids(&mut tx, team_id, &sources, target).await?;
+ let repointed = repoint_distinct_ids(&mut tx, tables, team_id, &sources, target).await?;
record_moved_mappings(&mut tx, op, &sources, &repointed).await?;
- move_cohort_membership(&mut tx, &sources, target).await?;
- move_hash_key_overrides(&mut tx, team_id, &sources, target).await?;
- tombstone_sealed_sources(&mut tx, op, team_id).await?;
+ move_cohort_membership(&mut tx, tables, &sources, target).await?;
+ move_hash_key_overrides(&mut tx, tables, team_id, &sources, target).await?;
+ tombstone_sealed_sources(&mut tx, tables, op, team_id).await?;
clear_target_mark(&mut tx, op).await?;
if !advance_step_in_tx(
@@ -1298,6 +1306,7 @@ struct RepointedDid {
/// each row's version.
async fn repoint_distinct_ids(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
team_id: i32,
sources: &[i64],
target: i64,
@@ -1305,27 +1314,29 @@ async fn repoint_distinct_ids(
// RETURNING sees the post-update row, so the pre-update owner has to
// come from a self-join snapshot — without it every returned
// person_id would be the target.
- let rows = sqlx::query!(
+ let repoint_sql = format!(
r#"
- UPDATE posthog_persondistinctid pdi
+ UPDATE {pdi_table} pdi
SET person_id = $3, version = COALESCE(pdi.version, 0) + 1
- FROM posthog_persondistinctid old
+ FROM {pdi_table} old
WHERE old.id = pdi.id
AND pdi.team_id = $1 AND pdi.person_id = ANY($2) AND pdi.is_deleted = false
- RETURNING old.person_id as "old_person_id!", pdi.distinct_id, pdi.version as "version!"
+ RETURNING old.person_id, pdi.distinct_id, pdi.version
"#,
- team_id,
- sources,
- target,
- )
- .fetch_all(&mut **tx)
- .await?;
+ pdi_table = tables.person_distinct_id,
+ );
+ let rows: Vec<(i64, String, i64)> = sqlx::query_as(&repoint_sql)
+ .bind(team_id)
+ .bind(sources)
+ .bind(target)
+ .fetch_all(&mut **tx)
+ .await?;
Ok(rows
.into_iter()
- .map(|r| RepointedDid {
- old_person_id: r.old_person_id,
- distinct_id: r.distinct_id,
- version: r.version,
+ .map(|(old_person_id, distinct_id, version)| RepointedDid {
+ old_person_id,
+ distinct_id,
+ version,
})
.collect())
}
@@ -1376,9 +1387,17 @@ async fn record_moved_mappings(
/// recalculation heals the rare duplicate.
async fn move_cohort_membership(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
sources: &[i64],
target: i64,
) -> Result<(), SagaError> {
+ // posthog_cohortpeople has no shadow mirror and no team_id column, so it
+ // is only addressable by real posthog_person ids. On any other person
+ // table the source ids come from that table's own sequence and would
+ // collide with unrelated persons' cohort rows — skip the move entirely.
+ if tables.person != "posthog_person" {
+ return Ok(());
+ }
sqlx::query!(
"UPDATE posthog_cohortpeople SET person_id = $2 WHERE person_id = ANY($1)",
sources,
@@ -1393,27 +1412,30 @@ async fn move_cohort_membership(
/// for a flag beats any source's.
async fn move_hash_key_overrides(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
team_id: i32,
sources: &[i64],
target: i64,
) -> Result<(), SagaError> {
- sqlx::query!(
+ let move_sql = format!(
r#"
WITH removed AS (
- DELETE FROM posthog_featureflaghashkeyoverride
+ DELETE FROM {override_table}
WHERE team_id = $1 AND person_id = ANY($2)
RETURNING feature_flag_key, hash_key
)
- INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)
+ INSERT INTO {override_table} (team_id, person_id, feature_flag_key, hash_key)
SELECT $1, $3, feature_flag_key, hash_key FROM removed
ON CONFLICT (team_id, person_id, feature_flag_key) DO NOTHING
"#,
- team_id,
- sources,
- target,
- )
- .execute(&mut **tx)
- .await?;
+ override_table = tables.ff_hash_key_override,
+ );
+ sqlx::query(&move_sql)
+ .bind(team_id)
+ .bind(sources)
+ .bind(target)
+ .execute(&mut **tx)
+ .await?;
Ok(())
}
@@ -1425,28 +1447,31 @@ async fn move_hash_key_overrides(
/// does not consult the leader's emitted-version floor today.
async fn tombstone_sealed_sources(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op: &OpRow,
team_id: i32,
) -> Result<(), SagaError> {
- sqlx::query!(
+ let tombstone_sql = format!(
r#"
- UPDATE posthog_person p
+ UPDATE {person_table} p
SET is_deleted = true,
- properties = '{}'::jsonb,
- properties_last_updated_at = '{}'::jsonb,
- properties_last_operation = '{}'::jsonb,
+ properties = '{{}}'::jsonb,
+ properties_last_updated_at = '{{}}'::jsonb,
+ properties_last_operation = '{{}}'::jsonb,
version = (lop.sealed->>'version')::bigint + 1
FROM lifecycle_op_person lop
WHERE lop.op_id = $1 AND lop.role = $3 AND lop.status = $4
AND p.team_id = $2 AND p.id = lop.person_id
"#,
- op.op_id,
- team_id,
- ROLE_SOURCE,
- STATUS_SEALED,
- )
- .execute(&mut **tx)
- .await?;
+ person_table = tables.person,
+ );
+ sqlx::query(&tombstone_sql)
+ .bind(op.op_id)
+ .bind(team_id)
+ .bind(ROLE_SOURCE)
+ .bind(STATUS_SEALED)
+ .execute(&mut **tx)
+ .await?;
Ok(())
}
diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rs
index 7ddf7bb80d42..660a837fbae1 100644
--- a/rust/personhog-identity/src/lifecycle/mod.rs
+++ b/rust/personhog-identity/src/lifecycle/mod.rs
@@ -35,10 +35,10 @@ pub struct PersonHogLifecycleService {
}
impl PersonHogLifecycleService {
- pub fn new(engine: Arc<Engine>) -> Self {
+ pub fn new(engine: Arc<Engine>, tables: crate::config::IdentityTables) -> Self {
Self {
engine,
- delete_driver: DeleteDriver,
+ delete_driver: DeleteDriver::new(tables),
}
}
}
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 3f5899d3a32c..47f82100190b 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -44,7 +44,7 @@ fn create_storage(config: &Config) -> Arc<PostgresIdentityStorage> {
.expect("Failed to create primary database pool");
tracing::info!("Created primary database pool");
- Arc::new(PostgresIdentityStorage::new(primary_pool))
+ Arc::new(PostgresIdentityStorage::new(primary_pool, config.tables()))
}
#[tokio::main]
@@ -65,10 +65,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.init();
+ config
+ .tables()
+ .validate()
+ .expect("Invalid identity table set");
+
tracing::info!("Starting personhog-identity service");
tracing::info!("gRPC address: {}", config.grpc_address);
tracing::info!("Metrics port: {}", config.metrics_port);
tracing::info!("Router URL: {}", config.router_url);
+ tracing::info!("Tables: {:?}", config.tables());
// Build lifecycle manager and register components
let mut manager = Manager::builder("personhog-identity").build();
@@ -184,8 +190,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.lifecycle_engine_config(),
));
if let Some(sweeper_handle) = sweeper_handle {
- let sweeper_merge_driver = MergeDriver::new(property_writer.clone());
+ let sweeper_merge_driver = MergeDriver::new(property_writer.clone(), config.tables());
let sweeper_engine = engine.clone();
+ let sweeper_driver = DeleteDriver::new(config.tables());
let sweep_interval = config.lifecycle_sweep_interval();
let retention = config.lifecycle_op_retention();
tracing::info!(
@@ -206,7 +213,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
_ = ticker.tick() => {}
}
match sweeper_engine
- .sweep(&[&DeleteDriver, &sweeper_merge_driver])
+ .sweep(&[&sweeper_driver, &sweeper_merge_driver])
.await
{
Ok(resumed) if resumed > 0 => {
@@ -225,7 +232,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(engine);
+ let lifecycle_service = PersonHogLifecycleService::new(engine, config.tables());
let grpc_addr = config.grpc_address;
let keepalive_interval = config.grpc_keepalive_interval();
diff --git a/rust/personhog-identity/src/storage/postgres/distinct_ids.rs b/rust/personhog-identity/src/storage/postgres/distinct_ids.rs
index 12ae1b3f4112..5514bda7844f 100644
--- a/rust/personhog-identity/src/storage/postgres/distinct_ids.rs
+++ b/rust/personhog-identity/src/storage/postgres/distinct_ids.rs
@@ -1,4 +1,5 @@
use sqlx::postgres::PgPool;
+use sqlx::Row;
use crate::storage::error::StorageResult;
use crate::storage::types::DistinctIdMapping;
@@ -10,6 +11,7 @@ use crate::storage::types::DistinctIdMapping;
/// expansion, so callers can switch sources without behavior change.
pub(super) async fn get_distinct_ids_for_persons(
pool: &PgPool,
+ pdi_table: &str,
team_id: i64,
person_ids: &[i64],
limit_per_person: Option<i64>,
@@ -20,8 +22,7 @@ pub(super) async fn get_distinct_ids_for_persons(
let rows = match limit_per_person {
Some(limit) if limit > 0 => {
- sqlx::query_as!(
- DistinctIdMapping,
+ let sql = format!(
r#"
SELECT l.person_id, l.distinct_id, l.version
FROM UNNEST($2::bigint[]) AS pid(id)
@@ -29,35 +30,44 @@ pub(super) async fn get_distinct_ids_for_persons(
SELECT capped.person_id, capped.distinct_id, capped.version
FROM (
SELECT person_id, distinct_id, version, id
- FROM posthog_persondistinctid
+ FROM {pdi_table}
WHERE team_id = $1 AND person_id = pid.id AND is_deleted = false
LIMIT 2500
) capped
- ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id
+ ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){{4}}[a-z0-9]+$'), capped.id
LIMIT $3
) l
- "#,
- team_id as i32,
- person_ids,
- limit
- )
- .fetch_all(pool)
- .await?
+ "#
+ );
+ sqlx::query(&sql)
+ .bind(team_id as i32)
+ .bind(person_ids)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?
}
_ => {
- sqlx::query_as!(
- DistinctIdMapping,
+ let sql = format!(
r#"
SELECT person_id, distinct_id, version
- FROM posthog_persondistinctid
+ FROM {pdi_table}
WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false
- "#,
- team_id as i32,
- person_ids
- )
- .fetch_all(pool)
- .await?
+ "#
+ );
+ sqlx::query(&sql)
+ .bind(team_id as i32)
+ .bind(person_ids)
+ .fetch_all(pool)
+ .await?
}
};
- Ok(rows)
+ rows.into_iter()
+ .map(|row| {
+ Ok(DistinctIdMapping {
+ person_id: row.try_get("person_id")?,
+ distinct_id: row.try_get("distinct_id")?,
+ version: row.try_get("version")?,
+ })
+ })
+ .collect()
}
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index eef74adaf487..c7d17182c392 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -9,23 +9,65 @@ mod stub_create;
use std::collections::HashMap;
use async_trait::async_trait;
-use sqlx::postgres::PgPool;
+use sqlx::postgres::{PgPool, PgRow};
+use sqlx::Row;
use personhog_common::grpc::{current_client_name, current_method_name};
+use crate::config::IdentityTables;
use crate::storage::error::StorageResult;
use crate::storage::types::{DistinctIdMapping, Person, PersonStub, StubOutcome};
use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
const POOL_LABEL: &str = "primary";
+/// Decode a person from a row whose SELECT list uses the canonical aliases
+/// (`team_id::bigint AS team_id`, `properties::text AS properties`, the
+/// `is_user_id` boolean CASE, …). Shared by every submodule that selects
+/// person rows — the table name is interpolated at runtime, so the queries
+/// cannot use the compile-time sqlx macros and their generated row types.
+pub(super) fn person_from_row(row: &PgRow) -> Result<Person, sqlx::Error> {
+ Ok(Person {
+ id: row.try_get("id")?,
+ uuid: row.try_get("uuid")?,
+ team_id: row.try_get("team_id")?,
+ properties: row.try_get("properties")?,
+ properties_last_updated_at: row.try_get("properties_last_updated_at")?,
+ properties_last_operation: row.try_get("properties_last_operation")?,
+ created_at: row.try_get("created_at")?,
+ version: row.try_get("version")?,
+ is_identified: row.try_get("is_identified")?,
+ is_user_id: row.try_get("is_user_id")?,
+ last_seen_at: row.try_get("last_seen_at")?,
+ })
+}
+
+/// The person-column SELECT list matching [`person_from_row`], with `{p}` as
+/// the table alias.
+pub(super) fn person_columns(p: &str) -> String {
+ format!(
+ "{p}.id, {p}.uuid, {p}.team_id::bigint AS team_id, \
+ {p}.properties::text AS properties, \
+ {p}.properties_last_updated_at::text AS properties_last_updated_at, \
+ {p}.properties_last_operation::text AS properties_last_operation, \
+ {p}.created_at, {p}.version, {p}.is_identified, \
+ CASE WHEN {p}.is_user_id IS NULL THEN NULL ELSE ({p}.is_user_id != 0) END AS is_user_id, \
+ {p}.last_seen_at"
+ )
+}
+
pub struct PostgresIdentityStorage {
pub primary_pool: PgPool,
+ tables: IdentityTables,
}
impl PostgresIdentityStorage {
- pub fn new(primary_pool: PgPool) -> Self {
- Self { primary_pool }
+ pub fn new(primary_pool: PgPool, tables: IdentityTables) -> Self {
+ tables.validate().expect("invalid identity table set");
+ Self {
+ primary_pool,
+ tables,
+ }
}
fn query_labels(operation: &str) -> [(String, String); 4] {
@@ -46,7 +88,7 @@ impl IdentityStorage for PostgresIdentityStorage {
) -> StorageResult<HashMap<(i64, String), Person>> {
let labels = Self::query_labels("resolve_distinct_ids");
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- resolve::resolve_distinct_ids(&self.primary_pool, keys).await
+ resolve::resolve_distinct_ids(&self.primary_pool, &self.tables, keys).await
}
async fn get_distinct_ids_for_persons(
@@ -59,6 +101,7 @@ impl IdentityStorage for PostgresIdentityStorage {
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
distinct_ids::get_distinct_ids_for_persons(
&self.primary_pool,
+ &self.tables.person_distinct_id,
team_id,
person_ids,
limit_per_person,
@@ -69,6 +112,6 @@ impl IdentityStorage for PostgresIdentityStorage {
async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {
let labels = Self::query_labels("create_person_stubs");
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- stub_create::create_person_stubs(&self.primary_pool, stubs).await
+ stub_create::create_person_stubs(&self.primary_pool, &self.tables, stubs).await
}
}
diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rs
index be3f8c5d51d0..0e68bd785edf 100644
--- a/rust/personhog-identity/src/storage/postgres/resolve.rs
+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs
@@ -1,8 +1,11 @@
use std::collections::HashMap;
use sqlx::postgres::PgPool;
+use sqlx::Row;
+use crate::config::IdentityTables;
use crate::storage::error::StorageResult;
+use crate::storage::postgres::{person_columns, person_from_row};
use crate::storage::types::Person;
/// Batch-resolve (team_id, distinct_id) keys to their live persons on the
@@ -10,6 +13,7 @@ use crate::storage::types::Person;
/// are absent from the result.
pub(super) async fn resolve_distinct_ids(
pool: &PgPool,
+ tables: &IdentityTables,
keys: &[(i64, String)],
) -> StorageResult<HashMap<(i64, String), Person>> {
if keys.is_empty() {
@@ -19,47 +23,35 @@ pub(super) async fn resolve_distinct_ids(
let team_ids: Vec<i32> = keys.iter().map(|(t, _)| *t as i32).collect();
let distinct_ids: Vec<String> = keys.iter().map(|(_, d)| d.clone()).collect();
- let rows = sqlx::query!(
+ let sql = format!(
r#"
- SELECT k.team_id as "key_team_id!", k.distinct_id as "key_distinct_id!",
- p.id as "id!", p.uuid as "uuid!", p.team_id::bigint as "team_id!",
- p.properties::text as "properties?",
- p.properties_last_updated_at::text as "properties_last_updated_at?",
- p.properties_last_operation::text as "properties_last_operation?",
- p.created_at as "created_at!", p.version, p.is_identified as "is_identified!",
- CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,
- p.last_seen_at
+ SELECT k.team_id AS key_team_id, k.distinct_id AS key_distinct_id,
+ {person_cols}
FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)
- JOIN posthog_persondistinctid pdi
+ JOIN {pdi_table} pdi
ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id
AND pdi.is_deleted = false
- JOIN posthog_person p
+ JOIN {person_table} p
ON p.team_id = pdi.team_id AND p.id = pdi.person_id
AND p.is_deleted = false
"#,
- &team_ids,
- &distinct_ids
- )
- .fetch_all(pool)
- .await?;
+ person_cols = person_columns("p"),
+ pdi_table = tables.person_distinct_id,
+ person_table = tables.person,
+ );
+ let rows = sqlx::query(&sql)
+ .bind(&team_ids)
+ .bind(&distinct_ids)
+ .fetch_all(pool)
+ .await?;
let mut resolved = HashMap::with_capacity(rows.len());
for row in rows {
+ let key_team_id: i32 = row.try_get("key_team_id")?;
+ let key_distinct_id: String = row.try_get("key_distinct_id")?;
resolved.insert(
- (i64::from(row.key_team_id), row.key_distinct_id),
- Person {
- id: row.id,
- uuid: row.uuid,
- team_id: row.team_id,
- properties: row.properties,
- properties_last_updated_at: row.properties_last_updated_at,
- properties_last_operation: row.properties_last_operation,
- created_at: row.created_at,
- version: row.version,
- is_identified: row.is_identified,
- is_user_id: row.is_user_id,
- last_seen_at: row.last_seen_at,
- },
+ (i64::from(key_team_id), key_distinct_id),
+ person_from_row(&row)?,
);
}
Ok(resolved)
diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rs
index bd2173ce3af6..0b22682b1688 100644
--- a/rust/personhog-identity/src/storage/postgres/stub_create.rs
+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs
@@ -27,11 +27,14 @@ use std::collections::{HashMap, HashSet};
use chrono::{DateTime, Utc};
use sqlx::postgres::PgPool;
+use sqlx::Row;
use uuid::Uuid;
use personhog_common::persons::person_uuid;
+use crate::config::IdentityTables;
use crate::storage::error::StorageResult;
+use crate::storage::postgres::{person_columns, person_from_row};
use crate::storage::types::{Person, PersonStub, StubOutcome};
type Tx<'a> = sqlx::Transaction<'a, sqlx::Postgres>;
@@ -65,6 +68,7 @@ struct MappingOutcome {
pub(super) async fn create_person_stubs(
pool: &PgPool,
+ tables: &IdentityTables,
stubs: &[PersonStub],
) -> StorageResult<Vec<StubOutcome>> {
if stubs.is_empty() {
@@ -81,10 +85,22 @@ pub(super) async fn create_person_stubs(
let mut tx = pool.begin().await?;
- let mut persons = insert_or_revive_persons(&mut tx, stubs, &team_ids, &uuids).await?;
- fetch_conflict_winners(&mut tx, stubs, &team_ids, &uuids, &mut persons).await?;
- let mapping = insert_distinct_id_mappings(&mut tx, stubs, &uuids, &persons).await?;
- let outcomes = resolve_stub_outcomes(&mut tx, stubs, &uuids, &persons, &mapping).await?;
+ let mut persons =
+ insert_or_revive_persons(&mut tx, &tables.person, stubs, &team_ids, &uuids).await?;
+ fetch_conflict_winners(
+ &mut tx,
+ &tables.person,
+ stubs,
+ &team_ids,
+ &uuids,
+ &mut persons,
+ )
+ .await?;
+ let mapping =
+ insert_distinct_id_mappings(&mut tx, &tables.person_distinct_id, stubs, &uuids, &persons)
+ .await?;
+ let outcomes =
+ resolve_stub_outcomes(&mut tx, tables, stubs, &uuids, &persons, &mapping).await?;
tx.commit().await?;
Ok(outcomes)
@@ -103,6 +119,7 @@ pub(super) async fn create_person_stubs(
/// (xmax can't be read back from a partitioned table).
async fn insert_or_revive_persons(
tx: &mut Tx<'_>,
+ person_table: &str,
stubs: &[PersonStub],
team_ids: &[i32],
uuids: &[Uuid],
@@ -118,67 +135,51 @@ async fn insert_or_revive_persons(
let sorted_is_identified: Vec<bool> = order.iter().map(|&i| stubs[i].is_identified).collect();
let sorted_uuids: Vec<Uuid> = order.iter().map(|&i| uuids[i]).collect();
- let inserted = sqlx::query!(
+ let sql = format!(
r#"
- INSERT INTO posthog_person
+ INSERT INTO {person_table}
(created_at, properties, properties_last_updated_at, properties_last_operation,
team_id, is_identified, uuid, version, last_seen_at)
- SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
+ SELECT u.created_at, '{{}}'::jsonb, '{{}}'::jsonb, '{{}}'::jsonb,
u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)
FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])
AS u(created_at, team_id, is_identified, uuid)
ON CONFLICT (team_id, uuid) DO UPDATE SET
is_deleted = false,
- version = COALESCE(posthog_person.version, 0) + 1,
- properties = '{}'::jsonb,
- properties_last_updated_at = '{}'::jsonb,
- properties_last_operation = '{}'::jsonb,
+ version = COALESCE({person_table}.version, 0) + 1,
+ properties = '{{}}'::jsonb,
+ properties_last_updated_at = '{{}}'::jsonb,
+ properties_last_operation = '{{}}'::jsonb,
created_at = EXCLUDED.created_at,
is_identified = EXCLUDED.is_identified,
last_seen_at = EXCLUDED.last_seen_at
- WHERE posthog_person.is_deleted = true
- RETURNING id, uuid, team_id::bigint as "team_id!", properties::text as "properties?",
- properties_last_updated_at::text as "properties_last_updated_at?",
- properties_last_operation::text as "properties_last_operation?",
- created_at, version, is_identified,
- CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
- last_seen_at
+ WHERE {person_table}.is_deleted = true
+ RETURNING {person_cols}
"#,
- &sorted_created_ats,
- &sorted_team_ids,
- &sorted_is_identified,
- &sorted_uuids
- )
- .fetch_all(&mut **tx)
- .await?;
+ person_cols = person_columns(person_table),
+ );
+ let inserted = sqlx::query(&sql)
+ .bind(&sorted_created_ats)
+ .bind(&sorted_team_ids)
+ .bind(&sorted_is_identified)
+ .bind(&sorted_uuids)
+ .fetch_all(&mut **tx)
+ .await?;
- Ok(inserted
- .into_iter()
- .map(|row| {
- let revived_tombstone = row.version != Some(0);
- let person = Person {
- id: row.id,
- uuid: row.uuid,
- team_id: row.team_id,
- properties: row.properties,
- properties_last_updated_at: row.properties_last_updated_at,
- properties_last_operation: row.properties_last_operation,
- created_at: row.created_at,
- version: row.version,
- is_identified: row.is_identified,
- is_user_id: row.is_user_id,
- last_seen_at: row.last_seen_at,
- };
- (
- (person.team_id, person.uuid),
- ResolvedPerson {
- person,
- created_by_us: true,
- revived_tombstone,
- },
- )
- })
- .collect())
+ let mut persons = PersonsByKey::with_capacity(inserted.len());
+ for row in inserted {
+ let person = person_from_row(&row)?;
+ let revived_tombstone = person.version != Some(0);
+ persons.insert(
+ (person.team_id, person.uuid),
+ ResolvedPerson {
+ person,
+ created_by_us: true,
+ revived_tombstone,
+ },
+ );
+ }
+ Ok(persons)
}
/// Step 2: batch-fetch the committed winners for conflicted keys. This must
@@ -186,6 +187,7 @@ async fn insert_or_revive_persons(
/// winner's commit, a fresh statement snapshot sees it.
async fn fetch_conflict_winners(
tx: &mut Tx<'_>,
+ person_table: &str,
stubs: &[PersonStub],
team_ids: &[i32],
uuids: &[Uuid],
@@ -200,27 +202,23 @@ async fn fetch_conflict_winners(
let conflicted_teams: Vec<i32> = conflicted.iter().map(|&i| team_ids[i]).collect();
let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|&i| uuids[i]).collect();
- let winners = sqlx::query_as!(
- Person,
+ let sql = format!(
r#"
- SELECT p.id as "id!", p.uuid as "uuid!", p.team_id::bigint as "team_id!",
- p.properties::text as "properties?",
- p.properties_last_updated_at::text as "properties_last_updated_at?",
- p.properties_last_operation::text as "properties_last_operation?",
- p.created_at as "created_at!", p.version, p.is_identified as "is_identified!",
- CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END as is_user_id,
- p.last_seen_at
- FROM posthog_person p
+ SELECT {person_cols}
+ FROM {person_table} p
JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)
ON p.team_id = k.team_id AND p.uuid = k.uuid
WHERE p.is_deleted = false
"#,
- &conflicted_teams,
- &conflicted_uuids
- )
- .fetch_all(&mut **tx)
- .await?;
- for winner in winners {
+ person_cols = person_columns("p"),
+ );
+ let winners = sqlx::query(&sql)
+ .bind(&conflicted_teams)
+ .bind(&conflicted_uuids)
+ .fetch_all(&mut **tx)
+ .await?;
+ for row in winners {
+ let winner = person_from_row(&row)?;
persons.insert(
(winner.team_id, winner.uuid),
ResolvedPerson {
@@ -247,6 +245,7 @@ async fn fetch_conflict_winners(
/// never re-pointed here, and not an error (a retry could never succeed).
async fn insert_distinct_id_mappings(
tx: &mut Tx<'_>,
+ pdi_table: &str,
stubs: &[PersonStub],
uuids: &[Uuid],
persons: &PersonsByKey,
@@ -285,35 +284,36 @@ async fn insert_distinct_id_mappings(
return Ok(mapping);
}
- let rows = sqlx::query!(
+ let sql = format!(
r#"
- INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ INSERT INTO {pdi_table} (distinct_id, person_id, team_id, version)
SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])
AS u(d, p, t, v)
ON CONFLICT (team_id, distinct_id) DO UPDATE SET
person_id = EXCLUDED.person_id,
- version = COALESCE(posthog_persondistinctid.version, 0) + 1,
+ version = COALESCE({pdi_table}.version, 0) + 1,
is_deleted = false
- WHERE posthog_persondistinctid.is_deleted = true
- RETURNING team_id::bigint as "team_id!", distinct_id, person_id,
- (xmax = 0) as "inserted!"
- "#,
- &pdi_dids,
- &pdi_person_ids,
- &pdi_teams,
- &pdi_versions
- )
- .fetch_all(&mut **tx)
- .await?;
+ WHERE {pdi_table}.is_deleted = true
+ RETURNING team_id::bigint AS team_id, distinct_id, person_id,
+ (xmax = 0) AS inserted
+ "#
+ );
+ let rows = sqlx::query(&sql)
+ .bind(&pdi_dids)
+ .bind(&pdi_person_ids)
+ .bind(&pdi_teams)
+ .bind(&pdi_versions)
+ .fetch_all(&mut **tx)
+ .await?;
for row in rows {
- if !row.inserted {
- mapping
- .revived
- .insert((row.team_id, row.distinct_id.clone()));
+ let team_id: i64 = row.try_get("team_id")?;
+ let distinct_id: String = row.try_get("distinct_id")?;
+ let person_id: i64 = row.try_get("person_id")?;
+ let inserted: bool = row.try_get("inserted")?;
+ if !inserted {
+ mapping.revived.insert((team_id, distinct_id.clone()));
}
- mapping
- .written
- .insert((row.team_id, row.distinct_id), row.person_id);
+ mapping.written.insert((team_id, distinct_id), person_id);
}
Ok(mapping)
}
@@ -325,6 +325,7 @@ async fn insert_distinct_id_mappings(
/// stub doesn't linger orphaned.
async fn resolve_stub_outcomes(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
stubs: &[PersonStub],
uuids: &[Uuid],
persons: &PersonsByKey,
@@ -345,19 +346,21 @@ async fn resolve_stub_outcomes(
continue;
}
if resolved.created_by_us {
- undo_created_person(tx, stub.team_id, resolved, mapping).await?;
+ undo_created_person(tx, tables, stub.team_id, resolved, mapping).await?;
outcomes.push(StubOutcome::LostRace);
continue;
}
// The person pre-existed and its primary mapping wasn't inserted by
// us — verify the existing mapping points at this person.
- let existing = sqlx::query_scalar!(
- "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2 AND is_deleted = false",
- stub.team_id as i32,
- &stub.distinct_id
- )
- .fetch_optional(&mut **tx)
- .await?;
+ let existing_sql = format!(
+ "SELECT person_id FROM {} WHERE team_id = $1 AND distinct_id = $2 AND is_deleted = false",
+ tables.person_distinct_id
+ );
+ let existing: Option<i64> = sqlx::query_scalar(&existing_sql)
+ .bind(stub.team_id as i32)
+ .bind(&stub.distinct_id)
+ .fetch_optional(&mut **tx)
+ .await?;
if existing == Some(resolved.person.id) {
outcomes.push(StubOutcome::Committed {
person: resolved.person.clone(),
@@ -377,10 +380,13 @@ async fn resolve_stub_outcomes(
/// fresh-row sweep distinguish them by is_deleted.
async fn undo_created_person(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
team_id: i64,
resolved: &ResolvedPerson,
mapping: &MappingOutcome,
) -> StorageResult<()> {
+ let person_table = &tables.person;
+ let pdi_table = &tables.person_distinct_id;
let revived_dids: Vec<String> = mapping
.written
.iter()
@@ -392,46 +398,48 @@ async fn undo_created_person(
.map(|((_, d), _)| d.clone())
.collect();
if !revived_dids.is_empty() {
- sqlx::query!(
+ let retombstone_sql = format!(
r#"
- UPDATE posthog_persondistinctid
+ UPDATE {pdi_table}
SET is_deleted = true, version = COALESCE(version, 0) + 1
WHERE team_id = $1 AND distinct_id = ANY($2)
- "#,
- team_id as i32,
- &revived_dids
- )
+ "#
+ );
+ sqlx::query(&retombstone_sql)
+ .bind(team_id as i32)
+ .bind(&revived_dids)
+ .execute(&mut **tx)
+ .await?;
+ }
+ let delete_mappings_sql = format!(
+ "DELETE FROM {pdi_table} WHERE team_id = $1 AND person_id = $2 AND is_deleted = false"
+ );
+ sqlx::query(&delete_mappings_sql)
+ .bind(team_id as i32)
+ .bind(resolved.person.id)
.execute(&mut **tx)
.await?;
- }
- sqlx::query!(
- "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2 AND is_deleted = false",
- team_id as i32,
- resolved.person.id
- )
- .execute(&mut **tx)
- .await?;
if resolved.revived_tombstone {
- sqlx::query!(
+ let sql = format!(
r#"
- UPDATE posthog_person
+ UPDATE {person_table}
SET is_deleted = true, version = COALESCE(version, 0) + 1,
- properties = '{}'::jsonb
+ properties = '{{}}'::jsonb
WHERE team_id = $1 AND id = $2
- "#,
- team_id as i32,
- resolved.person.id
- )
- .execute(&mut **tx)
- .await?;
+ "#
+ );
+ sqlx::query(&sql)
+ .bind(team_id as i32)
+ .bind(resolved.person.id)
+ .execute(&mut **tx)
+ .await?;
} else {
- sqlx::query!(
- "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",
- team_id as i32,
- resolved.person.id
- )
- .execute(&mut **tx)
- .await?;
+ let sql = format!("DELETE FROM {person_table} WHERE team_id = $1 AND id = $2");
+ sqlx::query(&sql)
+ .bind(team_id as i32)
+ .bind(resolved.person.id)
+ .execute(&mut **tx)
+ .await?;
}
Ok(())
}
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 04b2db6b70f7..1dcb0acac97b 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -9,60 +9,82 @@ use std::sync::Arc;
use rand::Rng;
use sqlx::postgres::PgPool;
+use personhog_identity::config::IdentityTables;
use personhog_identity::storage::postgres::PostgresIdentityStorage;
+/// The production table set. Most tests run here; the raw-SQL assertion
+/// helpers in the test binaries assume it.
+pub fn default_tables() -> IdentityTables {
+ IdentityTables::real()
+}
+
+/// The validation (shadow) table set — the service's config default.
+pub fn tmp_tables() -> IdentityTables {
+ IdentityTables::validation()
+}
+
pub struct TestContext {
pub pool: PgPool,
pub storage: Arc<PostgresIdentityStorage>,
pub team_id: i64,
+ pub tables: IdentityTables,
}
impl TestContext {
pub async fn new() -> Self {
+ Self::new_with_tables(default_tables()).await
+ }
+
+ pub async fn new_with_tables(tables: IdentityTables) -> Self {
let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
"postgres://posthog:posthog@localhost:5432/posthog_persons".to_string()
});
let pool = PgPool::connect(&database_url)
.await
.expect("Failed to connect to test database");
- let storage = Arc::new(PostgresIdentityStorage::new(pool.clone()));
+ let storage = Arc::new(PostgresIdentityStorage::new(pool.clone(), tables.clone()));
let team_id = rand::thread_rng().gen_range(1_000_000..100_000_000);
Self {
pool,
storage,
team_id,
+ tables,
}
}
/// Inserts a person with a random (non-deterministic) uuid plus a distinct
/// id row pointing at it. Returns the person id.
pub async fn insert_person_with_distinct_id(&self, distinct_id: &str) -> i64 {
- let person_id: i64 = sqlx::query_scalar(
+ let insert_sql = format!(
r#"
- INSERT INTO posthog_person
+ INSERT INTO {}
(created_at, properties, properties_last_updated_at, properties_last_operation,
team_id, is_identified, uuid, version)
- VALUES (now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $1, false, gen_random_uuid(), 0)
+ VALUES (now(), '{{}}'::jsonb, '{{}}'::jsonb, '{{}}'::jsonb, $1, false, gen_random_uuid(), 0)
RETURNING id
"#,
- )
- .bind(self.team_id as i32)
- .fetch_one(&self.pool)
- .await
- .expect("Failed to insert person");
+ self.tables.person
+ );
+ let person_id: i64 = sqlx::query_scalar(&insert_sql)
+ .bind(self.team_id as i32)
+ .fetch_one(&self.pool)
+ .await
+ .expect("Failed to insert person");
- sqlx::query(
+ let pdi_sql = format!(
r#"
- INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ INSERT INTO {} (distinct_id, person_id, team_id, version)
VALUES ($1, $2, $3, 0)
"#,
- )
- .bind(distinct_id)
- .bind(person_id)
- .bind(self.team_id as i32)
- .execute(&self.pool)
- .await
- .expect("Failed to insert distinct id");
+ self.tables.person_distinct_id
+ );
+ sqlx::query(&pdi_sql)
+ .bind(distinct_id)
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("Failed to insert distinct id");
person_id
}
@@ -85,8 +107,71 @@ impl TestContext {
)
}
- pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
- sqlx::query("DELETE FROM lifecycle_op WHERE team_id = $1")
+ /// Parks the tmp person sequence in a random high range. Collision
+ /// tests insert a real posthog_person row with a tmp person's numeric
+ /// id; without this the explicit-id insert could race another test's
+ /// sequence-assigned real id.
+ pub async fn park_tmp_person_sequence(&self) {
+ let base: i64 = rand::thread_rng().gen_range(1_000_000_000_000..2_000_000_000_000);
+ sqlx::query("SELECT setval('personhog_person_tmp_id_seq', $1)")
+ .bind(base)
+ .execute(&self.pool)
+ .await
+ .expect("park tmp person sequence");
+ }
+
+ /// Seeds this team's rows in the *real* namespace keyed by the given
+ /// numeric person id: a posthog_person row plus a mapping row and a
+ /// hash-key override referencing it. Validation-set tests plant these
+ /// so a leftover hardcoded real table in a saga query would visibly
+ /// destroy or move them.
+ pub async fn seed_real_namespace_collision(&self, person_id: i64, distinct_id: &str) {
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_person
+ (id, created_at, properties, properties_last_updated_at,
+ properties_last_operation, team_id, is_identified, uuid, version)
+ VALUES ($1, now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $2, false,
+ gen_random_uuid(), 0)
+ "#,
+ )
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("insert colliding real person");
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ VALUES ($1, $2, $3, 0)
+ "#,
+ )
+ .bind(distinct_id)
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("insert colliding real mapping");
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_featureflaghashkeyoverride
+ (feature_flag_key, hash_key, person_id, team_id)
+ VALUES ('flag', 'real-hash', $1, $2)
+ "#,
+ )
+ .bind(person_id)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("insert colliding real override");
+ }
+
+ /// Removes this team's rows from the real namespace tables — the
+ /// counterpart of [`seed_real_namespace_collision`] for validation-set
+ /// tests, whose [`cleanup`](Self::cleanup) only touches the configured
+ /// tables.
+ pub async fn cleanup_real_namespace(&self) -> Result<(), sqlx::Error> {
+ sqlx::query("DELETE FROM posthog_featureflaghashkeyoverride WHERE team_id = $1")
.bind(self.team_id as i32)
.execute(&self.pool)
.await?;
@@ -100,4 +185,26 @@ impl TestContext {
.await?;
Ok(())
}
+
+ 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(&format!(
+ "DELETE FROM {} WHERE team_id = $1",
+ self.tables.person_distinct_id
+ ))
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
+ sqlx::query(&format!(
+ "DELETE FROM {} WHERE team_id = $1",
+ self.tables.person
+ ))
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
}
diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rs
index fa8b748dd4bf..1767a33ba183 100644
--- a/rust/personhog-identity/tests/common/sim_leader.rs
+++ b/rust/personhog-identity/tests/common/sim_leader.rs
@@ -114,6 +114,7 @@ fn fenced_status(fence: &Fence) -> Status {
pub struct SimLeader {
pool: PgPool,
+ person_table: String,
calls: Mutex<Vec<LeaderCall>>,
fences: Mutex<HashMap<i64, Fence>>,
deaths: Mutex<HashMap<i64, DeathDocument>>,
@@ -128,9 +129,10 @@ pub struct SimLeader {
}
impl SimLeader {
- pub fn new(pool: PgPool) -> Self {
+ pub fn new(pool: PgPool, person_table: String) -> Self {
Self {
pool,
+ person_table,
calls: Mutex::new(Vec::new()),
fences: Mutex::new(HashMap::new()),
deaths: Mutex::new(HashMap::new()),
@@ -205,19 +207,21 @@ impl SimLeader {
}
async fn live_person(&self, team_id: i64, person_id: i64) -> Option<Person> {
+ let live_sql = format!(
+ r#"
+ SELECT uuid, COALESCE(version, 0), created_at, is_identified, properties
+ FROM {person_table}
+ WHERE team_id = $1 AND id = $2 AND is_deleted = false
+ "#,
+ person_table = self.person_table,
+ );
let row: Option<(Uuid, i64, chrono::DateTime<Utc>, bool, serde_json::Value)> =
- sqlx::query_as(
- r#"
- SELECT uuid, COALESCE(version, 0), created_at, is_identified, properties
- FROM posthog_person
- WHERE team_id = $1 AND id = $2 AND is_deleted = false
- "#,
- )
- .bind(team_id as i32)
- .bind(person_id)
- .fetch_optional(&self.pool)
- .await
- .expect("person lookup");
+ sqlx::query_as(&live_sql)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .fetch_optional(&self.pool)
+ .await
+ .expect("person lookup");
row.map(
|(uuid, version, created_at, is_identified, properties)| Person {
id: person_id,
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
index e6d44f1d42ce..b07c217552e9 100644
--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -19,7 +19,7 @@ use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePerso
/// Storage-assertion helpers used only by this test binary.
impl TestContext {
fn lifecycle_service(&self) -> PersonHogLifecycleService {
- PersonHogLifecycleService::new(Arc::new(self.engine()))
+ PersonHogLifecycleService::new(Arc::new(self.engine()), self.tables.clone())
}
/// (is_deleted, version, properties) of a person row.
@@ -529,3 +529,183 @@ async fn a_recreated_distinct_id_revives_above_the_death_version() {
ctx.cleanup().await.expect("cleanup");
}
+
+#[tokio::test]
+async fn full_flow_works_on_a_configured_person_table() {
+ // Runs create, resolve, and the whole delete saga against
+ // personhog_person_tmp — a leftover hardcoded posthog_person in any of
+ // the interpolated queries would pass silently on the default table.
+ let ctx = TestContext::new_with_tables(common::tmp_tables()).await;
+ let service = ctx.lifecycle_service();
+ let distinct_id = format!("tmp-table-{}", Uuid::now_v7());
+
+ ctx.park_tmp_person_sequence().await;
+ let person_id = ctx.create_person_via_stub(&distinct_id).await;
+
+ let key = (ctx.team_id, distinct_id.clone());
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(std::slice::from_ref(&key))
+ .await
+ .expect("resolve succeeds");
+ assert_eq!(resolved.get(&key).map(|p| p.id), Some(person_id));
+
+ // Distinct id expansion must read the configured mapping table too.
+ let mappings = ctx
+ .storage
+ .get_distinct_ids_for_persons(ctx.team_id, &[person_id], None)
+ .await
+ .expect("distinct id expansion succeeds");
+ assert_eq!(
+ mappings
+ .iter()
+ .map(|m| m.distinct_id.as_str())
+ .collect::<Vec<_>>(),
+ vec![distinct_id.as_str()]
+ );
+
+ // A cohort row whose person_id collides numerically belongs to the real
+ // namespace; a delete on the validation set must not touch it.
+ sqlx::query("INSERT INTO posthog_cohortpeople (cohort_id, person_id) VALUES (1, $1)")
+ .bind(person_id)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert colliding cohort row");
+
+ // The same collision for the other two interpolated tables: a real
+ // person sharing the numeric id, its mapping row, and an override on
+ // each mirror. The saga must tombstone/clear only the tmp rows.
+ let real_distinct_id = format!("real-{distinct_id}");
+ ctx.seed_real_namespace_collision(person_id, &real_distinct_id)
+ .await;
+ sqlx::query(
+ r#"
+ INSERT INTO personhog_featureflaghashkeyoverride_tmp
+ (feature_flag_key, hash_key, person_id, team_id)
+ VALUES ('flag', 'tmp-hash', $1, $2)
+ "#,
+ )
+ .bind(person_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert tmp override");
+
+ 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 (is_deleted, version): (bool, i64) = sqlx::query_as(
+ "SELECT is_deleted, version FROM personhog_person_tmp WHERE team_id = $1 AND id = $2",
+ )
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("tombstone row exists");
+ assert!(is_deleted);
+ assert!(version > SEAL_VERSION_MARGIN);
+
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(std::slice::from_ref(&key))
+ .await
+ .expect("resolve after delete succeeds");
+ assert!(resolved.is_empty(), "tombstoned person must not resolve");
+
+ // The tmp mapping row tombstoned; the colliding real one untouched.
+ let tmp_mapping_deleted: bool = sqlx::query_scalar(
+ "SELECT is_deleted FROM personhog_persondistinctid_tmp WHERE team_id = $1 AND distinct_id = $2",
+ )
+ .bind(ctx.team_id as i32)
+ .bind(&distinct_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("tmp mapping row exists");
+ assert!(
+ tmp_mapping_deleted,
+ "the configured mapping table must be tombstoned"
+ );
+ let real_mapping_deleted: bool = sqlx::query_scalar(
+ "SELECT is_deleted FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",
+ )
+ .bind(ctx.team_id as i32)
+ .bind(&real_distinct_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("real mapping row exists");
+ assert!(
+ !real_mapping_deleted,
+ "a validation-set delete must not tombstone real-namespace mapping rows"
+ );
+
+ // The tmp override cleared; the real-namespace one survives.
+ let tmp_overrides: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM personhog_featureflaghashkeyoverride_tmp WHERE team_id = $1 AND person_id = $2",
+ )
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("count tmp overrides");
+ assert_eq!(
+ tmp_overrides, 0,
+ "the configured override table must be cleared"
+ );
+ let real_overrides: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM posthog_featureflaghashkeyoverride WHERE team_id = $1 AND person_id = $2",
+ )
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("count real overrides");
+ assert_eq!(
+ real_overrides, 1,
+ "a validation-set delete must not clear real-namespace overrides"
+ );
+
+ // The colliding real person row is untouched.
+ let real_person_deleted: bool =
+ sqlx::query_scalar("SELECT is_deleted FROM posthog_person WHERE team_id = $1 AND id = $2")
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("real person row exists");
+ assert!(
+ !real_person_deleted,
+ "a validation-set delete must not tombstone real-namespace persons"
+ );
+
+ let colliding_rows: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM posthog_cohortpeople WHERE person_id = $1")
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("count cohort rows");
+ assert_eq!(
+ colliding_rows, 1,
+ "a validation-set delete must not clear real-namespace cohort rows"
+ );
+ sqlx::query("DELETE FROM posthog_cohortpeople WHERE person_id = $1")
+ .bind(person_id)
+ .execute(&ctx.pool)
+ .await
+ .expect("remove colliding cohort row");
+
+ ctx.cleanup_real_namespace()
+ .await
+ .expect("cleanup real namespace");
+ ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 782ef15f4d92..8a5f35329963 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -41,10 +41,14 @@ struct MergeHarness {
impl MergeHarness {
async fn new() -> Self {
- let ctx = TestContext::new().await;
+ Self::new_with_tables(common::default_tables()).await
+ }
+
+ async fn new_with_tables(tables: personhog_identity::config::IdentityTables) -> Self {
+ let ctx = TestContext::new_with_tables(tables).await;
let engine = ctx.engine();
- let leader = Arc::new(SimLeader::new(ctx.pool.clone()));
- let driver = MergeDriver::new(leader.clone());
+ let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.person.clone()));
+ let driver = MergeDriver::new(leader.clone(), ctx.tables.clone());
Self {
ctx,
engine,
@@ -85,12 +89,13 @@ impl MergeHarness {
/// Adds another distinct id mapping to an existing person.
async fn add_distinct_id(&self, person_id: i64, distinct_id: &str) {
- sqlx::query(
+ sqlx::query(&format!(
r#"
- INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version)
+ INSERT INTO {} (team_id, person_id, distinct_id, version)
VALUES ($1, $2, $3, 0)
"#,
- )
+ self.ctx.tables.person_distinct_id
+ ))
.bind(self.ctx.team_id as i32)
.bind(person_id)
.bind(distinct_id)
@@ -100,13 +105,14 @@ impl MergeHarness {
}
async fn set_person(&self, person_id: i64, properties: &str, version: i64, identified: bool) {
- sqlx::query(
+ sqlx::query(&format!(
r#"
- UPDATE posthog_person
+ UPDATE {}
SET properties = $3::jsonb, version = $4, is_identified = $5
WHERE team_id = $1 AND id = $2
"#,
- )
+ self.ctx.tables.person
+ ))
.bind(self.ctx.team_id as i32)
.bind(person_id)
.bind(properties)
@@ -149,12 +155,13 @@ impl MergeHarness {
/// (is_deleted, version, properties) of a person row.
async fn person_state(&self, person_id: i64) -> (bool, i64, serde_json::Value) {
- sqlx::query_as(
+ sqlx::query_as(&format!(
r#"
SELECT is_deleted, COALESCE(version, 0), properties
- FROM posthog_person WHERE team_id = $1 AND id = $2
+ FROM {} WHERE team_id = $1 AND id = $2
"#,
- )
+ self.ctx.tables.person
+ ))
.bind(self.ctx.team_id as i32)
.bind(person_id)
.fetch_one(&self.ctx.pool)
@@ -164,12 +171,13 @@ impl MergeHarness {
/// (person_id, is_deleted, version) of a distinct id row.
async fn pdi_state(&self, distinct_id: &str) -> (i64, bool, i64) {
- sqlx::query_as(
+ sqlx::query_as(&format!(
r#"
SELECT person_id, is_deleted, COALESCE(version, 0)
- FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2
+ FROM {} WHERE team_id = $1 AND distinct_id = $2
"#,
- )
+ self.ctx.tables.person_distinct_id
+ ))
.bind(self.ctx.team_id as i32)
.bind(distinct_id)
.fetch_one(&self.ctx.pool)
@@ -1336,3 +1344,159 @@ async fn parked_state(pool: &PgPool, op_id: Uuid) -> (bool, Option<String>) {
.expect("op row exists");
(row.0.is_some(), row.1)
}
+
+#[tokio::test]
+async fn merge_works_on_a_configured_person_table() {
+ // Runs the whole merge saga against personhog_person_tmp — a leftover
+ // hardcoded posthog_person in any of the interpolated queries would
+ // pass silently on the default table.
+ let h = MergeHarness::new_with_tables(common::tmp_tables()).await;
+ h.ctx.park_tmp_person_sequence().await;
+ let target = h
+ .ctx
+ .insert_person_with_distinct_id("tmp-merge-target")
+ .await;
+ let source = h
+ .ctx
+ .insert_person_with_distinct_id("tmp-merge-source")
+ .await;
+
+ // A cohort row whose person_id collides numerically belongs to the real
+ // namespace; a merge on the validation set must not move it.
+ sqlx::query("INSERT INTO posthog_cohortpeople (cohort_id, person_id) VALUES (1, $1)")
+ .bind(source)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("insert colliding cohort row");
+
+ // The same collision for the other two interpolated tables: a real
+ // person sharing the source's numeric id, its mapping row, and an
+ // override on each mirror. The flip must repoint/move only the tmp
+ // rows.
+ h.ctx
+ .seed_real_namespace_collision(source, "tmp-merge-collide-real")
+ .await;
+ sqlx::query(
+ r#"
+ INSERT INTO personhog_featureflaghashkeyoverride_tmp
+ (feature_flag_key, hash_key, person_id, team_id)
+ VALUES ('flag', 'tmp-hash', $1, $2)
+ "#,
+ )
+ .bind(source)
+ .bind(h.ctx.team_id as i32)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("insert tmp override");
+
+ let op_id = Uuid::now_v7();
+ let outcome = h
+ .execute(
+ op_id,
+ &merge_request("tmp-merge-target", &["tmp-merge-source"]),
+ )
+ .await
+ .expect("merge completes");
+ assert!(!outcome.aborted);
+ assert_eq!(
+ result_map(&outcome),
+ HashMap::from([("tmp-merge-source".to_string(), OUTCOME_MERGED.to_string())])
+ );
+
+ // The source's distinct id repointed at the target on the configured
+ // mapping table; the source person tombstoned on the configured person
+ // table.
+ let (person_id, is_deleted, version) = h.pdi_state("tmp-merge-source").await;
+ assert_eq!(person_id, target);
+ assert!(!is_deleted);
+ assert_eq!(version, 1);
+ let (source_deleted, _, properties) = h.person_state(source).await;
+ assert!(source_deleted);
+ assert_eq!(properties, json!({}));
+ let (target_deleted, _, _) = h.person_state(target).await;
+ assert!(!target_deleted);
+
+ // The colliding real-namespace mapping still points at its own person.
+ let (real_pid, real_deleted, real_version): (i64, bool, i64) = sqlx::query_as(
+ r#"
+ SELECT person_id, is_deleted, COALESCE(version, 0)
+ FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2
+ "#,
+ )
+ .bind(h.ctx.team_id as i32)
+ .bind("tmp-merge-collide-real")
+ .fetch_one(&h.ctx.pool)
+ .await
+ .expect("real mapping row exists");
+ assert_eq!(
+ real_pid, source,
+ "a validation-set merge must not repoint real-namespace mapping rows"
+ );
+ assert!(!real_deleted);
+ assert_eq!(real_version, 0);
+
+ // The tmp override moved to the target; the real one stayed put.
+ let tmp_override_owner: i64 = sqlx::query_scalar(
+ r#"
+ SELECT person_id FROM personhog_featureflaghashkeyoverride_tmp
+ WHERE team_id = $1 AND feature_flag_key = 'flag'
+ "#,
+ )
+ .bind(h.ctx.team_id as i32)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .expect("tmp override row exists");
+ assert_eq!(
+ tmp_override_owner, target,
+ "the configured override table must move to the target"
+ );
+ let real_override_owner: i64 = sqlx::query_scalar(
+ r#"
+ SELECT person_id FROM posthog_featureflaghashkeyoverride
+ WHERE team_id = $1 AND feature_flag_key = 'flag'
+ "#,
+ )
+ .bind(h.ctx.team_id as i32)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .expect("real override row exists");
+ assert_eq!(
+ real_override_owner, source,
+ "a validation-set merge must not move real-namespace overrides"
+ );
+
+ // The colliding real person row is untouched.
+ let real_person_deleted: bool =
+ sqlx::query_scalar("SELECT is_deleted FROM posthog_person WHERE team_id = $1 AND id = $2")
+ .bind(h.ctx.team_id as i32)
+ .bind(source)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .expect("real person row exists");
+ assert!(
+ !real_person_deleted,
+ "a validation-set merge must not tombstone real-namespace persons"
+ );
+
+ let colliding_rows: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM posthog_cohortpeople WHERE person_id = $1")
+ .bind(source)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .expect("count cohort rows");
+ assert_eq!(
+ colliding_rows, 1,
+ "a validation-set merge must not move real-namespace cohort rows"
+ );
+ sqlx::query("DELETE FROM posthog_cohortpeople WHERE person_id = $1")
+ .bind(source)
+ .execute(&h.ctx.pool)
+ .await
+ .expect("remove colliding cohort row");
+
+ h.ctx
+ .cleanup_real_namespace()
+ .await
+ .expect("cleanup real namespace");
+ h.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 31761c2e60c3..cb4ba9ed8643 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -4,6 +4,7 @@ use std::time::Duration;
use sqlx::postgres::PgPoolOptions;
use tonic::{Code, Request};
+use personhog_identity::config::IdentityTables;
use personhog_identity::lifecycle::engine::{Engine, EngineConfig};
use personhog_identity::lifecycle::validation::MAX_DELETE_BATCH_SIZE;
use personhog_identity::lifecycle::PersonHogLifecycleService;
@@ -33,7 +34,7 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
attempt_alert_threshold: 5,
},
));
- let service = PersonHogLifecycleService::new(engine);
+ let service = PersonHogLifecycleService::new(engine, IdentityTables::real());
service
.delete_persons(Request::new(request))
.await
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 3dd2fe35a6bf..39ee7c331e7c 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -156,12 +156,9 @@ pub async fn run(args: GateArgs) -> Result<()> {
{
bail!("--create-via-identity with --external-router-url needs --external-identity-url");
}
- // The identity service writes the real posthog_person table (its distinct
- // id FKs require it); a stack targeting another table would recover
- // created persons from a table they were never written to.
- if args.create_via_identity && args.pg_target_table != "posthog_person" {
- bail!("--create-via-identity requires --pg-target-table posthog_person");
- }
+ // The spawned identity derives its whole table set (person, distinct id,
+ // hash-key overrides) from --pg-target-table, so any known table set
+ // works; Stack::up rejects person tables without a known companion set.
if (args.router_kill_after.is_some() || args.router_shutdown_after.is_some())
&& args.routers < 3
{
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index f076282dda70..3b411fc796fa 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -1,6 +1,6 @@
use std::time::Duration;
-use anyhow::{bail, Context, Result};
+use anyhow::{Context, Result};
use sqlx::postgres::PgPool;
/// Seed `count` persons for `team_id` directly in `table` and return their
@@ -48,6 +48,18 @@ pub async fn seed_persons(
Ok(ids)
}
+/// The distinct id tables to sweep for a team: always the real mapping
+/// table, plus the tmp mirror when the harness targets the validation
+/// person table — identity writes its mappings there, and the mirror's FK
+/// blocks the person delete until they go.
+fn distinct_id_tables_for(person_table: &str) -> &'static [&'static str] {
+ if person_table == "personhog_person_tmp" {
+ &["posthog_persondistinctid", "personhog_persondistinctid_tmp"]
+ } else {
+ &["posthog_persondistinctid"]
+ }
+}
+
/// Delete all of `team_id`'s rows from `table`, plus the distinct id and
/// personless rows the identity-service create path writes. The harness
/// owns its team ids outright, so team-wide deletes are the whole cleanup.
@@ -56,11 +68,13 @@ pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u6
validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
- sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
- .bind(team)
- .execute(pool)
- .await
- .context("deleting distinct ids")?;
+ for pdi_table in distinct_id_tables_for(table) {
+ sqlx::query(&format!("DELETE FROM {pdi_table} WHERE team_id = $1"))
+ .bind(team)
+ .execute(pool)
+ .await
+ .with_context(|| format!("deleting distinct ids from {pdi_table}"))?;
+ }
sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
.bind(team)
.execute(pool)
@@ -146,11 +160,13 @@ pub async fn reap_stale_team_rows(
validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
- sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
- .bind(team)
- .execute(pool)
- .await
- .context("deleting distinct ids")?;
+ for pdi_table in distinct_id_tables_for(table) {
+ sqlx::query(&format!("DELETE FROM {pdi_table} WHERE team_id = $1"))
+ .bind(team)
+ .execute(pool)
+ .await
+ .with_context(|| format!("deleting distinct ids from {pdi_table}"))?;
+ }
sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
.bind(team)
.execute(pool)
@@ -173,10 +189,7 @@ pub async fn reap_stale_team_rows(
/// The table name comes from the operator's CLI/env, but sanity-check it
/// anyway since it is interpolated into SQL (identifiers cannot be bound).
pub fn validate_table_name(table: &str) -> Result<()> {
- if table.is_empty() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
- bail!("invalid table name: {table}");
- }
- Ok(())
+ personhog_common::persons::validate_table_name(table).map_err(|e| anyhow::anyhow!(e))
}
#[cfg(test)]
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index b54cb8f35ff9..3f87e440520d 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -97,6 +97,26 @@ pub struct Stack {
}
impl Stack {
+ /// The distinct id and hash-key-override tables paired with a person
+ /// table. Identity writes the mapping (and clears overrides) in the same
+ /// id namespace as its person table, so the three always travel together.
+ fn identity_companion_tables(person_table: &str) -> Result<(&'static str, &'static str)> {
+ match person_table {
+ "posthog_person" => Ok((
+ "posthog_persondistinctid",
+ "posthog_featureflaghashkeyoverride",
+ )),
+ "personhog_person_tmp" => Ok((
+ "personhog_persondistinctid_tmp",
+ "personhog_featureflaghashkeyoverride_tmp",
+ )),
+ other => bail!(
+ "--create-via-identity has no known identity table set for \
+ --pg-target-table {other:?}"
+ ),
+ }
+ }
+
pub async fn up(config: StackConfig) -> Result<Self> {
if config.routers == 0 || config.routers > MAX_ROUTERS {
bail!("--routers must be between 1 and {MAX_ROUTERS}");
@@ -222,8 +242,12 @@ impl Stack {
// Identity resolves and creates on the Postgres primary and pushes
// initial properties through the traffic router; it holds no etcd
- // state, so it can come up alongside the routers.
+ // state, so it can come up alongside the routers. Its table set is
+ // derived from the stack's person table so identity, writer, and the
+ // leader fallback agree on one id namespace.
let identity_url = if config.spawn_identity {
+ let (pdi_table, ffhko_table) =
+ Self::identity_companion_tables(&config.pg_target_table)?;
infra.push(ServiceProcess::spawn(
"identity",
&config.bin_dir.join("personhog-identity"),
@@ -232,6 +256,9 @@ impl Stack {
("PRIMARY_DATABASE_URL", config.persons_db_url.clone()),
("ROUTER_URL", router_url.clone()),
("METRICS_PORT", IDENTITY_METRICS_PORT.to_string()),
+ ("PERSON_TABLE", config.pg_target_table.clone()),
+ ("PERSON_DISTINCT_ID_TABLE", pdi_table.to_string()),
+ ("FF_HASH_KEY_OVERRIDE_TABLE", ffhko_table.to_string()),
],
&log_dir,
)?);