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): allow configurable lifecycle op tables (#100480)

Nick Best2452c6fe9b43
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index d9d864f30fe2..119e8f741992 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3027,6 +3027,15 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "common-sqlx-macros"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "common-temporal"
version = "0.1.0"
@@ -8724,6 +8733,7 @@ dependencies = [
"common-alloc",
"common-database",
"common-metrics",
+ "common-sqlx-macros",
"envconfig",
"futures",
"lifecycle",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 64fdfc162573..ddd85d87c5c1 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -39,6 +39,7 @@ members = [
"common/types",
"common/compression",
"common/hypercache",
+ "common/sqlx-macros",
"feature-flags",
"flags-consumer",
"hypercache-server",
@@ -230,6 +231,9 @@ tracing-opentelemetry = "0.23.0"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
url = "2.5.0"
uuid = { version = "1.23.0", features = ["v4", "v5", "v7", "serde"] }
+proc-macro2 = "1"
+quote = "1"
+syn = { version = "2", features = ["full"] }
zstd = "0.13"
neon = "1"
quick_cache = "0.6.21"
diff --git a/rust/common/sqlx-macros/Cargo.toml b/rust/common/sqlx-macros/Cargo.toml
new file mode 100644
index 000000000000..2ec47c54f2a6
--- /dev/null
+++ b/rust/common/sqlx-macros/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "common-sqlx-macros"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[lib]
+proc-macro = true
+
+[lints]
+workspace = true
+
+[dependencies]
+proc-macro2 = { workspace = true }
+quote = { workspace = true }
+syn = { workspace = true }
diff --git a/rust/common/sqlx-macros/README.md b/rust/common/sqlx-macros/README.md
new file mode 100644
index 000000000000..df70e11c966a
--- /dev/null
+++ b/rust/common/sqlx-macros/README.md
@@ -0,0 +1,28 @@
+# common-sqlx-macros
+
+Compile-time checked `sqlx` queries over mirrored table sets.
+
+A service that runs against either a real table or its `_tmp` mirror cannot put the table name in `sqlx::query!`, which needs one string literal. These macros take the SQL once with `{table}` placeholders and expand it into two `sqlx` macro calls, one per set, picked at runtime by a `bool`.
+
+```rust
+use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
+
+let rows = mirrored_query_as!(
+ OpRow,
+ tables.is_validation(),
+ "SELECT op_id, step FROM {lifecycle_op} WHERE team_id = $1",
+ team_id
+ => fetch_all(&pool)
+)?;
+```
+
+- `{name}` expands to `name` for the real set and `name_tmp` for the mirror.
+- `{real|mirror}` names both sides explicitly, for tables outside the suffix convention.
+- `{{` and `}}` are literal braces.
+- Everything after `=>` is the executor call. It sits inside the macro because each expansion has its own row type, and awaiting inside each branch is what lets them unify. The macros only work in `async` code, and `mirrored_query_as!` rows must be named structs.
+
+Both expansions go through the offline cache, so `cargo sqlx prepare` for the using crate needs a database with both table sets.
+
+## Extending
+
+Each macro wraps one `sqlx` macro; adding another (for example `query_file!`) is a new `#[proc_macro]` entry point that calls `MirroredQuery::expand` with the sqlx path. The placeholder rules live in `rewrite`, which has unit tests.
diff --git a/rust/common/sqlx-macros/src/lib.rs b/rust/common/sqlx-macros/src/lib.rs
new file mode 100644
index 000000000000..afa9c06d4db4
--- /dev/null
+++ b/rust/common/sqlx-macros/src/lib.rs
@@ -0,0 +1,211 @@
+//! Compile-time checked sqlx queries over mirrored table sets: one SQL
+//! string with `{table}` placeholders expands to a `sqlx` macro per set,
+//! selected at runtime by a `bool`. Usage and placeholder rules are in
+//! the crate README.
+//!
+//! The executor call after `=>` is part of the macro because each `sqlx`
+//! expansion has its own row type; awaiting inside each branch is what
+//! lets the two unify.
+
+use proc_macro::TokenStream;
+use proc_macro2::TokenStream as TokenStream2;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::{parse_macro_input, Expr, Ident, LitStr, Token, Type};
+
+const MIRROR_SUFFIX: &str = "_tmp";
+
+struct MirroredQuery {
+ row: Option<Type>,
+ mirror: Expr,
+ sql: LitStr,
+ args: Vec<Expr>,
+ method: Ident,
+ executor: TokenStream2,
+}
+
+impl MirroredQuery {
+ fn parse(input: ParseStream, with_row: bool) -> syn::Result<Self> {
+ let row = if with_row {
+ let row: Type = input.parse()?;
+ input.parse::<Token![,]>()?;
+ Some(row)
+ } else {
+ None
+ };
+ let mirror: Expr = input.parse()?;
+ input.parse::<Token![,]>()?;
+ let sql: LitStr = input.parse()?;
+ let mut args = Vec::new();
+ while input.peek(Token![,]) {
+ input.parse::<Token![,]>()?;
+ if input.peek(Token![=>]) {
+ break;
+ }
+ args.push(input.parse::<Expr>()?);
+ }
+ input.parse::<Token![=>]>()?;
+ let method: Ident = input.parse()?;
+ let content;
+ syn::parenthesized!(content in input);
+ let executor: TokenStream2 = content.parse()?;
+ Ok(Self {
+ row,
+ mirror,
+ sql,
+ args,
+ method,
+ executor,
+ })
+ }
+
+ fn expand(self, sqlx_macro: TokenStream2) -> TokenStream2 {
+ let (real, mirror) = match rewrite(&self.sql.value()) {
+ Ok(pair) => pair,
+ Err(message) => {
+ return syn::Error::new(self.sql.span(), message).to_compile_error();
+ }
+ };
+ let real = LitStr::new(&real, self.sql.span());
+ let mirror = LitStr::new(&mirror, self.sql.span());
+ let row = self.row.map(|row| quote!(#row,));
+ let args = &self.args;
+ let select = &self.mirror;
+ let method = &self.method;
+ let executor = &self.executor;
+ quote! {
+ if #select {
+ #sqlx_macro(#row #mirror #(, #args)*).#method(#executor).await
+ } else {
+ #sqlx_macro(#row #real #(, #args)*).#method(#executor).await
+ }
+ }
+ }
+}
+
+struct WithoutRow(MirroredQuery);
+struct WithRow(MirroredQuery);
+
+impl Parse for WithoutRow {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ MirroredQuery::parse(input, false).map(Self)
+ }
+}
+
+impl Parse for WithRow {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ MirroredQuery::parse(input, true).map(Self)
+ }
+}
+
+fn rewrite(sql: &str) -> Result<(String, String), String> {
+ let mut real = String::with_capacity(sql.len());
+ let mut mirror = String::with_capacity(sql.len());
+ let mut chars = sql.chars().peekable();
+ let mut placeholders = 0;
+ while let Some(c) = chars.next() {
+ match c {
+ '{' if chars.peek() == Some(&'{') => {
+ chars.next();
+ real.push('{');
+ mirror.push('{');
+ }
+ '}' if chars.peek() == Some(&'}') => {
+ chars.next();
+ real.push('}');
+ mirror.push('}');
+ }
+ '{' => {
+ let mut name = String::new();
+ loop {
+ match chars.next() {
+ Some('}') => break,
+ Some(ch) => name.push(ch),
+ None => return Err("unclosed `{` in mirrored query".to_string()),
+ }
+ }
+ let (real_name, mirror_name) = match name.split_once('|') {
+ Some((real_name, mirror_name)) => {
+ (real_name.to_string(), mirror_name.to_string())
+ }
+ None => (name.clone(), format!("{name}{MIRROR_SUFFIX}")),
+ };
+ for table in [&real_name, &mirror_name] {
+ if table.is_empty()
+ || !table
+ .chars()
+ .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
+ {
+ return Err(format!("`{table}` is not a table identifier"));
+ }
+ }
+ real.push_str(&real_name);
+ mirror.push_str(&mirror_name);
+ placeholders += 1;
+ }
+ '}' => return Err("stray `}` in mirrored query; write `}}` for a literal".to_string()),
+ _ => {
+ real.push(c);
+ mirror.push(c);
+ }
+ }
+ }
+ if placeholders == 0 {
+ return Err(
+ "mirrored query has no `{table}` placeholder; use sqlx::query! directly".to_string(),
+ );
+ }
+ Ok((real, mirror))
+}
+
+#[proc_macro]
+pub fn mirrored_query(input: TokenStream) -> TokenStream {
+ let WithoutRow(query) = parse_macro_input!(input as WithoutRow);
+ query.expand(quote!(::sqlx::query!)).into()
+}
+
+#[proc_macro]
+pub fn mirrored_query_as(input: TokenStream) -> TokenStream {
+ let WithRow(query) = parse_macro_input!(input as WithRow);
+ query.expand(quote!(::sqlx::query_as!)).into()
+}
+
+#[proc_macro]
+pub fn mirrored_query_scalar(input: TokenStream) -> TokenStream {
+ let WithoutRow(query) = parse_macro_input!(input as WithoutRow);
+ query.expand(quote!(::sqlx::query_scalar!)).into()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::rewrite;
+
+ #[test]
+ fn a_bare_placeholder_gets_the_mirror_suffix() {
+ let (real, mirror) = rewrite("SELECT 1 FROM {lifecycle_op} o").unwrap();
+ assert_eq!(real, "SELECT 1 FROM lifecycle_op o");
+ assert_eq!(mirror, "SELECT 1 FROM lifecycle_op_tmp o");
+ }
+
+ #[test]
+ fn an_explicit_pair_names_both_sides() {
+ let (real, mirror) = rewrite("FROM {posthog_person|personhog_person_tmp}").unwrap();
+ assert_eq!(real, "FROM posthog_person");
+ assert_eq!(mirror, "FROM personhog_person_tmp");
+ }
+
+ #[test]
+ fn doubled_braces_stay_literal() {
+ let (real, mirror) = rewrite("SET request = '{{}}'::jsonb FROM {t}").unwrap();
+ assert_eq!(real, "SET request = '{}'::jsonb FROM t");
+ assert_eq!(mirror, "SET request = '{}'::jsonb FROM t_tmp");
+ }
+
+ #[test]
+ fn malformed_placeholders_are_rejected() {
+ assert!(rewrite("FROM {lifecycle_op").is_err());
+ assert!(rewrite("FROM lifecycle_op}").is_err());
+ assert!(rewrite("FROM {bad name}").is_err());
+ assert!(rewrite("FROM lifecycle_op").is_err());
+ }
+}
diff --git a/rust/personhog-identity/.sqlx/query-0a698d74f1c84d076282ab9bfaae012d4d3b3d14485972648afe15c599682530.json b/rust/personhog-identity/.sqlx/query-0a698d74f1c84d076282ab9bfaae012d4d3b3d14485972648afe15c599682530.json
new file mode 100644
index 000000000000..018ca7af3a50
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-0a698d74f1c84d076282ab9bfaae012d4d3b3d14485972648afe15c599682530.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_tmp\n SET lease_expires_at = now() + make_interval(secs => $2)\n WHERE op_id = $1 AND completed_at IS NULL AND attempt = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Float8",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0a698d74f1c84d076282ab9bfaae012d4d3b3d14485972648afe15c599682530"
+}
diff --git a/rust/personhog-identity/.sqlx/query-17ea4152a4838f54308b61bdad18debc5664a40c1aafd4c7706f0a78d95bafdc.json b/rust/personhog-identity/.sqlx/query-17ea4152a4838f54308b61bdad18debc5664a40c1aafd4c7706f0a78d95bafdc.json
new file mode 100644
index 000000000000..dc0afde3f1ad
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-17ea4152a4838f54308b61bdad18debc5664a40c1aafd4c7706f0a78d95bafdc.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT sealed FROM lifecycle_op_person_tmp WHERE op_id = $1 AND role = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sealed",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "17ea4152a4838f54308b61bdad18debc5664a40c1aafd4c7706f0a78d95bafdc"
+}
diff --git a/rust/personhog-identity/.sqlx/query-1bcdfcfce1a90c8b39d703e846caf4c2cb2ab689669697b476b305a7975ed816.json b/rust/personhog-identity/.sqlx/query-1bcdfcfce1a90c8b39d703e846caf4c2cb2ab689669697b476b305a7975ed816.json
new file mode 100644
index 000000000000..d450290e000a
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-1bcdfcfce1a90c8b39d703e846caf4c2cb2ab689669697b476b305a7975ed816.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_person_tmp (op_id, team_id, person_id, person_uuid, role, status)\n SELECT $1, $2, u.person_id, u.person_uuid, $5, $6\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\n ON CONFLICT (op_id, person_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Int8Array",
+ "UuidArray",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1bcdfcfce1a90c8b39d703e846caf4c2cb2ab689669697b476b305a7975ed816"
+}
diff --git a/rust/personhog-identity/.sqlx/query-248952755ca64b45cc34eeb3c6eeb91e74ca63d95671a166799448e967ad087c.json b/rust/personhog-identity/.sqlx/query-248952755ca64b45cc34eeb3c6eeb91e74ca63d95671a166799448e967ad087c.json
new file mode 100644
index 000000000000..b1fb5dbc36cc
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-248952755ca64b45cc34eeb3c6eeb91e74ca63d95671a166799448e967ad087c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person_tmp SET status = $2 WHERE op_id = $1 AND status = $3",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "248952755ca64b45cc34eeb3c6eeb91e74ca63d95671a166799448e967ad087c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-26d83ce65bccd87ce92d585722cd7912eb6f735368db2f5bd8159decc7b2d748.json b/rust/personhog-identity/.sqlx/query-26d83ce65bccd87ce92d585722cd7912eb6f735368db2f5bd8159decc7b2d748.json
new file mode 100644
index 000000000000..9c9be1dc3c00
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-26d83ce65bccd87ce92d585722cd7912eb6f735368db2f5bd8159decc7b2d748.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\",\n created_at, completed_at,\n (lease_expires_at IS NOT NULL AND lease_expires_at >= now())\n as \"lease_live!\"\n FROM lifecycle_op_tmp\n WHERE op_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "op_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "step",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "attempt",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 5,
+ "name": "request: Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "outcome: Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "lease_live!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "26d83ce65bccd87ce92d585722cd7912eb6f735368db2f5bd8159decc7b2d748"
+}
diff --git a/rust/personhog-identity/.sqlx/query-2a85ebab2debd88588c5949491546038a90605dfebc728c8101d580ccff2df71.json b/rust/personhog-identity/.sqlx/query-2a85ebab2debd88588c5949491546038a90605dfebc728c8101d580ccff2df71.json
new file mode 100644
index 000000000000..a3602cfd9541
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-2a85ebab2debd88588c5949491546038a90605dfebc728c8101d580ccff2df71.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id, person_uuid,\n (sealed->>'version')::bigint AS \"sealed_version!\",\n (sealed->>'created_at')::bigint AS \"sealed_created_at!\"\n FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND status = 'sealed' AND sealed ? 'created_at'\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sealed_version!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "sealed_created_at!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "2a85ebab2debd88588c5949491546038a90605dfebc728c8101d580ccff2df71"
+}
diff --git a/rust/personhog-identity/.sqlx/query-316c8c75ee8090135340d797980d5e38f17de35b54f11c2e9ec830417dcdf5f5.json b/rust/personhog-identity/.sqlx/query-316c8c75ee8090135340d797980d5e38f17de35b54f11c2e9ec830417dcdf5f5.json
new file mode 100644
index 000000000000..c852e83130ad
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-316c8c75ee8090135340d797980d5e38f17de35b54f11c2e9ec830417dcdf5f5.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_tmp\n SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL\n WHERE op_id = $1 AND step = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "316c8c75ee8090135340d797980d5e38f17de35b54f11c2e9ec830417dcdf5f5"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3395b5c7c26287c98b9b5a12511e27614895e3224a83f2fed2158c27bda00a57.json b/rust/personhog-identity/.sqlx/query-3395b5c7c26287c98b9b5a12511e27614895e3224a83f2fed2158c27bda00a57.json
new file mode 100644
index 000000000000..4b2926de81e2
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3395b5c7c26287c98b9b5a12511e27614895e3224a83f2fed2158c27bda00a57.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_person_tmp (op_id, team_id, person_id, person_uuid, role, status)\n SELECT $1, $2, u.person_id, u.person_uuid, 'victim', $5\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\n ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING\n RETURNING person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Int8Array",
+ "UuidArray",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "3395b5c7c26287c98b9b5a12511e27614895e3224a83f2fed2158c27bda00a57"
+}
diff --git a/rust/personhog-identity/.sqlx/query-34428f9dee5307dacef6de994ec97a88d882fc10825c3697f7834d6534903a31.json b/rust/personhog-identity/.sqlx/query-34428f9dee5307dacef6de994ec97a88d882fc10825c3697f7834d6534903a31.json
new file mode 100644
index 000000000000..7fe0f1b14ea0
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-34428f9dee5307dacef6de994ec97a88d882fc10825c3697f7834d6534903a31.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND status = 'sealed'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "34428f9dee5307dacef6de994ec97a88d882fc10825c3697f7834d6534903a31"
+}
diff --git a/rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.json b/rust/personhog-identity/.sqlx/query-358ad441e0296658f0f58d180b9753f5759e3b7c1b8bcc60325af5d894bc3c39.json
similarity index 55%
rename from rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.json
rename to rust/personhog-identity/.sqlx/query-358ad441e0296658f0f58d180b9753f5759e3b7c1b8bcc60325af5d894bc3c39.json
index 4da26399af3c..6ec52802cacf 100644
--- a/rust/personhog-identity/.sqlx/query-d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034.json
+++ b/rust/personhog-identity/.sqlx/query-358ad441e0296658f0f58d180b9753f5759e3b7c1b8bcc60325af5d894bc3c39.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT person_id, person_uuid, sealed as \"sealed!\" FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ",
+ "query": "\n SELECT person_id, person_uuid, ordinal as \"ordinal!\", sealed as \"sealed!\"\n FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ORDER BY ordinal\n ",
"describe": {
"columns": [
{
@@ -15,6 +15,11 @@
},
{
"ordinal": 2,
+ "name": "ordinal!",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
"name": "sealed!",
"type_info": "Jsonb"
}
@@ -29,8 +34,9 @@
"nullable": [
false,
false,
+ true,
true
]
},
- "hash": "d1bc9d788810e25366eb8f8f027be2b1fb6af9292488628de61418cfbcd0e034"
+ "hash": "358ad441e0296658f0f58d180b9753f5759e3b7c1b8bcc60325af5d894bc3c39"
}
diff --git a/rust/personhog-identity/.sqlx/query-39689d5bf4b2e19a21d2f73dd57bc1963d006a10413b72c248a48a0840858bd2.json b/rust/personhog-identity/.sqlx/query-39689d5bf4b2e19a21d2f73dd57bc1963d006a10413b72c248a48a0840858bd2.json
new file mode 100644
index 000000000000..90d22c697214
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-39689d5bf4b2e19a21d2f73dd57bc1963d006a10413b72c248a48a0840858bd2.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND role = $2 AND status = $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "39689d5bf4b2e19a21d2f73dd57bc1963d006a10413b72c248a48a0840858bd2"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3d9bc04d09ce7b7feb3fd38bc2522b61ad8500c1eaebd55551b3b6fc3c51668d.json b/rust/personhog-identity/.sqlx/query-3d9bc04d09ce7b7feb3fd38bc2522b61ad8500c1eaebd55551b3b6fc3c51668d.json
new file mode 100644
index 000000000000..cffbd62767c2
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3d9bc04d09ce7b7feb3fd38bc2522b61ad8500c1eaebd55551b3b6fc3c51668d.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp lop\n SET moved = u.moved\n FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8Array",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3d9bc04d09ce7b7feb3fd38bc2522b61ad8500c1eaebd55551b3b6fc3c51668d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3f4d3db54fa04f0aebe0a43494e3224ebaf53c319df43fb9f147ff92d26a902a.json b/rust/personhog-identity/.sqlx/query-3f4d3db54fa04f0aebe0a43494e3224ebaf53c319df43fb9f147ff92d26a902a.json
new file mode 100644
index 000000000000..00652c2e83a7
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3f4d3db54fa04f0aebe0a43494e3224ebaf53c319df43fb9f147ff92d26a902a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person_tmp SET status = $2 WHERE op_id = $1 AND role = $3",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3f4d3db54fa04f0aebe0a43494e3224ebaf53c319df43fb9f147ff92d26a902a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-4247abdc4f01e72f3ec9132bab49846c093b821e072065225a500b277a22e34a.json b/rust/personhog-identity/.sqlx/query-4247abdc4f01e72f3ec9132bab49846c093b821e072065225a500b277a22e34a.json
new file mode 100644
index 000000000000..c8c58adb8bf0
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-4247abdc4f01e72f3ec9132bab49846c093b821e072065225a500b277a22e34a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4247abdc4f01e72f3ec9132bab49846c093b821e072065225a500b277a22e34a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-4bd0abc45641ff6319d2a8535718edee8d1c745de144922fcf71ee56202078c5.json b/rust/personhog-identity/.sqlx/query-4bd0abc45641ff6319d2a8535718edee8d1c745de144922fcf71ee56202078c5.json
new file mode 100644
index 000000000000..b70cfaa5d3c9
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-4bd0abc45641ff6319d2a8535718edee8d1c745de144922fcf71ee56202078c5.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp lop\n SET status = $4, sealed = u.sealed\n FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, sealed)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n AND lop.status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8Array",
+ "JsonbArray",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4bd0abc45641ff6319d2a8535718edee8d1c745de144922fcf71ee56202078c5"
+}
diff --git a/rust/personhog-identity/.sqlx/query-4fd9637eab32f77471edb60dd6084278cf6edfdc7b3b232e9a51ef4660b43408.json b/rust/personhog-identity/.sqlx/query-4fd9637eab32f77471edb60dd6084278cf6edfdc7b3b232e9a51ef4660b43408.json
new file mode 100644
index 000000000000..8bc140c3708c
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-4fd9637eab32f77471edb60dd6084278cf6edfdc7b3b232e9a51ef4660b43408.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person_tmp SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4fd9637eab32f77471edb60dd6084278cf6edfdc7b3b232e9a51ef4660b43408"
+}
diff --git a/rust/personhog-identity/.sqlx/query-55ac7f69716cf272614a5729e1a1e0ca370e42b55bf3870a148b83c03163a8c4.json b/rust/personhog-identity/.sqlx/query-55ac7f69716cf272614a5729e1a1e0ca370e42b55bf3870a148b83c03163a8c4.json
new file mode 100644
index 000000000000..9f2a28a8c0b9
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-55ac7f69716cf272614a5729e1a1e0ca370e42b55bf3870a148b83c03163a8c4.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT count(*) as \"count!\" FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "55ac7f69716cf272614a5729e1a1e0ca370e42b55bf3870a148b83c03163a8c4"
+}
diff --git a/rust/personhog-identity/.sqlx/query-5d8d6706287fed19f5774a13d9ebaeeb0c55c5cebe5a92678b699ec2bf18a563.json b/rust/personhog-identity/.sqlx/query-5d8d6706287fed19f5774a13d9ebaeeb0c55c5cebe5a92678b699ec2bf18a563.json
new file mode 100644
index 000000000000..0691c1cac5ea
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-5d8d6706287fed19f5774a13d9ebaeeb0c55c5cebe5a92678b699ec2bf18a563.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp SET status = $2\n WHERE op_id = $1 AND person_id = ANY($3) AND status = $4\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8Array",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5d8d6706287fed19f5774a13d9ebaeeb0c55c5cebe5a92678b699ec2bf18a563"
+}
diff --git a/rust/personhog-identity/.sqlx/query-62e4cad720796efa7b7a3549604edfe22ddb937259ce4b84075edec522c717c8.json b/rust/personhog-identity/.sqlx/query-62e4cad720796efa7b7a3549604edfe22ddb937259ce4b84075edec522c717c8.json
new file mode 100644
index 000000000000..b1460a2ede0e
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-62e4cad720796efa7b7a3549604edfe22ddb937259ce4b84075edec522c717c8.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp lop\n SET moved = u.moved\n FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8Array",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "62e4cad720796efa7b7a3549604edfe22ddb937259ce4b84075edec522c717c8"
+}
diff --git a/rust/personhog-identity/.sqlx/query-63aa22b837ff5f79d49811215c781ba8d6947659cbd7d20bb91dc2e998007597.json b/rust/personhog-identity/.sqlx/query-63aa22b837ff5f79d49811215c781ba8d6947659cbd7d20bb91dc2e998007597.json
new file mode 100644
index 000000000000..ec59310370aa
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-63aa22b837ff5f79d49811215c781ba8d6947659cbd7d20bb91dc2e998007597.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT op_id, op_type\n FROM lifecycle_op_tmp\n WHERE completed_at IS NULL\n AND parked_at IS NULL\n AND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))\n OR lease_expires_at < now())\n ORDER BY created_at\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "op_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Float8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "63aa22b837ff5f79d49811215c781ba8d6947659cbd7d20bb91dc2e998007597"
+}
diff --git a/rust/personhog-identity/.sqlx/query-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.json b/rust/personhog-identity/.sqlx/query-674cce2c61ac403d706c4dede5bbdaf230c06a3e749eeb07a871b128d214b865.json
similarity index 61%
rename from rust/personhog-identity/.sqlx/query-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.json
rename to rust/personhog-identity/.sqlx/query-674cce2c61ac403d706c4dede5bbdaf230c06a3e749eeb07a871b128d214b865.json
index 7c751cf0995a..3e6c5395d778 100644
--- a/rust/personhog-identity/.sqlx/query-049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9.json
+++ b/rust/personhog-identity/.sqlx/query-674cce2c61ac403d706c4dede5bbdaf230c06a3e749eeb07a871b128d214b865.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT person_id, person_uuid FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')\n ",
+ "query": "\n SELECT person_id, person_uuid FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')\n ",
"describe": {
"columns": [
{
@@ -25,5 +25,5 @@
false
]
},
- "hash": "049fb8cb41a108c6dc1af52f139e5c6b3fdf8cc7636d8f82c7eaf668860b6cc9"
+ "hash": "674cce2c61ac403d706c4dede5bbdaf230c06a3e749eeb07a871b128d214b865"
}
diff --git a/rust/personhog-identity/.sqlx/query-6cc77f114a2d7432de4d6aa4b39c3066aeacf159d123a7b679b754708328b15a.json b/rust/personhog-identity/.sqlx/query-6cc77f114a2d7432de4d6aa4b39c3066aeacf159d123a7b679b754708328b15a.json
new file mode 100644
index 000000000000..c94c3688640b
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-6cc77f114a2d7432de4d6aa4b39c3066aeacf159d123a7b679b754708328b15a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_tmp SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6cc77f114a2d7432de4d6aa4b39c3066aeacf159d123a7b679b754708328b15a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-6e26f63eeb15d8f8ba7c124a5ef93948fba9fff8d070a96a7e17adddf49825dd.json b/rust/personhog-identity/.sqlx/query-6e26f63eeb15d8f8ba7c124a5ef93948fba9fff8d070a96a7e17adddf49825dd.json
new file mode 100644
index 000000000000..d6c9fa258835
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-6e26f63eeb15d8f8ba7c124a5ef93948fba9fff8d070a96a7e17adddf49825dd.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_person_tmp (op_id, team_id, person_id, person_uuid, role, status)\n SELECT $1, $2, u.person_id, u.person_uuid, 'victim', $5\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\n ON CONFLICT (op_id, person_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Int8Array",
+ "UuidArray",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6e26f63eeb15d8f8ba7c124a5ef93948fba9fff8d070a96a7e17adddf49825dd"
+}
diff --git a/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.json b/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.json
deleted file mode 100644
index b4e264b42e44..000000000000
--- a/rust/personhog-identity/.sqlx/query-73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "73325caf0fbd5dc20fd8dcd13f826ce1ad764f31e97903752a61309ade88e816"
-}
diff --git a/rust/personhog-identity/.sqlx/query-7634df4ebfd768f0bf1af3719ac9fab2836d64f9c898a71ac4b5da7c95860fe0.json b/rust/personhog-identity/.sqlx/query-7634df4ebfd768f0bf1af3719ac9fab2836d64f9c898a71ac4b5da7c95860fe0.json
new file mode 100644
index 000000000000..64ab22b8bc8f
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-7634df4ebfd768f0bf1af3719ac9fab2836d64f9c898a71ac4b5da7c95860fe0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND status IN ('marked', 'sealed')\n ORDER BY person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7634df4ebfd768f0bf1af3719ac9fab2836d64f9c898a71ac4b5da7c95860fe0"
+}
diff --git a/rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.json b/rust/personhog-identity/.sqlx/query-7a6d44a6e1ea0c2f6da0ce42b8077946a128fd64c4a8751b59cbb26062dc0809.json
similarity index 55%
rename from rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.json
rename to rust/personhog-identity/.sqlx/query-7a6d44a6e1ea0c2f6da0ce42b8077946a128fd64c4a8751b59cbb26062dc0809.json
index cd28cc3a4f68..6e480d38cdf0 100644
--- a/rust/personhog-identity/.sqlx/query-5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e.json
+++ b/rust/personhog-identity/.sqlx/query-7a6d44a6e1ea0c2f6da0ce42b8077946a128fd64c4a8751b59cbb26062dc0809.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT person_id, ordinal as \"ordinal!\", sealed as \"sealed!\" FROM lifecycle_op_person\n WHERE op_id = $1 AND role = $2 AND status = $3\n ORDER BY ordinal\n ",
+ "query": "\n SELECT person_id, person_uuid, ordinal as \"ordinal!\", sealed as \"sealed!\"\n FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND role = $2 AND status = $3\n ORDER BY ordinal\n ",
"describe": {
"columns": [
{
@@ -10,11 +10,16 @@
},
{
"ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
"name": "ordinal!",
"type_info": "Int4"
},
{
- "ordinal": 2,
+ "ordinal": 3,
"name": "sealed!",
"type_info": "Jsonb"
}
@@ -27,10 +32,11 @@
]
},
"nullable": [
+ false,
false,
true,
true
]
},
- "hash": "5c11f83472e2ceb6a0bc29fd636d1ac4521bf5bae6466d664a32cde3b9ad3a7e"
+ "hash": "7a6d44a6e1ea0c2f6da0ce42b8077946a128fd64c4a8751b59cbb26062dc0809"
}
diff --git a/rust/personhog-identity/.sqlx/query-7b9dc54935ae723e504b17a5ce3386bfad3a3df8f759243ab17c4ea86818afe4.json b/rust/personhog-identity/.sqlx/query-7b9dc54935ae723e504b17a5ce3386bfad3a3df8f759243ab17c4ea86818afe4.json
new file mode 100644
index 000000000000..1922463f1b53
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-7b9dc54935ae723e504b17a5ce3386bfad3a3df8f759243ab17c4ea86818afe4.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_tmp SET step = $3 WHERE op_id = $1 AND step = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7b9dc54935ae723e504b17a5ce3386bfad3a3df8f759243ab17c4ea86818afe4"
+}
diff --git a/rust/personhog-identity/.sqlx/query-861000d503a7b397d7dd8c8ea9013180941367370f7b229ddf3c6c5509d64264.json b/rust/personhog-identity/.sqlx/query-861000d503a7b397d7dd8c8ea9013180941367370f7b229ddf3c6c5509d64264.json
new file mode 100644
index 000000000000..5c446b923bd5
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-861000d503a7b397d7dd8c8ea9013180941367370f7b229ddf3c6c5509d64264.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op_tmp\n WHERE op_id = $1\n AND completed_at IS NOT NULL\n AND (outcome->>'claim_abort')::boolean IS TRUE\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "861000d503a7b397d7dd8c8ea9013180941367370f7b229ddf3c6c5509d64264"
+}
diff --git a/rust/personhog-identity/.sqlx/query-91d9dbaa08c3a452ceffa3973531e90b8d550614f6d35ba0f2268477daf6c154.json b/rust/personhog-identity/.sqlx/query-91d9dbaa08c3a452ceffa3973531e90b8d550614f6d35ba0f2268477daf6c154.json
new file mode 100644
index 000000000000..577b50457287
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-91d9dbaa08c3a452ceffa3973531e90b8d550614f6d35ba0f2268477daf6c154.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person_tmp SET moved = $2 WHERE op_id = $1 AND role = $3",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "91d9dbaa08c3a452ceffa3973531e90b8d550614f6d35ba0f2268477daf6c154"
+}
diff --git a/rust/personhog-identity/.sqlx/query-92c29db912ef3e1b6e957026d5c403933a4d51e930677b5cf4ff6f1ed1d8f828.json b/rust/personhog-identity/.sqlx/query-92c29db912ef3e1b6e957026d5c403933a4d51e930677b5cf4ff6f1ed1d8f828.json
new file mode 100644
index 000000000000..66045a1438b7
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-92c29db912ef3e1b6e957026d5c403933a4d51e930677b5cf4ff6f1ed1d8f828.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id, status FROM lifecycle_op_person_tmp WHERE op_id = $1 AND role = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "status",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "92c29db912ef3e1b6e957026d5c403933a4d51e930677b5cf4ff6f1ed1d8f828"
+}
diff --git a/rust/personhog-identity/.sqlx/query-9741cc608fcf8b1b7b0a0b373d033ae6983a7a6bd85dc3e9c80c1a918f171c52.json b/rust/personhog-identity/.sqlx/query-9741cc608fcf8b1b7b0a0b373d033ae6983a7a6bd85dc3e9c80c1a918f171c52.json
new file mode 100644
index 000000000000..8b1a0e4b21cc
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-9741cc608fcf8b1b7b0a0b373d033ae6983a7a6bd85dc3e9c80c1a918f171c52.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id, status FROM lifecycle_op_person_tmp WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "status",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "9741cc608fcf8b1b7b0a0b373d033ae6983a7a6bd85dc3e9c80c1a918f171c52"
+}
diff --git a/rust/personhog-identity/.sqlx/query-976a7d5d788615a8fbb8abcacb9ff7bb68d486a801299b37960abc4bc731446d.json b/rust/personhog-identity/.sqlx/query-976a7d5d788615a8fbb8abcacb9ff7bb68d486a801299b37960abc4bc731446d.json
new file mode 100644
index 000000000000..7034229cb336
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-976a7d5d788615a8fbb8abcacb9ff7bb68d486a801299b37960abc4bc731446d.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_person_tmp\n (op_id, team_id, person_id, person_uuid, role, ordinal, status)\n SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, $6\n FROM unnest($3::bigint[], $4::uuid[], $5::text[], $7::int[])\n AS u(person_id, person_uuid, role, ordinal)\n ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING\n RETURNING person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Int8Array",
+ "UuidArray",
+ "TextArray",
+ "Text",
+ "Int4Array"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "976a7d5d788615a8fbb8abcacb9ff7bb68d486a801299b37960abc4bc731446d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-97ee021ad5a713ee978c00ca5888553fc946343e4067325ecfbd5d68a26cb61f.json b/rust/personhog-identity/.sqlx/query-97ee021ad5a713ee978c00ca5888553fc946343e4067325ecfbd5d68a26cb61f.json
new file mode 100644
index 000000000000..c6c11f44be8d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-97ee021ad5a713ee978c00ca5888553fc946343e4067325ecfbd5d68a26cb61f.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id, person_uuid FROM lifecycle_op_person_tmp WHERE op_id = $1 AND role = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "97ee021ad5a713ee978c00ca5888553fc946343e4067325ecfbd5d68a26cb61f"
+}
diff --git a/rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json b/rust/personhog-identity/.sqlx/query-99d01a6a317b43b7ca38c44dba30b85b011f34aa9f880622b58957b0791176eb.json
similarity index 55%
rename from rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json
rename to rust/personhog-identity/.sqlx/query-99d01a6a317b43b7ca38c44dba30b85b011f34aa9f880622b58957b0791176eb.json
index 6c68dc034190..583439dcfcb4 100644
--- a/rust/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json
+++ b/rust/personhog-identity/.sqlx/query-99d01a6a317b43b7ca38c44dba30b85b011f34aa9f880622b58957b0791176eb.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1",
+ "query": "SELECT step, completed_at IS NOT NULL AS \"completed!\" FROM lifecycle_op WHERE op_id = $1",
"describe": {
"columns": [
{
@@ -10,8 +10,8 @@
},
{
"ordinal": 1,
- "name": "completed_at",
- "type_info": "Timestamptz"
+ "name": "completed!",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -21,8 +21,8 @@
},
"nullable": [
false,
- true
+ null
]
},
- "hash": "4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd"
+ "hash": "99d01a6a317b43b7ca38c44dba30b85b011f34aa9f880622b58957b0791176eb"
}
diff --git a/rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json b/rust/personhog-identity/.sqlx/query-99eaa599f1e6ccfb66a2f35ed78a49841cf5ead9316ab84c0a82344bdff1748b.json
similarity index 54%
rename from rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json
rename to rust/personhog-identity/.sqlx/query-99eaa599f1e6ccfb66a2f35ed78a49841cf5ead9316ab84c0a82344bdff1748b.json
index 6c68dc034190..63144b6d929b 100644
--- a/rust/personhog-identity/.sqlx/query-4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd.json
+++ b/rust/personhog-identity/.sqlx/query-99eaa599f1e6ccfb66a2f35ed78a49841cf5ead9316ab84c0a82344bdff1748b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1",
+ "query": "SELECT step, completed_at IS NOT NULL AS \"completed!\" FROM lifecycle_op_tmp WHERE op_id = $1",
"describe": {
"columns": [
{
@@ -10,8 +10,8 @@
},
{
"ordinal": 1,
- "name": "completed_at",
- "type_info": "Timestamptz"
+ "name": "completed!",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -21,8 +21,8 @@
},
"nullable": [
false,
- true
+ null
]
},
- "hash": "4f7055551415aa49ddb2798120763770e4125150bd4c7c2774f2266ecd851bbd"
+ "hash": "99eaa599f1e6ccfb66a2f35ed78a49841cf5ead9316ab84c0a82344bdff1748b"
}
diff --git a/rust/personhog-identity/.sqlx/query-a007ed0c33229298558f8e524c06c2d2b05261da6df92f236f7942d2cf63f875.json b/rust/personhog-identity/.sqlx/query-a007ed0c33229298558f8e524c06c2d2b05261da6df92f236f7942d2cf63f875.json
new file mode 100644
index 000000000000..b906a1f5ebf6
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a007ed0c33229298558f8e524c06c2d2b05261da6df92f236f7942d2cf63f875.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_tmp\n SET parked_at = now(), parked_reason = $3, lease_expires_at = NULL\n WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a007ed0c33229298558f8e524c06c2d2b05261da6df92f236f7942d2cf63f875"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ac1dde53a6fb65814617b3acaaba824b10c2f96110b5e1fc0df9200e0dc85350.json b/rust/personhog-identity/.sqlx/query-ac1dde53a6fb65814617b3acaaba824b10c2f96110b5e1fc0df9200e0dc85350.json
new file mode 100644
index 000000000000..5a3122c38178
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ac1dde53a6fb65814617b3acaaba824b10c2f96110b5e1fc0df9200e0dc85350.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp SET status = $2\n WHERE op_id = $1 AND person_id = ANY($3) AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ac1dde53a6fb65814617b3acaaba824b10c2f96110b5e1fc0df9200e0dc85350"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b08fe9afd0c1e3444997a79e0e63c2348dcce846cac828579d5c4b39acde2cda.json b/rust/personhog-identity/.sqlx/query-b08fe9afd0c1e3444997a79e0e63c2348dcce846cac828579d5c4b39acde2cda.json
new file mode 100644
index 000000000000..6cb73841b854
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b08fe9afd0c1e3444997a79e0e63c2348dcce846cac828579d5c4b39acde2cda.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT person_id, person_uuid FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "person_uuid",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "b08fe9afd0c1e3444997a79e0e63c2348dcce846cac828579d5c4b39acde2cda"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b3916bffff20a5d932cefa8abce5ce8758ca406e915cbb10823308745de16b42.json b/rust/personhog-identity/.sqlx/query-b3916bffff20a5d932cefa8abce5ce8758ca406e915cbb10823308745de16b42.json
new file mode 100644
index 000000000000..ac4cd99088c9
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b3916bffff20a5d932cefa8abce5ce8758ca406e915cbb10823308745de16b42.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp lop\n SET status = $2, sealed = jsonb_build_object('version', u.version, 'created_at', u.created_at)\n FROM unnest($3::bigint[], $4::bigint[], $5::bigint[]) AS u(person_id, version, created_at)\n WHERE lop.op_id = $1 AND lop.person_id = u.person_id\n AND lop.status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8Array",
+ "Int8Array",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b3916bffff20a5d932cefa8abce5ce8758ca406e915cbb10823308745de16b42"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b975d5dde18eabd1037f9b8b74814ed721b37914a116a9dac7276773bb3ca2bd.json b/rust/personhog-identity/.sqlx/query-b975d5dde18eabd1037f9b8b74814ed721b37914a116a9dac7276773bb3ca2bd.json
new file mode 100644
index 000000000000..4edfb2e58a98
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b975d5dde18eabd1037f9b8b74814ed721b37914a116a9dac7276773bb3ca2bd.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op_tmp\n WHERE op_id IN (\n SELECT op_id FROM lifecycle_op_tmp\n WHERE completed_at IS NOT NULL\n AND completed_at < now() - make_interval(secs => $1)\n LIMIT $2\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Float8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b975d5dde18eabd1037f9b8b74814ed721b37914a116a9dac7276773bb3ca2bd"
+}
diff --git a/rust/personhog-identity/.sqlx/query-c6930abebbc067b91d8a32bd42345980966f7d690949a1825f8a1e6fcaa93b12.json b/rust/personhog-identity/.sqlx/query-c6930abebbc067b91d8a32bd42345980966f7d690949a1825f8a1e6fcaa93b12.json
new file mode 100644
index 000000000000..d439deddb7ed
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-c6930abebbc067b91d8a32bd42345980966f7d690949a1825f8a1e6fcaa93b12.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id FROM lifecycle_op_person_tmp WHERE op_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "c6930abebbc067b91d8a32bd42345980966f7d690949a1825f8a1e6fcaa93b12"
+}
diff --git a/rust/personhog-identity/.sqlx/query-c7b69fa9c1c3b52181bdfe1d014e8f430a8595b3f34ac6ce81155ba6d5736145.json b/rust/personhog-identity/.sqlx/query-c7b69fa9c1c3b52181bdfe1d014e8f430a8595b3f34ac6ce81155ba6d5736145.json
new file mode 100644
index 000000000000..7d47d079030c
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-c7b69fa9c1c3b52181bdfe1d014e8f430a8595b3f34ac6ce81155ba6d5736145.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE lifecycle_op_person_tmp SET sealed = $2 WHERE op_id = $1 AND role = $3",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c7b69fa9c1c3b52181bdfe1d014e8f430a8595b3f34ac6ce81155ba6d5736145"
+}
diff --git a/rust/personhog-identity/.sqlx/query-c838686fae3baca96c8e3797f93df92b75c1f5a805ecc94b3cb074e4ca1a0cd2.json b/rust/personhog-identity/.sqlx/query-c838686fae3baca96c8e3797f93df92b75c1f5a805ecc94b3cb074e4ca1a0cd2.json
new file mode 100644
index 000000000000..2da24ab075e3
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-c838686fae3baca96c8e3797f93df92b75c1f5a805ecc94b3cb074e4ca1a0cd2.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp SET status = $2\n WHERE op_id = $1 AND role = $3 AND status = $4\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c838686fae3baca96c8e3797f93df92b75c1f5a805ecc94b3cb074e4ca1a0cd2"
+}
diff --git a/rust/personhog-identity/.sqlx/query-d4f56152cd8a92017072440e819579ce8100e1cd7bbb3c2eac05ecf201ded18d.json b/rust/personhog-identity/.sqlx/query-d4f56152cd8a92017072440e819579ce8100e1cd7bbb3c2eac05ecf201ded18d.json
new file mode 100644
index 000000000000..f6be54b6766b
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-d4f56152cd8a92017072440e819579ce8100e1cd7bbb3c2eac05ecf201ded18d.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d4f56152cd8a92017072440e819579ce8100e1cd7bbb3c2eac05ecf201ded18d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-d72b3ff8a3a8e26fdf5468df52e23c8011d97a31dd867f7f8ae2f79803564135.json b/rust/personhog-identity/.sqlx/query-d72b3ff8a3a8e26fdf5468df52e23c8011d97a31dd867f7f8ae2f79803564135.json
new file mode 100644
index 000000000000..a29a5620dd82
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-d72b3ff8a3a8e26fdf5468df52e23c8011d97a31dd867f7f8ae2f79803564135.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_tmp (op_id, op_type, team_id, step, request)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (op_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int4",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d72b3ff8a3a8e26fdf5468df52e23c8011d97a31dd867f7f8ae2f79803564135"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ddf12809e2725d7c250b921bb382dc0e9d2f9a46765995ccc761d83bfaea2c1f.json b/rust/personhog-identity/.sqlx/query-ddf12809e2725d7c250b921bb382dc0e9d2f9a46765995ccc761d83bfaea2c1f.json
new file mode 100644
index 000000000000..7c566d17ba6d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ddf12809e2725d7c250b921bb382dc0e9d2f9a46765995ccc761d83bfaea2c1f.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_tmp\n SET lease_expires_at = now() + make_interval(secs => $2),\n attempt = attempt + 1,\n parked_at = NULL,\n parked_reason = NULL\n WHERE op_id IN (\n SELECT op_id FROM lifecycle_op_tmp\n WHERE op_id = $1 AND completed_at IS NULL\n AND (lease_expires_at IS NULL OR lease_expires_at < now())\n AND (parked_at IS NULL OR $3)\n FOR UPDATE SKIP LOCKED\n )\n RETURNING attempt\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "attempt",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Float8",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "ddf12809e2725d7c250b921bb382dc0e9d2f9a46765995ccc761d83bfaea2c1f"
+}
diff --git a/rust/personhog-identity/.sqlx/query-de27cb046ae480023e0b730c8af984215a4e60ae607515da62ff3c12165164af.json b/rust/personhog-identity/.sqlx/query-de27cb046ae480023e0b730c8af984215a4e60ae607515da62ff3c12165164af.json
new file mode 100644
index 000000000000..5bff85b0bba1
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-de27cb046ae480023e0b730c8af984215a4e60ae607515da62ff3c12165164af.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE lifecycle_op_person_tmp SET status = $2\n WHERE op_id = $1 AND role = $3 AND status = $4\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "de27cb046ae480023e0b730c8af984215a4e60ae607515da62ff3c12165164af"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e1c252814f3106c54c990bd5c5fdf1a00ea056549bb2c823e223d30968af65a0.json b/rust/personhog-identity/.sqlx/query-e1c252814f3106c54c990bd5c5fdf1a00ea056549bb2c823e223d30968af65a0.json
new file mode 100644
index 000000000000..36721ee49138
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e1c252814f3106c54c990bd5c5fdf1a00ea056549bb2c823e223d30968af65a0.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT person_id FROM lifecycle_op_person_tmp WHERE op_id = $1 AND role = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e1c252814f3106c54c990bd5c5fdf1a00ea056549bb2c823e223d30968af65a0"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e982d1b2cb225fe19e84ab0f31a09e5c5c6f0e5671347f4ff011a49545a1c26d.json b/rust/personhog-identity/.sqlx/query-e982d1b2cb225fe19e84ab0f31a09e5c5c6f0e5671347f4ff011a49545a1c26d.json
new file mode 100644
index 000000000000..afb72f4140ec
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e982d1b2cb225fe19e84ab0f31a09e5c5c6f0e5671347f4ff011a49545a1c26d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT moved FROM lifecycle_op_person_tmp WHERE op_id = $1 AND role = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "moved",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "e982d1b2cb225fe19e84ab0f31a09e5c5c6f0e5671347f4ff011a49545a1c26d"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ea96e264833f90d30dfcdb26f5fb4e57f6977ea28b18c9a9e892a29358b5a430.json b/rust/personhog-identity/.sqlx/query-ea96e264833f90d30dfcdb26f5fb4e57f6977ea28b18c9a9e892a29358b5a430.json
new file mode 100644
index 000000000000..896db32a05b5
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ea96e264833f90d30dfcdb26f5fb4e57f6977ea28b18c9a9e892a29358b5a430.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op_person_tmp\n WHERE op_id = $1 AND person_id = ANY($2) AND status IN ('marked', 'sealed')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ea96e264833f90d30dfcdb26f5fb4e57f6977ea28b18c9a9e892a29358b5a430"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ed5d9f2c07a384eeeb28263d78d0dbf1e6aad8c292f04e1946789162f7645bc1.json b/rust/personhog-identity/.sqlx/query-ed5d9f2c07a384eeeb28263d78d0dbf1e6aad8c292f04e1946789162f7645bc1.json
new file mode 100644
index 000000000000..12a5e568daa2
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ed5d9f2c07a384eeeb28263d78d0dbf1e6aad8c292f04e1946789162f7645bc1.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM lifecycle_op_person_tmp WHERE op_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ed5d9f2c07a384eeeb28263d78d0dbf1e6aad8c292f04e1946789162f7645bc1"
+}
diff --git a/rust/personhog-identity/.sqlx/query-fb5d7e6f0cadd899d20997f107f302ccfac9fa853207a03b65dc68e195292a7a.json b/rust/personhog-identity/.sqlx/query-fb5d7e6f0cadd899d20997f107f302ccfac9fa853207a03b65dc68e195292a7a.json
new file mode 100644
index 000000000000..56bdac6ee405
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-fb5d7e6f0cadd899d20997f107f302ccfac9fa853207a03b65dc68e195292a7a.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) AS \"count!\" FROM lifecycle_op_tmp WHERE completed_at IS NULL AND parked_at IS NOT NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "fb5d7e6f0cadd899d20997f107f302ccfac9fa853207a03b65dc68e195292a7a"
+}
diff --git a/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.json b/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.json
deleted file mode 100644
index 0c19a9b439c8..000000000000
--- a/rust/personhog-identity/.sqlx/query-fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE lifecycle_op_person SET status = $2\n WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "fd4ed67f3f81873078b959e1109810e95f9ad7e322af0039af101db3c6d53f97"
-}
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
index 032e895c64e6..da7aed8b58c9 100644
--- a/rust/personhog-identity/Cargo.toml
+++ b/rust/personhog-identity/Cargo.toml
@@ -10,6 +10,7 @@ personhog-proto = { path = "../personhog-proto" }
common-database = { path = "../common/database" }
common-alloc = { path = "../common/alloc" }
common-metrics = { path = "../common/metrics" }
+common-sqlx-macros = { path = "../common/sqlx-macros" }
lifecycle = { path = "../common/lifecycle" }
async-trait = { workspace = true }
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index f1fba2ffb794..bc19dc8464a1 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -34,6 +34,15 @@ pub struct Config {
#[envconfig(default = "personhog_featureflaghashkeyoverride_tmp")]
pub ff_hash_key_override_table: String,
+ /// Saga state table. Same namespace rule as PERSON_TABLE; the leader
+ /// derives the same pair from FALLBACK_TABLE. Set to "lifecycle_op" at cutover.
+ #[envconfig(default = "lifecycle_op_tmp")]
+ pub lifecycle_op_table: String,
+
+ /// Claim table paired with LIFECYCLE_OP_TABLE. Set to "lifecycle_op_person" at cutover.
+ #[envconfig(default = "lifecycle_op_person_tmp")]
+ pub lifecycle_op_person_table: String,
+
#[envconfig(default = "10")]
pub max_pg_connections: u32,
@@ -169,13 +178,16 @@ pub struct Config {
/// 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.
+/// person ids, plus the saga tables whose marks claim those ids. All five
+/// 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,
+ pub lifecycle_op: String,
+ pub lifecycle_op_person: String,
}
impl IdentityTables {
@@ -184,6 +196,8 @@ impl IdentityTables {
person: "posthog_person".to_string(),
person_distinct_id: "posthog_persondistinctid".to_string(),
ff_hash_key_override: "posthog_featureflaghashkeyoverride".to_string(),
+ lifecycle_op: "lifecycle_op".to_string(),
+ lifecycle_op_person: "lifecycle_op_person".to_string(),
}
}
@@ -192,9 +206,16 @@ impl IdentityTables {
person: "personhog_person_tmp".to_string(),
person_distinct_id: "personhog_persondistinctid_tmp".to_string(),
ff_hash_key_override: "personhog_featureflaghashkeyoverride_tmp".to_string(),
+ lifecycle_op: "lifecycle_op_tmp".to_string(),
+ lifecycle_op_person: "lifecycle_op_person_tmp".to_string(),
}
}
+ /// Whether this is the validation set, for `mirrored_query!` and kin.
+ pub fn is_validation(&self) -> bool {
+ *self == Self::validation()
+ }
+
/// 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
@@ -205,8 +226,8 @@ impl IdentityTables {
}
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"
+ FF_HASH_KEY_OVERRIDE_TABLE, LIFECYCLE_OP_TABLE, and LIFECYCLE_OP_PERSON_TABLE \
+ together, to either the full real set or the full validation set"
))
}
}
@@ -217,6 +238,8 @@ impl Config {
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(),
+ lifecycle_op: self.lifecycle_op_table.clone(),
+ lifecycle_op_person: self.lifecycle_op_person_table.clone(),
}
}
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index 80df8909239c..4298d6cefb19 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -23,6 +23,7 @@
use std::sync::Arc;
use async_trait::async_trait;
+use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use futures::stream::{self, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -141,6 +142,18 @@ fn record_outcomes(outcome: &Value) {
}
}
+struct PersonStatus {
+ person_id: i64,
+ status: String,
+}
+
+struct FencedVictim {
+ person_id: i64,
+ person_uuid: Uuid,
+ sealed_version: i64,
+ sealed_created_at: i64,
+}
+
pub struct DeleteDriver {
leader: Arc<dyn LifecycleLeader>,
tables: IdentityTables,
@@ -181,13 +194,27 @@ impl OpDriver for DeleteDriver {
))
})?;
match step {
- DeleteStep::Started => mark(pool, &self.tables.person, op).await,
+ DeleteStep::Started => mark(pool, &self.tables, op).await,
DeleteStep::Marked => {
- seal(pool, self.leader.as_ref(), self.leader_call_concurrency, op).await
+ seal(
+ pool,
+ self.leader.as_ref(),
+ &self.tables,
+ self.leader_call_concurrency,
+ op,
+ )
+ .await
}
DeleteStep::Sealed => unmap(pool, &self.tables, op).await,
DeleteStep::Unmapped => {
- complete(pool, self.leader.as_ref(), self.leader_call_concurrency, op).await
+ complete(
+ pool,
+ self.leader.as_ref(),
+ &self.tables,
+ self.leader_call_concurrency,
+ op,
+ )
+ .await
}
}
}
@@ -208,19 +235,20 @@ 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, person_table: &str, op: &OpRow) -> Result<(), SagaError> {
+async fn mark(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
+ let person_table = &tables.person;
let mut tx = begin_timed(pool).await?;
// Rows from a previous attempt of this op (crash between the insert and
// the advance): whatever they claimed stays claimed.
- let existing: Vec<i64> = sqlx::query_scalar!(
- "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1",
+ let existing: Vec<i64> = mirrored_query_scalar!(
+ tables.is_validation(),
+ "SELECT person_id FROM {lifecycle_op_person} WHERE op_id = $1",
op.op_id
- )
- .fetch_all(&mut *tx)
- .await?;
+ => fetch_all(&mut *tx)
+ )?;
// Sorted + deduped by the mark's conflict key so concurrent ops touching
// the same persons take row locks in the same order.
@@ -250,9 +278,10 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
// The mark: inserting the row is claiming the person; a unique violation
// on the partial mark index IS the conflict with another live op.
- let marked: Vec<i64> = sqlx::query_scalar!(
+ let marked: Vec<i64> = mirrored_query_scalar!(
+ tables.is_validation(),
r#"
- INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)
+ INSERT INTO {lifecycle_op_person} (op_id, team_id, person_id, person_uuid, role, status)
SELECT $1, $2, u.person_id, u.person_uuid, 'victim', $5
FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
ON CONFLICT (team_id, person_id) WHERE status IN ('marked', 'sealed') DO NOTHING
@@ -262,10 +291,9 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
team_id,
&live_ids,
&live_uuids,
- STATUS_MARKED,
- )
- .fetch_all(&mut *tx)
- .await?;
+ STATUS_MARKED
+ => fetch_all(&mut *tx)
+ )?;
// Victims another live op holds: record the skip (the status keeps the
// row outside the mark index). ON CONFLICT on the primary key covers a
@@ -281,9 +309,10 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
.map(|(_, uuid)| *uuid)
.collect();
if !conflicted_ids.is_empty() {
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)
+ INSERT INTO {lifecycle_op_person} (op_id, team_id, person_id, person_uuid, role, status)
SELECT $1, $2, u.person_id, u.person_uuid, 'victim', $5
FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
ON CONFLICT (op_id, person_id) DO NOTHING
@@ -292,10 +321,9 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
team_id,
&conflicted_ids,
&conflicted_uuids,
- STATUS_SKIPPED_CONFLICT,
- )
- .execute(&mut *tx)
- .await?;
+ STATUS_SKIPPED_CONFLICT
+ => execute(&mut *tx)
+ )?;
}
// The live filter above and the mark insert run in different
@@ -305,13 +333,14 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
// touched again. From here on the mark keeps every held person alive.
let corpse_sql = format!(
r#"
- DELETE FROM lifecycle_op_person lop
+ DELETE FROM {lop_table} lop
WHERE lop.op_id = $1 AND lop.status = 'marked'
AND NOT EXISTS (
SELECT 1 FROM {person_table} p
WHERE p.team_id = $2 AND p.id = lop.person_id AND p.is_deleted = false
)
- "#
+ "#,
+ lop_table = tables.lifecycle_op_person,
);
sqlx::query(&corpse_sql)
.bind(op.op_id)
@@ -319,23 +348,24 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
.execute(&mut *tx)
.await?;
- let claims: i64 = sqlx::query_scalar!(
+ let claims: i64 = mirrored_query_scalar!(
+ tables.is_validation(),
r#"
- SELECT count(*) as "count!" FROM lifecycle_op_person
+ SELECT count(*) as "count!" FROM {lifecycle_op_person}
WHERE op_id = $1 AND status IN ('marked', 'sealed')
"#,
op.op_id
- )
- .fetch_one(&mut *tx)
- .await?;
+ => fetch_one(&mut *tx)
+ )?;
let mut abort_outcome: Option<Value> = None;
let advanced = if claims == 0 {
// Every requested person was conflicted or missing: nothing was (or
// will be) mutated, so the op ends here as aborted.
- let outcome = build_outcome(&mut tx, op.op_id, &request.person_ids).await?;
+ let outcome = build_outcome(&mut tx, tables, op.op_id, &request.person_ids).await?;
let advanced = complete_op_in_tx(
&mut tx,
+ tables,
op.op_id,
DeleteStep::Started.as_str(),
STEP_ABORTED,
@@ -347,6 +377,7 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
} else {
advance_step_in_tx(
&mut tx,
+ tables,
op.op_id,
DeleteStep::Started.as_str(),
DeleteStep::Marked.as_str(),
@@ -386,30 +417,30 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
async fn seal(
pool: &PgPool,
leader: &dyn LifecycleLeader,
+ tables: &IdentityTables,
leader_call_concurrency: usize,
op: &OpRow,
) -> Result<(), SagaError> {
- let victims = sqlx::query!(
+ let victims: Vec<i64> = mirrored_query_scalar!(
+ tables.is_validation(),
r#"
- SELECT person_id FROM lifecycle_op_person
+ SELECT person_id FROM {lifecycle_op_person}
WHERE op_id = $1 AND status IN ('marked', 'sealed')
ORDER BY person_id
"#,
op.op_id
- )
- .fetch_all(pool)
- .await?;
+ => fetch_all(pool)
+ )?;
let fence_calls: Vec<_> = victims
.iter()
- .map(|victim| {
+ .map(|&person_id| {
let request = FencePersonRequest {
team_id: op.team_id,
- person_id: victim.person_id,
+ person_id,
op_id: op.op_id.to_string(),
op_type: LifecycleOpType::Delete.into(),
};
- let person_id = victim.person_id;
async move { (person_id, leader.fence_person(request).await) }
})
.collect();
@@ -449,9 +480,10 @@ async fn seal(
}
let mut tx = begin_timed(pool).await?;
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- UPDATE lifecycle_op_person lop
+ UPDATE {lifecycle_op_person} lop
SET status = $2, sealed = jsonb_build_object('version', u.version, 'created_at', u.created_at)
FROM unnest($3::bigint[], $4::bigint[], $5::bigint[]) AS u(person_id, version, created_at)
WHERE lop.op_id = $1 AND lop.person_id = u.person_id
@@ -461,25 +493,25 @@ async fn seal(
STATUS_SEALED,
&sealed_ids,
&sealed_versions,
- &sealed_created_ats,
- )
- .execute(&mut *tx)
- .await?;
+ &sealed_created_ats
+ => execute(&mut *tx)
+ )?;
if !vanished.is_empty() {
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- DELETE FROM lifecycle_op_person
+ DELETE FROM {lifecycle_op_person}
WHERE op_id = $1 AND person_id = ANY($2) AND status IN ('marked', 'sealed')
"#,
op.op_id,
- &vanished,
- )
- .execute(&mut *tx)
- .await?;
+ &vanished
+ => execute(&mut *tx)
+ )?;
}
if !advance_step_in_tx(
&mut tx,
+ tables,
op.op_id,
DeleteStep::Marked.as_str(),
DeleteStep::Sealed.as_str(),
@@ -506,15 +538,15 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
let team_id = op.team_id as i32;
let mut tx = begin_timed(pool).await?;
- let mut victims: Vec<i64> = sqlx::query_scalar!(
+ let mut victims: Vec<i64> = mirrored_query_scalar!(
+ tables.is_validation(),
r#"
- SELECT person_id FROM lifecycle_op_person
+ SELECT person_id FROM {lifecycle_op_person}
WHERE op_id = $1 AND status = 'sealed'
"#,
op.op_id
- )
- .fetch_all(&mut *tx)
- .await?;
+ => fetch_all(&mut *tx)
+ )?;
victims.sort_unstable();
// Take every row lock this transaction will need up front, in id order,
@@ -576,19 +608,19 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
}
}
if !moved_ids.is_empty() {
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- UPDATE lifecycle_op_person lop
+ UPDATE {lifecycle_op_person} lop
SET moved = u.moved
FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)
WHERE lop.op_id = $1 AND lop.person_id = u.person_id
"#,
op.op_id,
&moved_ids,
- &moved_json,
- )
- .execute(&mut *tx)
- .await?;
+ &moved_json
+ => execute(&mut *tx)
+ )?;
}
// posthog_cohortpeople has no shadow mirror and no team_id column, so it
@@ -622,11 +654,12 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
properties_last_updated_at = '{{}}'::jsonb,
properties_last_operation = '{{}}'::jsonb,
version = (lop.sealed->>'version')::bigint + 1
- FROM lifecycle_op_person lop
+ FROM {lop_table} lop
WHERE lop.op_id = $1 AND lop.status = 'sealed'
AND p.team_id = $2 AND p.id = lop.person_id
"#,
person_table = tables.person,
+ lop_table = tables.lifecycle_op_person,
);
sqlx::query(&tombstone_sql)
.bind(op.op_id)
@@ -636,6 +669,7 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
if !advance_step_in_tx(
&mut tx,
+ tables,
op.op_id,
DeleteStep::Sealed.as_str(),
DeleteStep::Unmapped.as_str(),
@@ -665,24 +699,26 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
async fn complete(
pool: &PgPool,
leader: &dyn LifecycleLeader,
+ tables: &IdentityTables,
leader_call_concurrency: usize,
op: &OpRow,
) -> Result<(), SagaError> {
let request = parse_request(op)?;
- let fenced = sqlx::query!(
+ let fenced = mirrored_query_as!(
+ FencedVictim,
+ tables.is_validation(),
r#"
SELECT person_id, person_uuid,
(sealed->>'version')::bigint AS "sealed_version!",
(sealed->>'created_at')::bigint AS "sealed_created_at!"
- FROM lifecycle_op_person
+ FROM {lifecycle_op_person}
WHERE op_id = $1 AND status = 'sealed' AND sealed ? 'created_at'
ORDER BY person_id
"#,
op.op_id
- )
- .fetch_all(pool)
- .await?;
+ => fetch_all(pool)
+ )?;
let release_calls: Vec<_> = fenced
.iter()
.map(|victim| {
@@ -708,17 +744,18 @@ async fn complete(
let mut tx = begin_timed(pool).await?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
+ mirrored_query!(
+ tables.is_validation(),
+ "UPDATE {lifecycle_op_person} SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
op.op_id,
- STATUS_DELETED,
- )
- .execute(&mut *tx)
- .await?;
+ STATUS_DELETED
+ => execute(&mut *tx)
+ )?;
- let outcome = build_outcome(&mut tx, op.op_id, &request.person_ids).await?;
+ let outcome = build_outcome(&mut tx, tables, op.op_id, &request.person_ids).await?;
if !complete_op_in_tx(
&mut tx,
+ tables,
op.op_id,
DeleteStep::Unmapped.as_str(),
STEP_COMPLETED,
@@ -742,15 +779,17 @@ async fn complete(
/// reports `not_found`.
async fn build_outcome(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op_id: Uuid,
requested: &[i64],
) -> Result<Value, SagaError> {
- let rows = sqlx::query!(
- "SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1",
+ let rows = mirrored_query_as!(
+ PersonStatus,
+ tables.is_validation(),
+ "SELECT person_id, status FROM {lifecycle_op_person} WHERE op_id = $1",
op_id
- )
- .fetch_all(&mut **tx)
- .await?;
+ => fetch_all(&mut **tx)
+ )?;
let results = requested
.iter()
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 3e9e77d39dbc..d7f3e9330b7e 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -20,12 +20,15 @@ use std::time::{Duration, Instant};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use rand::Rng;
use serde_json::Value;
use sqlx::postgres::PgPool;
use tonic::Status;
use uuid::Uuid;
+use crate::config::IdentityTables;
+
/// Terminal step: the op ran to the end.
pub const STEP_COMPLETED: &str = "completed";
/// Terminal step: the op backed out before mutating anything.
@@ -210,17 +213,27 @@ pub struct EngineConfig {
pub struct Engine {
pool: PgPool,
config: EngineConfig,
+ tables: IdentityTables,
}
impl Engine {
- pub fn new(pool: PgPool, config: EngineConfig) -> Self {
- Self { pool, config }
+ pub fn new(pool: PgPool, config: EngineConfig, tables: IdentityTables) -> Self {
+ tables.validate().expect("invalid identity table set");
+ Self {
+ pool,
+ config,
+ tables,
+ }
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
+ pub fn tables(&self) -> &IdentityTables {
+ &self.tables
+ }
+
/// Create the op if it is new, then drive it to a terminal step and
/// return the terminal row. A retry with the same op_id attaches to the
/// existing op: completed → returns the recorded row without running
@@ -252,9 +265,10 @@ impl Engine {
team_id: i64,
request: &Value,
) -> Result<OpRow, SagaError> {
- let inserted = sqlx::query!(
+ let inserted = mirrored_query!(
+ self.tables.is_validation(),
r#"
- INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)
+ INSERT INTO {lifecycle_op} (op_id, op_type, team_id, step, request)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (op_id) DO NOTHING
"#,
@@ -262,10 +276,9 @@ impl Engine {
driver.op_type(),
team_id as i32,
driver.initial_step(),
- request,
- )
- .execute(&self.pool)
- .await?
+ request
+ => execute(&self.pool)
+ )?
.rows_affected()
> 0;
@@ -511,22 +524,23 @@ impl Engine {
}
}
- async fn load(&self, op_id: Uuid) -> Result<Option<OpRow>, sqlx::Error> {
- sqlx::query_as!(
+ /// The op row for this id, if one exists.
+ pub async fn load(&self, op_id: Uuid) -> Result<Option<OpRow>, sqlx::Error> {
+ mirrored_query_as!(
OpRow,
+ self.tables.is_validation(),
r#"
SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,
request as "request: Value", outcome as "outcome: Value",
created_at, completed_at,
(lease_expires_at IS NOT NULL AND lease_expires_at >= now())
as "lease_live!"
- FROM lifecycle_op
+ FROM {lifecycle_op}
WHERE op_id = $1
"#,
op_id
+ => fetch_optional(&self.pool)
)
- .fetch_optional(&self.pool)
- .await
}
/// Sleep one poll interval, jittered to 0.5–1.5× so waiters released by
@@ -548,15 +562,16 @@ impl Engine {
/// again beats joining a tuple-lock queue. A skipped row reads as None,
/// the same as losing the claim outright.
async fn try_claim(&self, op_id: Uuid, unpark: bool) -> Result<Option<i32>, sqlx::Error> {
- sqlx::query_scalar!(
+ mirrored_query_scalar!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op
+ UPDATE {lifecycle_op}
SET lease_expires_at = now() + make_interval(secs => $2),
attempt = attempt + 1,
parked_at = NULL,
parked_reason = NULL
WHERE op_id IN (
- SELECT op_id FROM lifecycle_op
+ SELECT op_id FROM {lifecycle_op}
WHERE op_id = $1 AND completed_at IS NULL
AND (lease_expires_at IS NULL OR lease_expires_at < now())
AND (parked_at IS NULL OR $3)
@@ -566,10 +581,9 @@ impl Engine {
"#,
op_id,
self.config.lease.as_secs_f64(),
- unpark,
+ unpark
+ => fetch_optional(&self.pool)
)
- .fetch_optional(&self.pool)
- .await
}
/// Park an op after a definitive leader refusal: record when and why,
@@ -584,18 +598,18 @@ impl Engine {
status: &Status,
) -> Result<bool, sqlx::Error> {
let reason = personhog_common::grpc::refusal_reason_label(status).to_string();
- let parked = sqlx::query!(
+ let parked = mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op
+ UPDATE {lifecycle_op}
SET parked_at = now(), parked_reason = $3, lease_expires_at = NULL
WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2
"#,
op_id,
attempt,
- reason,
- )
- .execute(&self.pool)
- .await?
+ reason
+ => execute(&self.pool)
+ )?
.rows_affected()
> 0;
if parked {
@@ -622,29 +636,29 @@ impl Engine {
/// Extend our lease. Returns false when the lease is no longer ours
/// (another driver claimed the op and bumped `attempt`).
async fn renew_lease(&self, op_id: Uuid, attempt: i32) -> Result<bool, sqlx::Error> {
- let result = sqlx::query!(
+ let result = mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op
+ UPDATE {lifecycle_op}
SET lease_expires_at = now() + make_interval(secs => $2)
WHERE op_id = $1 AND completed_at IS NULL AND attempt = $3
"#,
op_id,
self.config.lease.as_secs_f64(),
- attempt,
- )
- .execute(&self.pool)
- .await?;
+ attempt
+ => execute(&self.pool)
+ )?;
Ok(result.rows_affected() > 0)
}
async fn release_lease(&self, op_id: Uuid, attempt: i32) -> Result<(), sqlx::Error> {
- sqlx::query!(
- "UPDATE lifecycle_op SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
+ mirrored_query!(
+ self.tables.is_validation(),
+ "UPDATE {lifecycle_op} SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
op_id,
- attempt,
- )
- .execute(&self.pool)
- .await?;
+ attempt
+ => execute(&self.pool)
+ )?;
Ok(())
}
@@ -653,10 +667,12 @@ impl Engine {
/// than one lease (so a freshly created op isn't stolen from the RPC
/// about to claim it). Returns how many ops reached a terminal step.
pub async fn sweep(&self, drivers: &[&dyn OpDriver]) -> Result<u32, SagaError> {
- let abandoned = sqlx::query!(
+ let abandoned = mirrored_query_as!(
+ AbandonedOp,
+ self.tables.is_validation(),
r#"
SELECT op_id, op_type
- FROM lifecycle_op
+ FROM {lifecycle_op}
WHERE completed_at IS NULL
AND parked_at IS NULL
AND ((lease_expires_at IS NULL AND created_at < now() - make_interval(secs => $1))
@@ -665,10 +681,9 @@ impl Engine {
LIMIT $2
"#,
self.config.lease.as_secs_f64(),
- SWEEP_BATCH_SIZE,
- )
- .fetch_all(&self.pool)
- .await?;
+ SWEEP_BATCH_SIZE
+ => fetch_all(&self.pool)
+ )?;
let mut resumed = 0u32;
for op in abandoned {
@@ -699,12 +714,11 @@ impl Engine {
// The park counter dies with the process, so a gauge refreshed
// every pass keeps parked ops visible across restarts. Telemetry
// only: a failure must not fail a pass whose resumes succeeded.
- match sqlx::query_scalar!(
- r#"SELECT count(*) AS "count!" FROM lifecycle_op WHERE completed_at IS NULL AND parked_at IS NOT NULL"#
- )
- .fetch_one(&self.pool)
- .await
- {
+ match mirrored_query_scalar!(
+ self.tables.is_validation(),
+ r#"SELECT count(*) AS "count!" FROM {lifecycle_op} WHERE completed_at IS NULL AND parked_at IS NOT NULL"#
+ => fetch_one(&self.pool)
+ ) {
Ok(parked) => common_metrics::gauge(OPS_PARKED, &[], parked as f64),
Err(e) => tracing::warn!(error = %e, "failed to refresh the parked-ops gauge"),
}
@@ -716,43 +730,49 @@ impl Engine {
/// The retention window exists only for op_id idempotency — the durable
/// deletion shield is the person tombstone row, not the op row.
pub async fn gc(&self, retention: Duration) -> Result<u64, SagaError> {
- let result = sqlx::query!(
+ let result = mirrored_query!(
+ self.tables.is_validation(),
r#"
- DELETE FROM lifecycle_op
+ DELETE FROM {lifecycle_op}
WHERE op_id IN (
- SELECT op_id FROM lifecycle_op
+ SELECT op_id FROM {lifecycle_op}
WHERE completed_at IS NOT NULL
AND completed_at < now() - make_interval(secs => $1)
LIMIT $2
)
"#,
retention.as_secs_f64(),
- self.config.gc_batch_limit,
- )
- .execute(&self.pool)
- .await?;
+ self.config.gc_batch_limit
+ => execute(&self.pool)
+ )?;
Ok(result.rows_affected())
}
}
+struct AbandonedOp {
+ op_id: Uuid,
+ op_type: String,
+}
+
/// Compare-and-swap the op's step inside the step's own transaction, so the
/// work and the advance commit together. Returns false when the row is no
/// longer on `from` — another driver already advanced it; the caller must
/// roll back its transaction and let the engine reload.
pub async fn advance_step_in_tx(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op_id: Uuid,
from: &str,
to: &str,
) -> Result<bool, sqlx::Error> {
- let result = sqlx::query!(
- "UPDATE lifecycle_op SET step = $3 WHERE op_id = $1 AND step = $2",
+ let result = mirrored_query!(
+ tables.is_validation(),
+ "UPDATE {lifecycle_op} SET step = $3 WHERE op_id = $1 AND step = $2",
op_id,
from,
to
- )
- .execute(&mut **tx)
- .await?;
+ => execute(&mut **tx)
+ )?;
Ok(result.rows_affected() == 1)
}
@@ -760,23 +780,24 @@ pub async fn advance_step_in_tx(
/// `completed_at`, and drop the lease in the same compare-and-swap.
pub async fn complete_op_in_tx(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op_id: Uuid,
from: &str,
final_step: &str,
outcome: &Value,
) -> Result<bool, sqlx::Error> {
- let result = sqlx::query!(
+ let result = mirrored_query!(
+ tables.is_validation(),
r#"
- UPDATE lifecycle_op
+ UPDATE {lifecycle_op}
SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL
WHERE op_id = $1 AND step = $2
"#,
op_id,
from,
final_step,
- outcome,
- )
- .execute(&mut **tx)
- .await?;
+ outcome
+ => execute(&mut **tx)
+ )?;
Ok(result.rows_affected() == 1)
}
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 3107911a41c0..7fc9d9847b8c 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -35,6 +35,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
+use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use futures::stream::{self, StreamExt};
use personhog_common::persons::person_uuid;
use serde::{Deserialize, Serialize};
@@ -133,20 +134,49 @@ pub struct MergeSourceEntry {
}
/// Whether another driver advanced or settled the op past our step.
-async fn op_moved_on(pool: &PgPool, op: &OpRow) -> Result<bool, SagaError> {
- let current = sqlx::query!(
- r#"SELECT step, completed_at FROM lifecycle_op WHERE op_id = $1"#,
+async fn op_moved_on(
+ pool: &PgPool,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<bool, SagaError> {
+ let current = mirrored_query_as!(
+ OpProgress,
+ tables.is_validation(),
+ r#"SELECT step, completed_at IS NOT NULL AS "completed!" FROM {lifecycle_op} WHERE op_id = $1"#,
op.op_id
- )
- .fetch_optional(pool)
- .await?;
+ => fetch_optional(pool)
+ )?;
Ok(match current {
// A vanished row was completed and garbage-collected.
None => true,
- Some(row) => row.completed_at.is_some() || row.step != op.step,
+ Some(row) => row.completed || row.step != op.step,
})
}
+struct OpProgress {
+ step: String,
+ completed: bool,
+}
+
+struct PersonRef {
+ person_id: i64,
+ person_uuid: Uuid,
+}
+
+struct PersonStatus {
+ person_id: i64,
+ status: String,
+}
+
+/// A sealed source row. `ordinal` and `sealed` are set before any reader
+/// selects on `status = sealed`, so a NULL decodes as the corrupt state it is.
+struct SealedSource {
+ person_id: i64,
+ person_uuid: Uuid,
+ ordinal: i32,
+ sealed: Value,
+}
+
/// The recorded `lifecycle_op.outcome` payload: one entry per requested
/// source distinct id, in request order, plus the survivor document when
/// the merge committed.
@@ -356,22 +386,10 @@ impl MergeOpExecutor {
// handler signatures this feeds into.
#[allow(clippy::result_large_err)]
pub async fn find(&self, op_id: Uuid) -> Result<Option<OpRow>, Status> {
- sqlx::query_as!(
- OpRow,
- r#"
- SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,
- request as "request: Value", outcome as "outcome: Value",
- created_at, completed_at,
- (lease_expires_at IS NOT NULL AND lease_expires_at >= now())
- as "lease_live!"
- FROM lifecycle_op
- WHERE op_id = $1
- "#,
- op_id
- )
- .fetch_optional(self.engine.pool())
- .await
- .map_err(|e| Status::internal(format!("database error: {e}")))
+ self.engine
+ .load(op_id)
+ .await
+ .map_err(|e| Status::internal(format!("database error: {e}")))
}
/// Whether this terminal row is a disposable claim abort.
@@ -392,23 +410,27 @@ impl MergeOpExecutor {
let mut tx = begin_timed(self.engine.pool())
.await
.map_err(|e| Status::internal(format!("discard begin failed: {e}")))?;
- let deleted = sqlx::query!(
+ let tables = self.engine.tables();
+ let deleted = mirrored_query!(
+ tables.is_validation(),
r#"
- DELETE FROM lifecycle_op
+ DELETE FROM {lifecycle_op}
WHERE op_id = $1
AND completed_at IS NOT NULL
AND (outcome->>'claim_abort')::boolean IS TRUE
"#,
op_id
+ => execute(&mut *tx)
)
- .execute(&mut *tx)
- .await
.map_err(|e| Status::internal(format!("discard failed: {e}")))?;
if deleted.rows_affected() > 0 {
- sqlx::query!("DELETE FROM lifecycle_op_person WHERE op_id = $1", op_id)
- .execute(&mut *tx)
- .await
- .map_err(|e| Status::internal(format!("discard marks failed: {e}")))?;
+ mirrored_query!(
+ tables.is_validation(),
+ "DELETE FROM {lifecycle_op_person} WHERE op_id = $1",
+ op_id
+ => execute(&mut *tx)
+ )
+ .map_err(|e| Status::internal(format!("discard marks failed: {e}")))?;
}
tx.commit()
.await
@@ -618,7 +640,7 @@ impl MergeDriver {
})
.collect();
conflicts.push(("target_vanished", dispositions.len() as u64));
- return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
+ return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;
};
let (target_person_id, target_person_uuid) = (target.person_id, target.person_uuid);
@@ -728,9 +750,10 @@ impl MergeDriver {
let roles: Vec<String> = rows.iter().map(|r| r.2.to_string()).collect();
let ordinals: Vec<Option<i32>> = rows.iter().map(|r| r.3).collect();
- let marked: Vec<i64> = sqlx::query_scalar!(
+ let marked: Vec<i64> = mirrored_query_scalar!(
+ self.tables.is_validation(),
r#"
- INSERT INTO lifecycle_op_person
+ INSERT INTO {lifecycle_op_person}
(op_id, team_id, person_id, person_uuid, role, ordinal, status)
SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, $6
FROM unnest($3::bigint[], $4::uuid[], $5::text[], $7::int[])
@@ -744,23 +767,15 @@ impl MergeDriver {
&uuids,
roles.as_slice(),
STATUS_MARKED,
- ordinals.as_slice() as _,
- )
- .fetch_all(&mut *tx)
- .await?;
+ ordinals.as_slice() as _
+ => fetch_all(&mut *tx)
+ )?;
if !marked.contains(&target_person_id) {
// Another live op holds the target: abort. Flip whatever this
// insert claimed back out of the mark set in the same commit —
// nothing outside our rows has happened.
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = $3",
- op.op_id,
- STATUS_ABORTED,
- STATUS_MARKED,
- )
- .execute(&mut *tx)
- .await?;
+ unmark(&mut tx, &self.tables, op).await?;
let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE {
@@ -769,7 +784,7 @@ impl MergeDriver {
}
}
conflicts.push(("target_marked", converted));
- return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
+ return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;
}
// Sources another live op holds: record the skip (the status keeps
@@ -783,9 +798,10 @@ impl MergeDriver {
if !conflicted.is_empty() {
let conflicted_ids: Vec<i64> = conflicted.iter().map(|c| c.0).collect();
let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|c| c.1).collect();
- sqlx::query!(
+ mirrored_query!(
+ self.tables.is_validation(),
r#"
- INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)
+ INSERT INTO {lifecycle_op_person} (op_id, team_id, person_id, person_uuid, role, status)
SELECT $1, $2, u.person_id, u.person_uuid, $5, $6
FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
ON CONFLICT (op_id, person_id) DO NOTHING
@@ -795,10 +811,9 @@ impl MergeDriver {
&conflicted_ids,
&conflicted_uuids,
ROLE_SOURCE,
- STATUS_SKIPPED_CONFLICT,
- )
- .execute(&mut *tx)
- .await?;
+ STATUS_SKIPPED_CONFLICT
+ => execute(&mut *tx)
+ )?;
let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE
@@ -823,14 +838,7 @@ impl MergeDriver {
.get(&request.target_distinct_id)
.is_some_and(|r| r.person_id == target_person_id);
if !target_still_live {
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = $3",
- op.op_id,
- STATUS_ABORTED,
- STATUS_MARKED,
- )
- .execute(&mut *tx)
- .await?;
+ unmark(&mut tx, &self.tables, op).await?;
let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE {
@@ -839,7 +847,7 @@ impl MergeDriver {
}
}
conflicts.push(("target_vanished", converted));
- return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
+ return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;
}
let dropped = reconcile_pending_claims(
&mut dispositions,
@@ -849,18 +857,18 @@ impl MergeDriver {
&mut conflicts,
);
if !dropped.is_empty() {
- sqlx::query!(
+ mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op_person SET status = $2
+ UPDATE {lifecycle_op_person} SET status = $2
WHERE op_id = $1 AND person_id = ANY($3) AND status = $4
"#,
op.op_id,
STATUS_DROPPED,
&dropped,
- STATUS_MARKED,
- )
- .execute(&mut *tx)
- .await?;
+ STATUS_MARKED
+ => execute(&mut *tx)
+ )?;
}
if !dispositions
@@ -869,19 +877,19 @@ impl MergeDriver {
{
// Every source fell out: release the target's just-taken mark
// and end the op. No fences exist yet.
- sqlx::query!(
+ mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op_person SET status = $2
+ UPDATE {lifecycle_op_person} SET status = $2
WHERE op_id = $1 AND role = $3 AND status = $4
"#,
op.op_id,
STATUS_CLEARED,
ROLE_TARGET,
- STATUS_MARKED,
- )
- .execute(&mut *tx)
- .await?;
- return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
+ STATUS_MARKED
+ => execute(&mut *tx)
+ )?;
+ return abort_in_claim_tx(tx, &self.tables, op, dispositions, conflicts).await;
}
// Persist the claim record on the target row; the terminal outcome
@@ -889,17 +897,11 @@ impl MergeDriver {
let claim_record = serde_json::to_value(ClaimRecord { dispositions }).map_err(|e| {
SagaError::CorruptState(format!("failed to serialize claim record: {e}"))
})?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET moved = $2 WHERE op_id = $1 AND role = $3",
- op.op_id,
- claim_record,
- ROLE_TARGET,
- )
- .execute(&mut *tx)
- .await?;
+ write_claim_record(&mut tx, &self.tables, op, &claim_record).await?;
if !advance_step_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
MergeStep::Started.as_str(),
MergeStep::Claimed.as_str(),
@@ -916,11 +918,41 @@ impl MergeDriver {
}
}
+async fn unmark(tx: &mut Tx<'_>, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
+ mirrored_query!(
+ tables.is_validation(),
+ "UPDATE {lifecycle_op_person} SET status = $2 WHERE op_id = $1 AND status = $3",
+ op.op_id,
+ STATUS_ABORTED,
+ STATUS_MARKED
+ => execute(&mut **tx)
+ )?;
+ Ok(())
+}
+
+async fn write_claim_record(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op: &OpRow,
+ record: &Value,
+) -> Result<(), SagaError> {
+ mirrored_query!(
+ tables.is_validation(),
+ "UPDATE {lifecycle_op_person} SET moved = $2 WHERE op_id = $1 AND role = $3",
+ op.op_id,
+ record,
+ ROLE_TARGET
+ => execute(&mut **tx)
+ )?;
+ Ok(())
+}
+
/// End an op inside the claim transaction: nothing outside this op's own
/// rows has been mutated, so recording the outcome and the terminal step
/// in the same commit is the whole abort.
async fn abort_in_claim_tx(
mut tx: Tx<'_>,
+ tables: &IdentityTables,
op: &OpRow,
dispositions: Vec<Disposition>,
conflicts: Vec<(&'static str, u64)>,
@@ -936,6 +968,7 @@ async fn abort_in_claim_tx(
outcome["claim_abort"] = Value::Bool(true);
if !complete_op_in_tx(
&mut tx,
+ tables,
op.op_id,
MergeStep::Started.as_str(),
STEP_ABORTED,
@@ -969,16 +1002,7 @@ impl MergeDriver {
/// the takeover scan can mint, bounded the same way.
async fn seal(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
- let sources = sqlx::query!(
- r#"
- SELECT person_id, person_uuid FROM lifecycle_op_person
- WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')
- "#,
- op.op_id,
- ROLE_SOURCE,
- )
- .fetch_all(pool)
- .await?;
+ let sources = live_sources(pool, &self.tables, op).await?;
let mut sealed: Vec<(i64, SealedSnapshot)> = Vec::new();
let mut vanished: Vec<i64> = Vec::new();
@@ -1068,29 +1092,13 @@ impl MergeDriver {
.collect();
self.release_fences(op, &remaining).await?;
let mut tx = begin_timed(pool).await?;
- settle_drops(&mut tx, op, &vanished, &identified).await?;
- sqlx::query!(
- r#"
- UPDATE lifecycle_op_person SET status = $2
- WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')
- "#,
- op.op_id,
- STATUS_ABORTED,
- ROLE_SOURCE,
- )
- .execute(&mut *tx)
- .await?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",
- op.op_id,
- STATUS_CLEARED,
- ROLE_TARGET,
- )
- .execute(&mut *tx)
- .await?;
- let outcome = build_outcome(&mut tx, op, Some(AbortOutcome::Conflict)).await?;
+ settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
+ abort_marks(&mut tx, &self.tables, op).await?;
+ let outcome =
+ build_outcome(&mut tx, &self.tables, op, Some(AbortOutcome::Conflict)).await?;
if !complete_op_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
MergeStep::Claimed.as_str(),
STEP_ABORTED,
@@ -1108,16 +1116,17 @@ impl MergeDriver {
}
let mut tx = begin_timed(pool).await?;
- settle_drops(&mut tx, op, &vanished, &identified).await?;
+ settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
let sealed_ids: Vec<i64> = sealed.iter().map(|(id, _)| *id).collect();
let sealed_jsons: Vec<Value> = sealed
.iter()
.map(|(_, snapshot)| serde_json::to_value(snapshot))
.collect::<Result<_, _>>()
.map_err(|e| SagaError::CorruptState(format!("failed to serialize seal: {e}")))?;
- sqlx::query!(
+ mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op_person lop
+ UPDATE {lifecycle_op_person} lop
SET status = $4, sealed = u.sealed
FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, sealed)
WHERE lop.op_id = $1 AND lop.person_id = u.person_id
@@ -1126,13 +1135,13 @@ impl MergeDriver {
op.op_id,
&sealed_ids,
&sealed_jsons,
- STATUS_SEALED,
- )
- .execute(&mut *tx)
- .await?;
+ STATUS_SEALED
+ => execute(&mut *tx)
+ )?;
if !advance_step_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
MergeStep::Claimed.as_str(),
MergeStep::SourcesSealed.as_str(),
@@ -1159,42 +1168,16 @@ impl MergeDriver {
from_step: MergeStep,
status: &Status,
) -> Result<(), SagaError> {
- let live = sqlx::query!(
- r#"
- SELECT person_id, person_uuid FROM lifecycle_op_person
- WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')
- "#,
- op.op_id,
- ROLE_SOURCE,
- )
- .fetch_all(pool)
- .await?;
+ let live = live_sources(pool, &self.tables, op).await?;
let pairs: Vec<(i64, Uuid)> = live.iter().map(|s| (s.person_id, s.person_uuid)).collect();
let mut tx = begin_timed(pool).await?;
- sqlx::query!(
- r#"
- UPDATE lifecycle_op_person SET status = $2
- WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')
- "#,
- op.op_id,
- STATUS_ABORTED,
- ROLE_SOURCE,
- )
- .execute(&mut *tx)
- .await?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",
- op.op_id,
- STATUS_CLEARED,
- ROLE_TARGET,
- )
- .execute(&mut *tx)
- .await?;
+ abort_marks(&mut tx, &self.tables, op).await?;
// Fence contention never reaches this abort; it retries at the step.
- let outcome = build_outcome(&mut tx, op, Some(AbortOutcome::Refused)).await?;
+ let outcome = build_outcome(&mut tx, &self.tables, op, Some(AbortOutcome::Refused)).await?;
if !complete_op_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
from_step.as_str(),
STEP_ABORTED,
@@ -1280,10 +1263,49 @@ fn snapshot_from_sealed(person: &Person) -> Result<SealedSnapshot, SagaError> {
})
}
+async fn live_sources(
+ pool: &PgPool,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<Vec<PersonRef>, SagaError> {
+ Ok(mirrored_query_as!(
+ PersonRef,
+ tables.is_validation(),
+ r#"
+ SELECT person_id, person_uuid FROM {lifecycle_op_person}
+ WHERE op_id = $1 AND role = $2 AND status IN ('marked', 'sealed')
+ "#,
+ op.op_id,
+ ROLE_SOURCE
+ => fetch_all(pool)
+ )?)
+}
+
+/// Settle a pre-flip abort's marks: sources `aborted`, target `cleared`.
+async fn abort_marks(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<(), SagaError> {
+ mirrored_query!(
+ tables.is_validation(),
+ r#"
+ UPDATE {lifecycle_op_person} SET status = $2
+ WHERE op_id = $1 AND role = $3 AND status IN ('marked', 'sealed')
+ "#,
+ op.op_id,
+ STATUS_ABORTED,
+ ROLE_SOURCE
+ => execute(&mut **tx)
+ )?;
+ clear_target_mark(tx, tables, op).await
+}
+
/// Settle sources that dropped out during the seal: `dropped` releases
/// their marks; the claim record's decisions flip to the drop reason.
async fn settle_drops(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op: &OpRow,
vanished: &[i64],
identified: &[i64],
@@ -1292,19 +1314,19 @@ async fn settle_drops(
if all.is_empty() {
return Ok(());
}
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- UPDATE lifecycle_op_person SET status = $2
+ UPDATE {lifecycle_op_person} SET status = $2
WHERE op_id = $1 AND person_id = ANY($3) AND status IN ('marked', 'sealed')
"#,
op.op_id,
STATUS_DROPPED,
- &all,
- )
- .execute(&mut **tx)
- .await?;
+ &all
+ => execute(&mut **tx)
+ )?;
- let mut record = claim_record(tx, op).await?;
+ let mut record = claim_record(tx, tables, op).await?;
for disposition in record.dispositions.iter_mut() {
if disposition.decision != DECISION_PENDING_MERGE {
continue;
@@ -1322,15 +1344,7 @@ async fn settle_drops(
}
let updated = serde_json::to_value(&record)
.map_err(|e| SagaError::CorruptState(format!("failed to serialize claim record: {e}")))?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET moved = $2 WHERE op_id = $1 AND role = $3",
- op.op_id,
- updated,
- ROLE_TARGET,
- )
- .execute(&mut **tx)
- .await?;
- Ok(())
+ write_claim_record(tx, tables, op, &updated).await
}
impl MergeDriver {
@@ -1345,19 +1359,8 @@ impl MergeDriver {
/// terminal outcome's survivor, durable without ever re-folding.
async fn fold(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
- let target = target_row(pool, op).await?;
- let sources = sqlx::query!(
- r#"
- SELECT person_id, ordinal as "ordinal!", sealed as "sealed!" FROM lifecycle_op_person
- WHERE op_id = $1 AND role = $2 AND status = $3
- ORDER BY ordinal
- "#,
- op.op_id,
- ROLE_SOURCE,
- STATUS_SEALED,
- )
- .fetch_all(pool)
- .await?;
+ let target = target_row(pool, &self.tables, op).await?;
+ let sources = sealed_sources(pool, &self.tables, op).await?;
// The fold verifies each snapshot's identity and orders by the
// ordinal itself, so the request carries the recorded pair order
@@ -1428,7 +1431,7 @@ impl MergeDriver {
// under a live claim the pre-flip abort is safe.
if personhog_common::grpc::semantic_refusal_reason(&status)
== Some("fold-unverified")
- && op_moved_on(pool, op).await?
+ && op_moved_on(pool, &self.tables, op).await?
{
tracing::info!(
op_id = %op.op_id,
@@ -1462,16 +1465,17 @@ impl MergeDriver {
});
let mut tx = begin_timed(pool).await?;
- sqlx::query!(
- "UPDATE lifecycle_op_person SET sealed = $2 WHERE op_id = $1 AND role = $3",
+ mirrored_query!(
+ self.tables.is_validation(),
+ "UPDATE {lifecycle_op_person} SET sealed = $2 WHERE op_id = $1 AND role = $3",
op.op_id,
survivor,
- ROLE_TARGET,
- )
- .execute(&mut *tx)
- .await?;
+ ROLE_TARGET
+ => execute(&mut *tx)
+ )?;
if !advance_step_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
MergeStep::SourcesSealed.as_str(),
MergeStep::DocumentFolded.as_str(),
@@ -1490,23 +1494,40 @@ impl MergeDriver {
}
}
-struct TargetRow {
- person_id: i64,
- person_uuid: Uuid,
+async fn target_row(
+ pool: &PgPool,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<PersonRef, SagaError> {
+ Ok(mirrored_query_as!(
+ PersonRef,
+ tables.is_validation(),
+ "SELECT person_id, person_uuid FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
+ op.op_id,
+ ROLE_TARGET
+ => fetch_one(pool)
+ )?)
}
-async fn target_row(pool: &PgPool, op: &OpRow) -> Result<TargetRow, SagaError> {
- let row = sqlx::query!(
- "SELECT person_id, person_uuid FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",
+async fn sealed_sources(
+ pool: &PgPool,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<Vec<SealedSource>, SagaError> {
+ Ok(mirrored_query_as!(
+ SealedSource,
+ tables.is_validation(),
+ r#"
+ SELECT person_id, person_uuid, ordinal as "ordinal!", sealed as "sealed!"
+ FROM {lifecycle_op_person}
+ WHERE op_id = $1 AND role = $2 AND status = $3
+ ORDER BY ordinal
+ "#,
op.op_id,
- ROLE_TARGET,
- )
- .fetch_one(pool)
- .await?;
- Ok(TargetRow {
- person_id: row.person_id,
- person_uuid: row.person_uuid,
- })
+ ROLE_SOURCE,
+ STATUS_SEALED
+ => fetch_all(pool)
+ )?)
}
fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {
@@ -1527,27 +1548,24 @@ async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
let team_id = op.team_id as i32;
let mut tx = begin_timed(pool).await?;
- let target = {
- let row = sqlx::query!(
- "SELECT person_id FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",
- op.op_id,
- ROLE_TARGET,
- )
- .fetch_one(&mut *tx)
- .await?;
- row.person_id
- };
- let mut sources: Vec<i64> = sqlx::query_scalar!(
+ let target: i64 = mirrored_query_scalar!(
+ tables.is_validation(),
+ "SELECT person_id FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
+ op.op_id,
+ ROLE_TARGET
+ => fetch_one(&mut *tx)
+ )?;
+ let mut sources: Vec<i64> = mirrored_query_scalar!(
+ tables.is_validation(),
r#"
- SELECT person_id FROM lifecycle_op_person
+ SELECT person_id FROM {lifecycle_op_person}
WHERE op_id = $1 AND role = $2 AND status = $3
"#,
op.op_id,
ROLE_SOURCE,
- STATUS_SEALED,
- )
- .fetch_all(&mut *tx)
- .await?;
+ STATUS_SEALED
+ => fetch_all(&mut *tx)
+ )?;
sources.sort_unstable();
// Lock every row up front in id order; the writer's flush does the
@@ -1576,14 +1594,15 @@ async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
.await?;
let repointed = repoint_distinct_ids(&mut tx, tables, team_id, &sources, target).await?;
- record_moved_mappings(&mut tx, op, &sources, &repointed).await?;
+ record_moved_mappings(&mut tx, tables, op, &sources, &repointed).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?;
+ clear_target_mark(&mut tx, tables, op).await?;
if !advance_step_in_tx(
&mut tx,
+ tables,
op.op_id,
MergeStep::DocumentFolded.as_str(),
MergeStep::Flipped.as_str(),
@@ -1652,6 +1671,7 @@ async fn repoint_distinct_ids(
/// later ClickHouse emission (or an operator) reads back (delete parity).
async fn record_moved_mappings(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op: &OpRow,
sources: &[i64],
repointed: &[RepointedDid],
@@ -1672,19 +1692,19 @@ async fn record_moved_mappings(
if moved_ids.is_empty() {
return Ok(());
}
- sqlx::query!(
+ mirrored_query!(
+ tables.is_validation(),
r#"
- UPDATE lifecycle_op_person lop
+ UPDATE {lifecycle_op_person} lop
SET moved = u.moved
FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)
WHERE lop.op_id = $1 AND lop.person_id = u.person_id
"#,
op.op_id,
&moved_ids,
- &moved_json,
- )
- .execute(&mut **tx)
- .await?;
+ &moved_json
+ => execute(&mut **tx)
+ )?;
Ok(())
}
@@ -1763,11 +1783,12 @@ async fn tombstone_sealed_sources(
properties_last_updated_at = '{{}}'::jsonb,
properties_last_operation = '{{}}'::jsonb,
version = (lop.sealed->>'version')::bigint + 1
- FROM lifecycle_op_person lop
+ FROM {lop_table} 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
"#,
person_table = tables.person,
+ lop_table = tables.lifecycle_op_person,
);
sqlx::query(&tombstone_sql)
.bind(op.op_id)
@@ -1783,15 +1804,19 @@ async fn tombstone_sealed_sources(
/// reaches Postgres through the writer's projection (single-writer
/// rule). Only its mark clears — from here the merged person is
/// claimable by other lifecycle ops.
-async fn clear_target_mark(tx: &mut Tx<'_>, op: &OpRow) -> Result<(), SagaError> {
- sqlx::query!(
- "UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND role = $3",
+async fn clear_target_mark(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<(), SagaError> {
+ mirrored_query!(
+ tables.is_validation(),
+ "UPDATE {lifecycle_op_person} SET status = $2 WHERE op_id = $1 AND role = $3",
op.op_id,
STATUS_CLEARED,
- ROLE_TARGET,
- )
- .execute(&mut **tx)
- .await?;
+ ROLE_TARGET
+ => execute(&mut **tx)
+ )?;
Ok(())
}
@@ -1804,17 +1829,7 @@ impl MergeDriver {
/// death document already exists; absorb the retry". Flipping first
/// would make the first-ever release absorb and never produce.
async fn complete(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
- let sources = sqlx::query!(
- r#"
- SELECT person_id, person_uuid, sealed as "sealed!" FROM lifecycle_op_person
- WHERE op_id = $1 AND role = $2 AND status = $3
- "#,
- op.op_id,
- ROLE_SOURCE,
- STATUS_SEALED,
- )
- .fetch_all(pool)
- .await?;
+ let sources = sealed_sources(pool, &self.tables, op).await?;
let release_calls: Vec<_> = sources
.iter()
@@ -1864,21 +1879,22 @@ impl MergeDriver {
}
let mut tx = begin_timed(pool).await?;
- sqlx::query!(
+ mirrored_query!(
+ self.tables.is_validation(),
r#"
- UPDATE lifecycle_op_person SET status = $2
+ UPDATE {lifecycle_op_person} SET status = $2
WHERE op_id = $1 AND role = $3 AND status = $4
"#,
op.op_id,
STATUS_DELETED,
ROLE_SOURCE,
- STATUS_SEALED,
- )
- .execute(&mut *tx)
- .await?;
- let outcome = build_outcome(&mut tx, op, None).await?;
+ STATUS_SEALED
+ => execute(&mut *tx)
+ )?;
+ let outcome = build_outcome(&mut tx, &self.tables, op, None).await?;
if !complete_op_in_tx(
&mut tx,
+ &self.tables,
op.op_id,
MergeStep::Flipped.as_str(),
STEP_COMPLETED,
@@ -1896,15 +1912,19 @@ impl MergeDriver {
}
}
-async fn claim_record(tx: &mut Tx<'_>, op: &OpRow) -> Result<ClaimRecord, SagaError> {
- let row = sqlx::query!(
- r#"SELECT moved FROM lifecycle_op_person WHERE op_id = $1 AND role = $2"#,
+async fn claim_record(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<ClaimRecord, SagaError> {
+ let moved = mirrored_query_scalar!(
+ tables.is_validation(),
+ "SELECT moved FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
op.op_id,
- ROLE_TARGET,
- )
- .fetch_one(&mut **tx)
- .await?;
- let moved = row.moved.ok_or_else(|| {
+ ROLE_TARGET
+ => fetch_one(&mut **tx)
+ )?;
+ let moved = moved.ok_or_else(|| {
SagaError::CorruptState(format!("merge op {} has no claim record", op.op_id))
})?;
serde_json::from_value(moved).map_err(|e| {
@@ -1922,17 +1942,19 @@ async fn claim_record(tx: &mut Tx<'_>, op: &OpRow) -> Result<ClaimRecord, SagaEr
/// `error`.
async fn build_outcome(
tx: &mut Tx<'_>,
+ tables: &IdentityTables,
op: &OpRow,
abort_outcome: Option<AbortOutcome>,
) -> Result<Value, SagaError> {
- let record = claim_record(tx, op).await?;
- let statuses: HashMap<i64, String> = sqlx::query!(
- "SELECT person_id, status FROM lifecycle_op_person WHERE op_id = $1 AND role = $2",
+ let record = claim_record(tx, tables, op).await?;
+ let statuses: HashMap<i64, String> = mirrored_query_as!(
+ PersonStatus,
+ tables.is_validation(),
+ "SELECT person_id, status FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
op.op_id,
- ROLE_SOURCE,
- )
- .fetch_all(&mut **tx)
- .await?
+ ROLE_SOURCE
+ => fetch_all(&mut **tx)
+ )?
.into_iter()
.map(|r| (r.person_id, r.status))
.collect();
@@ -1940,14 +1962,13 @@ async fn build_outcome(
let survivor = if abort_outcome.is_some() {
None
} else {
- let row = sqlx::query!(
- r#"SELECT sealed FROM lifecycle_op_person WHERE op_id = $1 AND role = $2"#,
+ mirrored_query_scalar!(
+ tables.is_validation(),
+ "SELECT sealed FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
op.op_id,
- ROLE_TARGET,
- )
- .fetch_one(&mut **tx)
- .await?;
- row.sealed
+ ROLE_TARGET
+ => fetch_one(&mut **tx)
+ )?
};
outcome_from_dispositions(&record.dispositions, abort_outcome, survivor, &statuses)
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index b2d424b69661..31990f7283fc 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -233,6 +233,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let engine = Arc::new(Engine::new(
storage.primary_pool.clone(),
config.lifecycle_engine_config(),
+ config.tables(),
));
if let Some(sweeper_handle) = sweeper_handle {
let sweeper_merge_driver = MergeDriver::new(
diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rs
index 624746bf8239..c368cb20572d 100644
--- a/rust/personhog-identity/src/storage/postgres/attach.rs
+++ b/rust/personhog-identity/src/storage/postgres/attach.rs
@@ -41,7 +41,7 @@ pub(super) async fn attach_distinct_ids(
JOIN {person} p
ON p.team_id = $3 AND p.id = $2 AND p.is_deleted = false
WHERE NOT EXISTS (
- SELECT 1 FROM lifecycle_op_person m
+ SELECT 1 FROM {lop} m
WHERE m.team_id = p.team_id AND m.person_id = p.id
AND m.status IN ('marked', 'sealed')
)
@@ -54,6 +54,7 @@ pub(super) async fn attach_distinct_ids(
"#,
pdi = tables.person_distinct_id,
person = tables.person,
+ lop = tables.lifecycle_op_person,
);
let mut conn = super::acquire_timed(pool).await?;
let written = sqlx::query(&insert_sql)
diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rs
index 99d0ccedc453..3b403ce85824 100644
--- a/rust/personhog-identity/src/storage/postgres/stub_create.rs
+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs
@@ -85,8 +85,7 @@ pub(super) async fn create_person_stubs(
let mut tx = super::begin_timed(pool).await?;
- let mut persons =
- insert_or_revive_persons(&mut tx, &tables.person, stubs, &team_ids, &uuids).await?;
+ let mut persons = insert_or_revive_persons(&mut tx, tables, stubs, &team_ids, &uuids).await?;
fetch_conflict_winners(
&mut tx,
&tables.person,
@@ -121,11 +120,12 @@ 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,
+ tables: &IdentityTables,
stubs: &[PersonStub],
team_ids: &[i32],
uuids: &[Uuid],
) -> StorageResult<PersonsByKey> {
+ let person_table = &tables.person;
// Sorted and deduped by the (team_id, uuid) conflict key — see the
// module invariants.
let mut order: Vec<usize> = (0..stubs.len()).collect();
@@ -157,7 +157,7 @@ async fn insert_or_revive_persons(
last_seen_at = EXCLUDED.last_seen_at
WHERE {person_table}.is_deleted = true
AND NOT EXISTS (
- SELECT 1 FROM lifecycle_op_person lop
+ SELECT 1 FROM {lop_table} lop
WHERE lop.team_id = {person_table}.team_id
AND lop.person_id = {person_table}.id
AND lop.status IN ('marked', 'sealed')
@@ -165,6 +165,7 @@ async fn insert_or_revive_persons(
RETURNING {person_cols}
"#,
person_cols = person_columns(person_table),
+ lop_table = tables.lifecycle_op_person,
);
let inserted = sqlx::query(&sql)
.bind(&sorted_created_ats)
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 5d16b7b0ce4e..1faafd0bd5c1 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -108,6 +108,7 @@ impl TestContext {
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ self.tables.clone(),
)
}
@@ -191,10 +192,13 @@ impl TestContext {
}
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.lifecycle_op
+ ))
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
sqlx::query(&format!(
"DELETE FROM {} WHERE team_id = $1",
self.tables.person_distinct_id
diff --git a/rust/personhog-identity/tests/common/sim_leader.rs b/rust/personhog-identity/tests/common/sim_leader.rs
index c22eb2c04fa9..1f432da464c0 100644
--- a/rust/personhog-identity/tests/common/sim_leader.rs
+++ b/rust/personhog-identity/tests/common/sim_leader.rs
@@ -31,6 +31,7 @@ use tonic::Status;
use uuid::Uuid;
use personhog_common::grpc::semantic_refusal;
+use personhog_identity::config::IdentityTables;
use personhog_identity::leader::{LifecycleLeader, PropertyWriter};
use personhog_proto::personhog::types::v1::{
FencePersonRequest, FencePersonResponse, FoldPersonDocumentRequest, FoldPersonDocumentResponse,
@@ -120,7 +121,7 @@ fn fenced_status(fence: &Fence) -> Status {
pub struct SimLeader {
pool: PgPool,
- person_table: String,
+ tables: IdentityTables,
calls: Mutex<Vec<LeaderCall>>,
fences: Mutex<HashMap<i64, Fence>>,
deaths: Mutex<HashMap<i64, DeathDocument>>,
@@ -135,10 +136,10 @@ pub struct SimLeader {
}
impl SimLeader {
- pub fn new(pool: PgPool, person_table: String) -> Self {
+ pub fn new(pool: PgPool, tables: IdentityTables) -> Self {
Self {
pool,
- person_table,
+ tables,
calls: Mutex::new(Vec::new()),
fences: Mutex::new(HashMap::new()),
deaths: Mutex::new(HashMap::new()),
@@ -229,7 +230,7 @@ impl SimLeader {
FROM {person_table}
WHERE team_id = $1 AND id = $2 AND is_deleted = false
"#,
- person_table = self.person_table,
+ person_table = self.tables.person,
);
let row: Option<(Uuid, i64, chrono::DateTime<Utc>, bool, serde_json::Value)> =
sqlx::query_as(&live_sql)
@@ -256,10 +257,11 @@ impl SimLeader {
/// The mark row the real leader consults before producing a death
/// document (personhog-leader/src/fence.rs `mark_status`).
async fn mark_status(&self, op_id: Uuid, team_id: i64, person_id: i64) -> Option<String> {
- sqlx::query_scalar(
- "SELECT status FROM lifecycle_op_person \
+ sqlx::query_scalar(&format!(
+ "SELECT status FROM {} \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role <> 'target'",
- )
+ self.tables.lifecycle_op_person
+ ))
.bind(op_id)
.bind(team_id as i32)
.bind(person_id)
@@ -275,10 +277,11 @@ impl SimLeader {
team_id: i64,
person_id: i64,
) -> Option<String> {
- sqlx::query_scalar(
- "SELECT status FROM lifecycle_op_person \
+ sqlx::query_scalar(&format!(
+ "SELECT status FROM {} \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role = 'target'",
- )
+ self.tables.lifecycle_op_person
+ ))
.bind(op_id)
.bind(team_id as i32)
.bind(person_id)
@@ -594,7 +597,7 @@ impl PropertyWriter for SimLeader {
let update_sql = format!(
"UPDATE {person_table} SET properties = $3::jsonb, is_identified = is_identified OR $4 \
WHERE team_id = $1 AND id = $2",
- person_table = self.person_table,
+ person_table = self.tables.person,
);
sqlx::query(&update_sql)
.bind(request.team_id as i32)
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
index e3f856108cf4..1c1e69f51978 100644
--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -22,10 +22,7 @@ use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePerso
impl TestContext {
fn lifecycle_service(&self) -> PersonHogLifecycleService {
let engine = Arc::new(self.engine());
- let leader = Arc::new(SimLeader::new(
- self.pool.clone(),
- self.tables.person.clone(),
- ));
+ let leader = Arc::new(SimLeader::new(self.pool.clone(), self.tables.clone()));
PersonHogLifecycleService::new(
engine,
leader.clone(),
@@ -557,7 +554,7 @@ impl FencedHarness {
async fn new() -> Self {
let ctx = TestContext::new().await;
let engine = ctx.engine();
- let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.person.clone()));
+ let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.clone()));
let driver = DeleteDriver::new(
leader.clone(),
ctx.tables.clone(),
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index 7643ed05f458..ed857e06f008 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -54,10 +54,20 @@ impl OpDriver for DummyDriver {
self.steps_run.fetch_add(1, Ordering::SeqCst);
let mut tx = pool.begin().await.map_err(SagaError::Db)?;
let advanced = match op.step.as_str() {
- "started" => advance_step_in_tx(&mut tx, op.op_id, "started", "half").await?,
+ "started" => {
+ advance_step_in_tx(
+ &mut tx,
+ &common::default_tables(),
+ op.op_id,
+ "started",
+ "half",
+ )
+ .await?
+ }
"half" => {
complete_op_in_tx(
&mut tx,
+ &common::default_tables(),
op.op_id,
"half",
STEP_COMPLETED,
@@ -306,6 +316,7 @@ async fn a_live_lease_blocks_a_second_driver_until_it_lapses() {
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ ctx.tables.clone(),
);
let err = short_engine
.execute(&driver, op_id, ctx.team_id, &json!({}))
@@ -355,6 +366,7 @@ async fn a_drive_that_runs_out_its_own_deadline_says_so_and_releases_the_lease()
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ ctx.tables.clone(),
);
// The claim was ours the whole time, so the answer must not blame a
@@ -483,6 +495,7 @@ async fn a_driver_whose_lease_was_stolen_stops_running_steps_instead_of_renewing
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ ctx.tables.clone(),
);
let err = short_engine
.execute(&driver, op_id, ctx.team_id, &json!({}))
@@ -567,8 +580,15 @@ impl OpDriver for RefusingDriver {
)));
}
let mut tx = pool.begin().await.map_err(SagaError::Db)?;
- let advanced =
- complete_op_in_tx(&mut tx, op.op_id, "started", STEP_COMPLETED, &json!({})).await?;
+ let advanced = complete_op_in_tx(
+ &mut tx,
+ &common::default_tables(),
+ op.op_id,
+ "started",
+ STEP_COMPLETED,
+ &json!({}),
+ )
+ .await?;
if !advanced {
tx.rollback().await.map_err(SagaError::Db)?;
return Ok(());
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index ce37f70bfe68..3f758f3b129e 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -49,7 +49,7 @@ impl MergeHarness {
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(), ctx.tables.person.clone()));
+ let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.clone()));
let driver = MergeDriver::new(
leader.clone(),
ctx.tables.clone(),
@@ -132,23 +132,25 @@ impl MergeHarness {
/// A mark row held by a different (still-live) op.
async fn foreign_mark(&self, person_id: i64) -> Uuid {
let foreign_op = Uuid::now_v7();
- sqlx::query(
+ sqlx::query(&format!(
r#"
- INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)
- VALUES ($1, 'delete', $2, 'marked', '{}'::jsonb)
+ INSERT INTO {} (op_id, op_type, team_id, step, request)
+ VALUES ($1, 'delete', $2, 'marked', '{{}}'::jsonb)
"#,
- )
+ self.ctx.tables.lifecycle_op
+ ))
.bind(foreign_op)
.bind(self.ctx.team_id as i32)
.execute(&self.ctx.pool)
.await
.expect("insert foreign op");
- sqlx::query(
+ sqlx::query(&format!(
r#"
- INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status)
+ INSERT INTO {} (op_id, team_id, person_id, person_uuid, role, status)
VALUES ($1, $2, $3, $4, 'victim', 'marked')
"#,
- )
+ self.ctx.tables.lifecycle_op_person
+ ))
.bind(foreign_op)
.bind(self.ctx.team_id as i32)
.bind(person_id)
@@ -192,9 +194,10 @@ impl MergeHarness {
}
async fn op_person_status(&self, op_id: Uuid, person_id: i64) -> String {
- sqlx::query_scalar(
- "SELECT status FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",
- )
+ sqlx::query_scalar(&format!(
+ "SELECT status FROM {} WHERE op_id = $1 AND person_id = $2",
+ self.ctx.tables.lifecycle_op_person
+ ))
.bind(op_id)
.bind(person_id)
.fetch_one(&self.ctx.pool)
@@ -205,9 +208,10 @@ impl MergeHarness {
/// The `sealed` payload of an op's per-person row (the fence snapshot
/// for sources, the folded survivor for the target).
async fn op_person_sealed(&self, op_id: Uuid, person_id: i64) -> Option<serde_json::Value> {
- sqlx::query_scalar(
- "SELECT sealed FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",
- )
+ sqlx::query_scalar(&format!(
+ "SELECT sealed FROM {} WHERE op_id = $1 AND person_id = $2",
+ self.ctx.tables.lifecycle_op_person
+ ))
.bind(op_id)
.bind(person_id)
.fetch_one(&self.ctx.pool)
@@ -218,9 +222,10 @@ impl MergeHarness {
/// The `moved` payload of an op's per-person row (the repointed
/// mappings for sources, the claim record for the target).
async fn op_person_moved(&self, op_id: Uuid, person_id: i64) -> Option<serde_json::Value> {
- sqlx::query_scalar(
- "SELECT moved FROM lifecycle_op_person WHERE op_id = $1 AND person_id = $2",
- )
+ sqlx::query_scalar(&format!(
+ "SELECT moved FROM {} WHERE op_id = $1 AND person_id = $2",
+ self.ctx.tables.lifecycle_op_person
+ ))
.bind(op_id)
.bind(person_id)
.fetch_one(&self.ctx.pool)
@@ -1094,6 +1099,7 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ h.ctx.tables.clone(),
);
let resumed = sweep_engine.sweep(&[&h.driver]).await.expect("sweep runs");
assert!(resumed >= 1, "the abandoned merge was resumed");
diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rs
index ce042566a37f..933e3c3d04c0 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -37,11 +37,12 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
attempt_alert_threshold: 5,
gc_batch_limit: 10_000,
},
+ personhog_identity::config::IdentityTables::real(),
));
let tables = IdentityTables::real();
let service = PersonHogLifecycleService::new(
engine,
- Arc::new(SimLeader::new(pool, tables.person.clone())),
+ Arc::new(SimLeader::new(pool, tables.clone())),
tables,
common::FAN_OUT_CONCURRENCY,
);
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index bc6ac8716e72..8bb795bea5f4 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -280,6 +280,15 @@ pub struct Config {
#[envconfig(default = "posthog_person")]
pub fallback_table: String,
+ /// Saga state tables the fence checks read (the takeover scan, the mark
+ /// verifications, the ghost-fence healer). Must be the pair identity
+ /// writes: its LIFECYCLE_OP_TABLE and LIFECYCLE_OP_PERSON_TABLE.
+ #[envconfig(default = "lifecycle_op")]
+ pub lifecycle_op_table: String,
+
+ #[envconfig(default = "lifecycle_op_person")]
+ pub lifecycle_op_person_table: String,
+
#[envconfig(default = "5")]
pub fallback_pg_max_connections: u32,
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 048898643962..316e328b9513 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -13,6 +13,7 @@ use crate::emitted::EmittedVersions;
use crate::fence::{drop_partition_fences, rebuild_partition_fences, FenceMap};
use crate::fencing::{heal_fence, FenceGuard, FencedChangelogProducers, HealOutcome};
use crate::inflight::InflightTracker;
+use crate::pg::PgFallback;
use crate::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};
const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
@@ -53,10 +54,9 @@ pub struct LeaderHandoffHandler {
/// The in-process fence copies, rebuilt from the live marks at every
/// ownership boundary (see the fence module for the durability model).
fences: FenceMap,
- /// Pool for the takeover scan — the cache-miss fallback pool. Without
- /// it (dev fixtures) fences are not rebuilt on takeover and only
- /// FencePerson calls fill the map.
- fence_scan_pool: Option<sqlx::PgPool>,
+ /// The takeover scan's source. Without it (dev fixtures) fences are
+ /// not rebuilt on takeover and only FencePerson calls fill the map.
+ fence_scan: Option<PgFallback>,
num_partitions: u32,
pools: Arc<WarmClientPools>,
/// Present when broker-enforced epoch fencing is on: acquiring a
@@ -92,7 +92,7 @@ impl LeaderHandoffHandler {
dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
fences: FenceMap,
- fence_scan_pool: Option<sqlx::PgPool>,
+ fence_scan: Option<PgFallback>,
num_partitions: u32,
pools: Arc<WarmClientPools>,
fenced: Option<Arc<FencedChangelogProducers>>,
@@ -105,7 +105,7 @@ impl LeaderHandoffHandler {
dirty_index,
warming,
fences,
- fence_scan_pool,
+ fence_scan,
num_partitions,
pools,
fenced,
@@ -256,9 +256,9 @@ impl HandoffHandler for LeaderHandoffHandler {
// (now current) owner, so the two sources cover every mark; a
// fence installed for a partition that is not yet serving is
// harmless.
- if let Some(pool) = &self.fence_scan_pool {
+ if let Some(fallback) = &self.fence_scan {
let installed =
- rebuild_partition_fences(pool, &self.fences, partition, self.num_partitions)
+ rebuild_partition_fences(fallback, &self.fences, partition, self.num_partitions)
.await
.map_err(|e| personhog_coordination::error::Error::HandoffFailed {
partition,
diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rs
index 896c239a679d..1aa7f6b27009 100644
--- a/rust/personhog-leader/src/fence.rs
+++ b/rust/personhog-leader/src/fence.rs
@@ -45,7 +45,6 @@ use std::time::Duration;
use dashmap::DashMap;
use metrics::{counter, gauge, histogram};
-use sqlx::postgres::PgPool;
use sqlx::Row;
use tonic::Status;
use uuid::Uuid;
@@ -54,6 +53,7 @@ use personhog_common::partitioning::partition_for_person;
use personhog_proto::personhog::types::v1::LifecycleOpType;
use crate::cache::PersonCacheKey;
+use crate::pg::PgFallback;
/// A person's live fence: the operation that froze it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -129,22 +129,25 @@ const SCAN_TIMEOUT: Duration = Duration::from_secs(10);
/// (a handoff cancelled after warming, then re-acquired) converges
/// instead of accumulating. Returns how many fences were installed.
pub async fn rebuild_partition_fences(
- pool: &PgPool,
+ fallback: &PgFallback,
fences: &FenceMap,
partition: u32,
num_partitions: u32,
) -> Result<usize, sqlx::Error> {
let start = std::time::Instant::now();
- let query = sqlx::query(
+ let tables = &fallback.lifecycle;
+ let sql = format!(
r#"
SELECT lop.team_id, lop.person_id, lop.op_id, o.op_type
- FROM lifecycle_op_person lop
- JOIN lifecycle_op o ON o.op_id = lop.op_id
+ FROM {op_person} lop
+ JOIN {op} o ON o.op_id = lop.op_id
WHERE lop.status IN ('marked', 'sealed')
AND lop.role <> 'target'
"#,
- )
- .fetch_all(pool);
+ op_person = tables.op_person,
+ op = tables.op,
+ );
+ let query = sqlx::query(&sql).fetch_all(&fallback.pool);
let rows = match tokio::time::timeout(SCAN_TIMEOUT, query).await {
Ok(result) => result?,
@@ -227,16 +230,16 @@ const HEAL_TRACKER_PRUNE_THRESHOLD: usize = 10_000;
/// belongs to the op that was checked (a newer op's fence is never
/// touched).
pub struct FenceHealer {
- pool: PgPool,
+ fallback: PgFallback,
fences: FenceMap,
/// Per-person stamp of the last triggered check, for the cooldown.
last_checked: DashMap<PersonCacheKey, std::time::Instant>,
}
impl FenceHealer {
- pub fn new(pool: PgPool, fences: FenceMap) -> Self {
+ pub fn new(fallback: PgFallback, fences: FenceMap) -> Self {
Self {
- pool,
+ fallback,
fences,
last_checked: DashMap::new(),
}
@@ -270,7 +273,9 @@ impl FenceHealer {
}
async fn check_and_heal(&self, key: PersonCacheKey, state: FenceState) {
- let status = match mark_status(&self.pool, state.op_id, key.team_id, key.person_id).await {
+ let status = match mark_status(&self.fallback, state.op_id, key.team_id, key.person_id)
+ .await
+ {
Ok(status) => status,
Err(e) => {
counter!("personhog_leader_fence_heals_total", "outcome" => "error").increment(1);
@@ -318,21 +323,23 @@ impl FenceHealer {
/// it may produce a death document: the request alone must never be enough
/// to destroy a person.
pub async fn mark_status(
- pool: &PgPool,
+ fallback: &PgFallback,
op_id: Uuid,
team_id: i64,
person_id: i64,
) -> Result<Option<String>, sqlx::Error> {
- let mut conn = crate::pg::acquire_timed(pool, "mark_status").await?;
- sqlx::query_scalar(
- "SELECT status FROM lifecycle_op_person \
+ let mut conn = crate::pg::acquire_timed(&fallback.pool, "mark_status").await?;
+ let sql = format!(
+ "SELECT status FROM {} \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role <> 'target'",
- )
- .bind(op_id)
- .bind(team_id as i32)
- .bind(person_id)
- .fetch_optional(&mut *conn)
- .await
+ fallback.lifecycle.op_person
+ );
+ sqlx::query_scalar(&sql)
+ .bind(op_id)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .fetch_optional(&mut *conn)
+ .await
}
/// The fold's check: the status of the op's mark row claiming this person
@@ -345,19 +352,21 @@ pub async fn mark_status(
/// full race — the same at-least-once residual the op_id proto comment
/// states.
pub async fn target_mark_status(
- pool: &PgPool,
+ fallback: &PgFallback,
op_id: Uuid,
team_id: i64,
person_id: i64,
) -> Result<Option<String>, sqlx::Error> {
- let mut conn = crate::pg::acquire_timed(pool, "target_mark_status").await?;
- sqlx::query_scalar(
- "SELECT status FROM lifecycle_op_person \
+ let mut conn = crate::pg::acquire_timed(&fallback.pool, "target_mark_status").await?;
+ let sql = format!(
+ "SELECT status FROM {} \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role = 'target'",
- )
- .bind(op_id)
- .bind(team_id as i32)
- .bind(person_id)
- .fetch_optional(&mut *conn)
- .await
+ fallback.lifecycle.op_person
+ );
+ sqlx::query_scalar(&sql)
+ .bind(op_id)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .fetch_optional(&mut *conn)
+ .await
}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 9d25e72a3351..ea4d0737b74c 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -36,7 +36,7 @@ use personhog_leader::fencing::{
preregister_fencing_metrics, FencedChangelogProducers, FencedProducerConfig,
};
use personhog_leader::inflight::InflightTracker;
-use personhog_leader::pg::{validate_table_name, PgFallback};
+use personhog_leader::pg::{validate_table_name, LifecycleTables, PgFallback};
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::settle::prune_and_settle_tick;
@@ -66,6 +66,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.validate_shutdown_budgets()
.expect("Invalid shutdown configuration");
validate_table_name(&config.fallback_table).expect("Invalid FALLBACK_TABLE");
+ validate_table_name(&config.lifecycle_op_table).expect("Invalid LIFECYCLE_OP_TABLE");
+ validate_table_name(&config.lifecycle_op_person_table)
+ .expect("Invalid LIFECYCLE_OP_PERSON_TABLE");
// Initialize tracing
let log_layer = fmt::layer()
@@ -310,6 +313,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
pool_config,
)?,
table: config.fallback_table.clone(),
+ lifecycle: LifecycleTables::new(
+ &config.lifecycle_op_table,
+ &config.lifecycle_op_person_table,
+ ),
};
personhog_common::spawn_pool_monitor(
vec![personhog_common::MonitoredPool {
@@ -366,7 +373,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
kafka_producer.clone(),
config.ingestion_warnings_topic.clone(),
);
- let fence_scan_pool = fallback.as_ref().map(|f| f.pool.clone());
+ let fence_scan = fallback.clone();
let mut fence_repair_nudge: Option<Arc<Notify>> = None;
let fenced = if config.kafka_transactional_fencing {
// Every one of these is derived from LEASE_TTL rather than set
@@ -523,7 +530,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
},
},
Arc::clone(&fences),
- fence_scan_pool,
+ fence_scan,
num_partitions,
Arc::clone(&warm_pools),
fenced.clone(),
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index 716751fb00d2..5b378d21f32c 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -16,6 +16,24 @@ use crate::cache::{approx_person_bytes, CachedPerson, PersonCacheKey};
pub struct PgFallback {
pub pool: PgPool,
pub table: String,
+ pub lifecycle: LifecycleTables,
+}
+
+/// The saga tables the fence checks read. Must be the pair identity
+/// writes its marks to, or every committed release fails closed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LifecycleTables {
+ pub op: String,
+ pub op_person: String,
+}
+
+impl LifecycleTables {
+ pub fn new(op: &str, op_person: &str) -> Self {
+ Self {
+ op: op.to_string(),
+ op_person: op_person.to_string(),
+ }
+ }
}
/// Take a fallback-pool connection, recording the wait: the pool is small
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index f805e21242e7..d5e46028595d 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -207,7 +207,7 @@ impl PersonHogLeaderService {
changelog_topic,
fence_healer: fallback
.as_ref()
- .map(|f| Arc::new(FenceHealer::new(f.pool.clone(), Arc::clone(&fences)))),
+ .map(|f| Arc::new(FenceHealer::new(f.clone(), Arc::clone(&fences)))),
fallback,
inflight,
num_partitions,
@@ -1381,7 +1381,7 @@ impl PersonHogLeader for PersonHogLeaderService {
"no-lifecycle-db",
));
};
- match target_mark_status(&fallback.pool, op_id, req.team_id, req.person_id).await {
+ match target_mark_status(fallback, op_id, req.team_id, req.person_id).await {
Ok(Some(status)) if status == "marked" => {}
Ok(_) => {
counter!("personhog_leader_fences_total", "action" => "fold_unverified")
@@ -1848,7 +1848,7 @@ impl PersonHogLeader for PersonHogLeaderService {
));
};
let verify_started = Instant::now();
- let mark = mark_status(&fallback.pool, op_id, req.team_id, req.person_id).await;
+ let mark = mark_status(fallback, op_id, req.team_id, req.person_id).await;
record_release_phase("verify_mark", verify_started);
match mark {
// A live mark: the op holds the person; proceed.
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 77f32b0188eb..ab5e6dd4c001 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -31,7 +31,7 @@ use personhog_leader::cache::{
};
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
-use personhog_leader::pg::PgFallback;
+use personhog_leader::pg::{LifecycleTables, PgFallback};
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::warming::WarmClientPools;
@@ -609,6 +609,7 @@ pub async fn start_leader_with_pg_fallback(
Some(PgFallback {
pool,
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index 1ecaed777189..2e0ea6475cfc 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -18,7 +18,7 @@ use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, Person
use personhog_leader::emitted::EmittedVersions;
use personhog_leader::fence::{FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY};
use personhog_leader::inflight::InflightTracker;
-use personhog_leader::pg::PgFallback;
+use personhog_leader::pg::{LifecycleTables, PgFallback};
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::settle::drop_settled_death_documents;
use personhog_leader::warnings::WarningsProducer;
@@ -328,6 +328,7 @@ async fn a_committed_release_produces_the_death_document_above_every_version() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -485,6 +486,7 @@ async fn a_revival_is_served_once_the_death_documents_mark_settles() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -667,6 +669,7 @@ async fn a_committed_release_derives_the_death_version_above_the_emitted_floor()
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -763,6 +766,7 @@ async fn a_stub_sealed_at_version_zero_can_be_released() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -845,6 +849,7 @@ async fn a_ghost_fence_heals_after_a_rejected_write() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -937,6 +942,7 @@ async fn a_ghost_fence_heals_after_a_rejected_fence_attempt() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -1027,6 +1033,7 @@ async fn a_live_marked_fence_survives_heal_attempts() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -1093,6 +1100,7 @@ async fn a_committed_release_without_a_live_mark_is_refused() {
Some(PgFallback {
pool,
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -1344,7 +1352,12 @@ async fn the_takeover_scan_rebuilds_exactly_the_partitions_live_fences() {
let partition_a = partition_for_person(team_id, fenced_a, NUM_PARTITIONS);
let fences: FenceMap = Arc::new(DashMap::new());
- let installed = rebuild_partition_fences(&pool, &fences, partition_a, NUM_PARTITIONS)
+ let fallback = PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
+ };
+ let installed = rebuild_partition_fences(&fallback, &fences, partition_a, NUM_PARTITIONS)
.await
.expect("scan runs");
@@ -1381,7 +1394,7 @@ async fn the_takeover_scan_rebuilds_exactly_the_partitions_live_fences() {
op_type: personhog_proto::personhog::types::v1::LifecycleOpType::Delete,
},
);
- let reinstalled = rebuild_partition_fences(&pool, &fences, ghost_partition, NUM_PARTITIONS)
+ let reinstalled = rebuild_partition_fences(&fallback, &fences, ghost_partition, NUM_PARTITIONS)
.await
.expect("re-warm runs");
assert!(
@@ -1604,6 +1617,7 @@ async fn start_marked_fold_harness(seed: CachedPerson, op: &Uuid) -> FenceHarnes
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -2078,6 +2092,7 @@ async fn a_fold_whose_op_holds_no_live_target_mark_is_refused() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
@@ -2530,6 +2545,7 @@ async fn a_release_after_a_cache_eviction_still_produces_the_death_document() {
Some(PgFallback {
pool: pool.clone(),
table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
}),
)
.await;
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index fe55ed807c48..278983452237 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -569,6 +569,8 @@ const RESERVED_LEADER_ENV: &[&str] = &[
"ETCD_PREFIX",
"KAFKA_PERSON_STATE_TOPIC",
"FALLBACK_TABLE",
+ "LIFECYCLE_OP_TABLE",
+ "LIFECYCLE_OP_PERSON_TABLE",
"FALLBACK_DATABASE_URL",
"WRITER_CONSUMER_GROUP",
// Derived fencing timeouts scale off the lease TTL, so overriding it
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index e2dc94345cce..0fa9b7e299cd 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -249,7 +249,8 @@ pub async fn run(args: GateArgs) -> Result<()> {
// leftover mark would make a later run's takeover scan install a stale
// fence for this team.
seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
- sqlx::query("DELETE FROM lifecycle_op WHERE team_id = $1")
+ let (lifecycle_op, lifecycle_op_person) = seed::lifecycle_tables_for(&args.pg_target_table);
+ sqlx::query(&format!("DELETE FROM {lifecycle_op} WHERE team_id = $1"))
.bind(args.team_id as i32)
.execute(&pool)
.await
@@ -437,21 +438,21 @@ pub async fn run(args: GateArgs) -> Result<()> {
// rebuilds its fences from these rows. Fencing without them
// would not survive a restart (the harness acts as the
// saga's mark step here).
- sqlx::query(
- "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
- VALUES ($1, 'delete', $2, 'started', '{}'::jsonb)",
- )
+ sqlx::query(&format!(
+ "INSERT INTO {lifecycle_op} (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'started', '{{}}'::jsonb)"
+ ))
.bind(fence_op)
.bind(args.team_id as i32)
.execute(&pool)
.await
.context("inserting fence op row")?;
for &person_id in person_ids.snapshot().iter().take(args.fence_count) {
- sqlx::query(
- "INSERT INTO lifecycle_op_person \
+ sqlx::query(&format!(
+ "INSERT INTO {lifecycle_op_person} \
(op_id, team_id, person_id, person_uuid, role, status) \
- VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'marked')",
- )
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'marked')"
+ ))
.bind(fence_op)
.bind(args.team_id as i32)
.bind(person_id)
@@ -506,16 +507,16 @@ pub async fn run(args: GateArgs) -> Result<()> {
// The op is over: settle it so the marks leave the live
// set (an aborted op's marks must not fence anyone after
// release).
- sqlx::query(
- "UPDATE lifecycle_op_person SET status = 'skipped_conflict' WHERE op_id = $1",
- )
+ sqlx::query(&format!(
+ "UPDATE {lifecycle_op_person} SET status = 'skipped_conflict' WHERE op_id = $1"
+ ))
.bind(fence_op)
.execute(&pool)
.await
.context("settling fence marks")?;
- sqlx::query(
- "UPDATE lifecycle_op SET step = 'aborted', completed_at = now() WHERE op_id = $1",
- )
+ sqlx::query(&format!(
+ "UPDATE {lifecycle_op} SET step = 'aborted', completed_at = now() WHERE op_id = $1"
+ ))
.bind(fence_op)
.execute(&pool)
.await
@@ -616,7 +617,14 @@ pub async fn run(args: GateArgs) -> Result<()> {
// lease lapses, which is why the deadline is long.
let mut violations = prober_violations;
violations.extend(
- merge::settle_unresolved(&pool, &state, unresolved_merges, Duration::from_secs(90)).await?,
+ merge::settle_unresolved(
+ &pool,
+ &args.pg_target_table,
+ &state,
+ unresolved_merges,
+ Duration::from_secs(90),
+ )
+ .await?,
);
println!("Verifying strong reads...");
diff --git a/rust/personhog-test-harness/src/scenarios/merge.rs b/rust/personhog-test-harness/src/scenarios/merge.rs
index eba989bab13f..6a8b328263a5 100644
--- a/rust/personhog-test-harness/src/scenarios/merge.rs
+++ b/rust/personhog-test-harness/src/scenarios/merge.rs
@@ -438,6 +438,7 @@ pub async fn run_merges(
/// time to re-drive it. An op that never settles is a violation.
pub async fn settle_unresolved(
pool: &PgPool,
+ person_table: &str,
state: &PersonState,
unresolved: Vec<UnresolvedMerge>,
deadline: Duration,
@@ -452,10 +453,12 @@ pub async fn settle_unresolved(
let mut violations = Vec::new();
let mut pending = unresolved;
let started = Instant::now();
+ let (lifecycle_op, _) = crate::seed::lifecycle_tables_for(person_table);
+ let op_query = format!("SELECT step, outcome FROM {lifecycle_op} WHERE op_id = $1");
loop {
let mut still_pending = Vec::new();
for merge in pending {
- let row = sqlx::query("SELECT step, outcome FROM lifecycle_op WHERE op_id = $1")
+ let row = sqlx::query(&op_query)
.bind(merge.op_id)
.fetch_optional(pool)
.await
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index b9e720f3ef96..639f8410504e 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -62,6 +62,16 @@ pub fn distinct_id_tables_for(person_table: &str) -> &'static [&'static str] {
}
}
+/// The saga tables paired with a person table, derived the way identity
+/// and the leader derive them.
+pub fn lifecycle_tables_for(person_table: &str) -> (&'static str, &'static str) {
+ if person_table == "personhog_person_tmp" {
+ ("lifecycle_op_tmp", "lifecycle_op_person_tmp")
+ } else {
+ ("lifecycle_op", "lifecycle_op_person")
+ }
+}
+
/// Create (or revive) one person per distinct id through the identity
/// service and return their row ids in entry order. This is the bed's
/// seeding path: creation runs the same get-or-create the ingestion
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 0e4bed9c0b7f..7cd80f31e9b5 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -73,6 +73,14 @@ pub struct StackConfig {
/// leader-mode routers (each hosting a coordinator candidate), all pointed
/// at the docker-compose Kafka/etcd/Postgres but isolated from the dev
/// stack via their own ports, etcd prefix, and per-run changelog topic.
+/// Identity's companion tables; its env must name the full set.
+struct IdentityCompanionTables {
+ person_distinct_id: &'static str,
+ ff_hash_key_override: &'static str,
+ lifecycle_op: &'static str,
+ lifecycle_op_person: &'static str,
+}
+
pub struct Stack {
config: StackConfig,
infra: Vec<ServiceProcess>,
@@ -101,16 +109,21 @@ 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)> {
+ fn identity_companion_tables(person_table: &str) -> Result<IdentityCompanionTables> {
+ let (lifecycle_op, lifecycle_op_person) = crate::seed::lifecycle_tables_for(person_table);
match person_table {
- "posthog_person" => Ok((
- "posthog_persondistinctid",
- "posthog_featureflaghashkeyoverride",
- )),
- "personhog_person_tmp" => Ok((
- "personhog_persondistinctid_tmp",
- "personhog_featureflaghashkeyoverride_tmp",
- )),
+ "posthog_person" => Ok(IdentityCompanionTables {
+ person_distinct_id: "posthog_persondistinctid",
+ ff_hash_key_override: "posthog_featureflaghashkeyoverride",
+ lifecycle_op,
+ lifecycle_op_person,
+ }),
+ "personhog_person_tmp" => Ok(IdentityCompanionTables {
+ person_distinct_id: "personhog_persondistinctid_tmp",
+ ff_hash_key_override: "personhog_featureflaghashkeyoverride_tmp",
+ lifecycle_op,
+ lifecycle_op_person,
+ }),
other => bail!(
"--create-via-identity has no known identity table set for \
--pg-target-table {other:?}"
@@ -253,8 +266,7 @@ impl Stack {
// 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)?;
+ let companions = Self::identity_companion_tables(&config.pg_target_table)?;
infra.push(ServiceProcess::spawn(
"identity",
&config.bin_dir.join("personhog-identity"),
@@ -264,8 +276,19 @@ impl Stack {
("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()),
+ (
+ "PERSON_DISTINCT_ID_TABLE",
+ companions.person_distinct_id.to_string(),
+ ),
+ (
+ "FF_HASH_KEY_OVERRIDE_TABLE",
+ companions.ff_hash_key_override.to_string(),
+ ),
+ ("LIFECYCLE_OP_TABLE", companions.lifecycle_op.to_string()),
+ (
+ "LIFECYCLE_OP_PERSON_TABLE",
+ companions.lifecycle_op_person.to_string(),
+ ),
// The service default is off. The gate needs the
// sweeper: a leader kill abandons a merge mid-saga,
// and only the sweeper re-drives it. The short
@@ -313,6 +336,8 @@ impl Stack {
pub fn spawn_leader(&mut self) -> Result<String> {
let index = self.next_leader_index;
self.next_leader_index += 1;
+ let (lifecycle_op, lifecycle_op_person) =
+ crate::seed::lifecycle_tables_for(&self.config.pg_target_table);
let grpc_port = LEADER_GRPC_BASE_PORT + index as u16;
// A real pod name: the leader derives its advertise address from
@@ -355,6 +380,8 @@ impl Stack {
// dirty index treats an unmarked person's PG row as
// current, which is only true of the writer's own table.
("FALLBACK_TABLE", self.config.pg_target_table.clone()),
+ ("LIFECYCLE_OP_TABLE", lifecycle_op.to_string()),
+ ("LIFECYCLE_OP_PERSON_TABLE", lifecycle_op_person.to_string()),
(
"METRICS_PORT",
(LEADER_METRICS_BASE_PORT + index as u16).to_string(),
diff --git a/rust/personhog-test-harness/src/verify.rs b/rust/personhog-test-harness/src/verify.rs
index 993235e29f5e..ca2f04f7a446 100644
--- a/rust/personhog-test-harness/src/verify.rs
+++ b/rust/personhog-test-harness/src/verify.rs
@@ -60,10 +60,13 @@ pub async fn verify_postgres(
.collect::<Vec<_>>();
// The saga records each source's seal on its op row and sets the
// row's status to deleted after the flip.
- let sealed_query = "SELECT person_id, (sealed->>'version')::bigint AS sealed_version \
- FROM lifecycle_op_person \
- WHERE team_id = $1 AND role = 'source' AND status = 'deleted' \
- AND person_id = ANY($2)";
+ let (_, lifecycle_op_person) = crate::seed::lifecycle_tables_for(table);
+ let sealed_query = format!(
+ "SELECT person_id, (sealed->>'version')::bigint AS sealed_version \
+ FROM {lifecycle_op_person} \
+ WHERE team_id = $1 AND role = 'source' AND status = 'deleted' \
+ AND person_id = ANY($2)"
+ );
let deadline = Instant::now() + QUIESCE_DEADLINE;
loop {
let rows = sqlx::query(&query)
@@ -137,7 +140,7 @@ pub async fn verify_postgres(
tombstones.insert(id, (is_deleted, version.unwrap_or(0)));
}
let mut seals: HashMap<i64, i64> = HashMap::new();
- for row in sqlx::query(sealed_query)
+ for row in sqlx::query(&sealed_query)
.bind(team)
.bind(&merged_ids)
.fetch_all(pool)