Skip to content

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

feat(personhog): add the publish outbox with op pointers (#116945)

José Sequeira3b515ee9fe5b
diff --git a/posthog/dags/personhog_shadow_lane.py b/posthog/dags/personhog_shadow_lane.py
index c910db00c29d..56f59908c2a4 100644
--- a/posthog/dags/personhog_shadow_lane.py
+++ b/posthog/dags/personhog_shadow_lane.py
@@ -88,6 +88,8 @@ PERSONHOG_STATE_TABLES = [
*LIFECYCLE_OP_TABLES,
"person_pg_cleanup_queue",
"person_tombstone_publish_queue",
+ "person_publish_outbox",
+ "person_publish_outbox_tmp",
]
diff --git a/rust/personhog-identity/.sqlx/query-44523b7acbaae8657911a3c0b3bfe9e71587ff33ddcb30a666a2fef348a11eb0.json b/rust/personhog-identity/.sqlx/query-44523b7acbaae8657911a3c0b3bfe9e71587ff33ddcb30a666a2fef348a11eb0.json
new file mode 100644
index 000000000000..7ca715a28a66
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-44523b7acbaae8657911a3c0b3bfe9e71587ff33ddcb30a666a2fef348a11eb0.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='op_complete_with_pointer' */ \n WITH done AS (\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 RETURNING op_id, team_id, op_type\n ), queued AS (\n INSERT INTO person_publish_outbox_tmp (team_id, kind, op_id)\n SELECT team_id, op_type || '_op', op_id FROM done\n )\n SELECT count(*) AS \"advanced!\" FROM done\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "advanced!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "44523b7acbaae8657911a3c0b3bfe9e71587ff33ddcb30a666a2fef348a11eb0"
+}
diff --git a/rust/personhog-identity/.sqlx/query-61c31b257f9577ac28071c6e842e9d74e2fd670b41764b23c2c0cf50cde94664.json b/rust/personhog-identity/.sqlx/query-61c31b257f9577ac28071c6e842e9d74e2fd670b41764b23c2c0cf50cde94664.json
new file mode 100644
index 000000000000..21736ed485ca
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-61c31b257f9577ac28071c6e842e9d74e2fd670b41764b23c2c0cf50cde94664.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='op_gc' */ \n DELETE FROM lifecycle_op_tmp\n WHERE op_id IN (\n SELECT op.op_id FROM lifecycle_op_tmp op\n WHERE op.completed_at IS NOT NULL\n AND op.completed_at < now() - make_interval(secs => $1)\n AND NOT EXISTS (\n SELECT 1 FROM person_publish_outbox_tmp o WHERE o.op_id = op.op_id\n )\n LIMIT $2\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Float8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "61c31b257f9577ac28071c6e842e9d74e2fd670b41764b23c2c0cf50cde94664"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ae66e881849ca01dc27fb79726d84d267612ecf13b39431bdeb81dcefc23a912.json b/rust/personhog-identity/.sqlx/query-ae66e881849ca01dc27fb79726d84d267612ecf13b39431bdeb81dcefc23a912.json
deleted file mode 100644
index bfa9d95e14b2..000000000000
--- a/rust/personhog-identity/.sqlx/query-ae66e881849ca01dc27fb79726d84d267612ecf13b39431bdeb81dcefc23a912.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "/* service='personhog-identity', operation='op_gc' */ \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": "ae66e881849ca01dc27fb79726d84d267612ecf13b39431bdeb81dcefc23a912"
-}
diff --git a/rust/personhog-identity/.sqlx/query-edc38267038927c70854616217cf9cb55a4e28e11e5934ba5cc6805b35284c57.json b/rust/personhog-identity/.sqlx/query-edc38267038927c70854616217cf9cb55a4e28e11e5934ba5cc6805b35284c57.json
new file mode 100644
index 000000000000..0296612e5564
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-edc38267038927c70854616217cf9cb55a4e28e11e5934ba5cc6805b35284c57.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='op_gc' */ \n DELETE FROM lifecycle_op\n WHERE op_id IN (\n SELECT op.op_id FROM lifecycle_op op\n WHERE op.completed_at IS NOT NULL\n AND op.completed_at < now() - make_interval(secs => $1)\n AND NOT EXISTS (\n SELECT 1 FROM person_publish_outbox o WHERE o.op_id = op.op_id\n )\n LIMIT $2\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Float8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "edc38267038927c70854616217cf9cb55a4e28e11e5934ba5cc6805b35284c57"
+}
diff --git a/rust/personhog-identity/.sqlx/query-f5762c8a18191e4a2e19328d0ebc55ae4cd466ed3dc7c0d2dcc0ab462b43974c.json b/rust/personhog-identity/.sqlx/query-f5762c8a18191e4a2e19328d0ebc55ae4cd466ed3dc7c0d2dcc0ab462b43974c.json
new file mode 100644
index 000000000000..0251af8d938e
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-f5762c8a18191e4a2e19328d0ebc55ae4cd466ed3dc7c0d2dcc0ab462b43974c.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='op_complete_with_pointer' */ \n WITH done AS (\n UPDATE lifecycle_op\n SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL\n WHERE op_id = $1 AND step = $2\n RETURNING op_id, team_id, op_type\n ), queued AS (\n INSERT INTO person_publish_outbox (team_id, kind, op_id)\n SELECT team_id, op_type || '_op', op_id FROM done\n )\n SELECT count(*) AS \"advanced!\" FROM done\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "advanced!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f5762c8a18191e4a2e19328d0ebc55ae4cd466ed3dc7c0d2dcc0ab462b43974c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-fad4fa7daa65822c9b233deff9620b1126353e31c4951259815716ef4814ca72.json b/rust/personhog-identity/.sqlx/query-fad4fa7daa65822c9b233deff9620b1126353e31c4951259815716ef4814ca72.json
deleted file mode 100644
index eab55cc5f83e..000000000000
--- a/rust/personhog-identity/.sqlx/query-fad4fa7daa65822c9b233deff9620b1126353e31c4951259815716ef4814ca72.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "/* service='personhog-identity', operation='op_gc' */ \n DELETE FROM lifecycle_op\n WHERE op_id IN (\n SELECT op_id FROM lifecycle_op\n WHERE completed_at IS NOT NULL\n AND completed_at < now() - make_interval(secs => $1)\n LIMIT $2\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Float8",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "fad4fa7daa65822c9b233deff9620b1126353e31c4951259815716ef4814ca72"
-}
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 968af54b5609..5e9b11ac232b 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -223,13 +223,38 @@ pub struct Config {
/// locks for long; the next pass continues.
#[envconfig(default = "10000")]
pub lifecycle_gc_batch_limit: i64,
+
+ /// Outbox the publisher drains, paired with LIFECYCLE_OP_TABLE: a merge
+ /// or delete op's pointer row resolves against that op's rows. Set to
+ /// "person_publish_outbox" at cutover.
+ #[envconfig(default = "person_publish_outbox_tmp")]
+ pub person_publish_outbox_table: String,
+
+ /// Write the publish outbox, one pointer per completed merge or delete
+ /// op, for a publisher to drain. Off, identity writes nothing there and
+ /// never names the outbox table in a completion. An outbox nobody drains
+ /// holds every pointed op past GC retention, so turn this on only where
+ /// a publisher runs against the same table set.
+ #[envconfig(default = "false")]
+ pub lifecycle_outbox_enabled: bool,
+}
+
+/// Whether identity writes the publish outbox (`LIFECYCLE_OUTBOX_ENABLED`):
+/// one pointer per completed merge or delete op. Carried by every writer so
+/// the choice is made where the writer is built, never defaulted at the
+/// write site.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OutboxWrites {
+ Enabled,
+ Disabled,
}
/// 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, 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.
+/// person ids, plus the saga tables whose marks claim those ids and the
+/// outbox whose pointers name those ops. All six 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,
@@ -237,6 +262,7 @@ pub struct IdentityTables {
pub ff_hash_key_override: String,
pub lifecycle_op: String,
pub lifecycle_op_person: String,
+ pub person_publish_outbox: String,
}
impl IdentityTables {
@@ -247,6 +273,7 @@ impl IdentityTables {
ff_hash_key_override: "posthog_featureflaghashkeyoverride".to_string(),
lifecycle_op: "lifecycle_op".to_string(),
lifecycle_op_person: "lifecycle_op_person".to_string(),
+ person_publish_outbox: "person_publish_outbox".to_string(),
}
}
@@ -257,6 +284,7 @@ impl IdentityTables {
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(),
+ person_publish_outbox: "person_publish_outbox_tmp".to_string(),
}
}
@@ -275,8 +303,9 @@ impl IdentityTables {
}
Err(format!(
"mixed identity table set {self:?}: set PERSON_TABLE, PERSON_DISTINCT_ID_TABLE, \
- 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"
+ FF_HASH_KEY_OVERRIDE_TABLE, LIFECYCLE_OP_TABLE, LIFECYCLE_OP_PERSON_TABLE, and \
+ PERSON_PUBLISH_OUTBOX_TABLE together, to either the full real set or the full \
+ validation set"
))
}
}
@@ -289,6 +318,15 @@ impl Config {
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(),
+ person_publish_outbox: self.person_publish_outbox_table.clone(),
+ }
+ }
+
+ pub fn outbox_writes(&self) -> OutboxWrites {
+ if self.lifecycle_outbox_enabled {
+ OutboxWrites::Enabled
+ } else {
+ OutboxWrites::Disabled
}
}
@@ -416,9 +454,6 @@ impl Config {
}
}
-// A mixed table set pairs person ids from one sequence with rows keyed by
-// another; validation must refuse it rather than let a partial env override
-// through.
#[cfg(test)]
mod tests {
use super::IdentityTables;
@@ -429,6 +464,9 @@ mod tests {
assert!(IdentityTables::validation().validate().is_ok());
}
+ // A mixed table set pairs person ids from one sequence with rows keyed by
+ // another; validation must refuse it rather than let a partial env
+ // override through.
#[test]
fn a_mixed_table_set_is_refused() {
let mixed = IdentityTables {
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index a1b973c7a77d..8b023b4b332d 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -30,11 +30,11 @@ use uuid::Uuid;
use personhog_proto::personhog::types::v1::LifecycleOpType;
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::leader::LifecycleLeader;
use crate::lifecycle::engine::{
- advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
- STEP_COMPLETED,
+ abort_op_in_tx, advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx,
+ STEP_ABORTED, STEP_COMPLETED,
};
use crate::lifecycle::leader_calls::{
fence_victims, release_fenced, Fenced, FencedVictim, LeaderCalls,
@@ -153,6 +153,7 @@ pub struct DeleteDriver {
/// The leaders' partition count, which decides which victims share a
/// fence call.
num_partitions: u32,
+ outbox_writes: OutboxWrites,
}
impl DeleteDriver {
@@ -161,6 +162,7 @@ impl DeleteDriver {
tables: IdentityTables,
leader_call_concurrency: usize,
num_partitions: u32,
+ outbox_writes: OutboxWrites,
) -> Self {
tables.validate().expect("invalid identity table set");
assert!(num_partitions > 0, "num_partitions must be > 0");
@@ -170,6 +172,7 @@ impl DeleteDriver {
// Clamped to 1: a zero-width buffered stream never polls.
leader_call_concurrency: leader_call_concurrency.max(1),
num_partitions,
+ outbox_writes,
}
}
@@ -203,7 +206,16 @@ impl OpDriver for DeleteDriver {
DeleteStep::Started => mark(pools, &self.tables, op).await,
DeleteStep::Marked => seal(pools, self.leader_calls(), &self.tables, op).await,
DeleteStep::Sealed => unmap(pools, &self.tables, op).await,
- DeleteStep::Unmapped => complete(pools, self.leader_calls(), &self.tables, op).await,
+ DeleteStep::Unmapped => {
+ complete(
+ pools,
+ self.leader_calls(),
+ &self.tables,
+ op,
+ self.outbox_writes,
+ )
+ .await
+ }
}
}
}
@@ -355,12 +367,11 @@ async fn mark(pools: &IdentityPools, tables: &IdentityTables, op: &OpRow) -> Res
// 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, tables, op.op_id, &request.person_ids).await?;
- let advanced = complete_op_in_tx(
+ let advanced = abort_op_in_tx(
&mut tx,
tables,
op.op_id,
DeleteStep::Started.as_str(),
- STEP_ABORTED,
&outcome,
)
.await?;
@@ -687,6 +698,7 @@ async fn complete(
calls: LeaderCalls<'_>,
tables: &IdentityTables,
op: &OpRow,
+ outbox_writes: OutboxWrites,
) -> Result<(), SagaError> {
let request = parse_request(op)?;
@@ -724,8 +736,8 @@ async fn complete(
tables,
op.op_id,
DeleteStep::Unmapped.as_str(),
- STEP_COMPLETED,
&outcome,
+ outbox_writes,
)
.await?
{
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 01b030627df7..e61212e44273 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -26,7 +26,7 @@ use serde_json::Value;
use tonic::Status;
use uuid::Uuid;
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::pools::{IdentityPools, Lane};
/// Terminal step: the op ran to the end.
@@ -857,6 +857,10 @@ impl Engine {
/// Delete completed op rows past retention (per-person rows cascade).
/// The retention window exists only for op_id idempotency — the durable
/// deletion shield is the person tombstone row, not the op row.
+ ///
+ /// An op with a row in the publish outbox outlives retention: a pending
+ /// pointer still has to be resolved against the op's `moved` rows, and a
+ /// given-up pointer must stay inspectable until an operator clears it.
pub async fn gc(&self, retention: Duration) -> Result<u64, SagaError> {
let result = mirrored_query!(
self.tables.is_validation(),
@@ -864,9 +868,12 @@ impl Engine {
r#"
DELETE FROM {lifecycle_op}
WHERE op_id IN (
- SELECT op_id FROM {lifecycle_op}
- WHERE completed_at IS NOT NULL
- AND completed_at < now() - make_interval(secs => $1)
+ SELECT op.op_id FROM {lifecycle_op} op
+ WHERE op.completed_at IS NOT NULL
+ AND op.completed_at < now() - make_interval(secs => $1)
+ AND NOT EXISTS (
+ SELECT 1 FROM {person_publish_outbox} o WHERE o.op_id = op.op_id
+ )
LIMIT $2
)
"#,
@@ -906,9 +913,46 @@ pub async fn advance_step_in_tx(
Ok(result.rows_affected() == 1)
}
-/// Terminal flavor of [`advance_step_in_tx`]: record the outcome, stamp
-/// `completed_at`, and drop the lease in the same compare-and-swap.
+/// Terminal flavor of [`advance_step_in_tx`] for an op that ran to the
+/// end: record the outcome, stamp `completed_at`, drop the lease and, with
+/// outbox writes enabled, enqueue the op's publish pointer, all in one
+/// compare-and-swap. The insert selects from the update's own `RETURNING`,
+/// so a pointer cannot exist unless the compare-and-swap won in the same
+/// statement. With outbox writes disabled the statement names only
+/// `lifecycle_op`, so identity completes ops without the outbox table
+/// until the flag is turned on.
pub async fn complete_op_in_tx(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+ from: &str,
+ outcome: &Value,
+ outbox_writes: OutboxWrites,
+) -> Result<bool, sqlx::Error> {
+ match outbox_writes {
+ OutboxWrites::Enabled => {
+ complete_op_with_pointer_in_tx(tx, tables, op_id, from, outcome).await
+ }
+ OutboxWrites::Disabled => {
+ settle_op_in_tx(tx, tables, op_id, from, STEP_COMPLETED, outcome).await
+ }
+ }
+}
+
+/// Terminal flavor of [`advance_step_in_tx`] for an op that backed out
+/// before mutating anything. It takes no publish setting because there is
+/// nothing to publish; that is structural, not a branch.
+pub async fn abort_op_in_tx(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+ from: &str,
+ outcome: &Value,
+) -> Result<bool, sqlx::Error> {
+ settle_op_in_tx(tx, tables, op_id, from, STEP_ABORTED, outcome).await
+}
+
+async fn settle_op_in_tx(
tx: &mut Tx<'_>,
tables: &IdentityTables,
op_id: Uuid,
@@ -932,3 +976,34 @@ pub async fn complete_op_in_tx(
)?;
Ok(result.rows_affected() == 1)
}
+
+async fn complete_op_with_pointer_in_tx(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+ from: &str,
+ outcome: &Value,
+) -> Result<bool, sqlx::Error> {
+ let advanced = mirrored_query_scalar!(
+ tables.is_validation(),
+ op = "op_complete_with_pointer",
+ r#"
+ WITH done AS (
+ UPDATE {lifecycle_op}
+ SET step = $3, outcome = $4, completed_at = now(), lease_expires_at = NULL
+ WHERE op_id = $1 AND step = $2
+ RETURNING op_id, team_id, op_type
+ ), queued AS (
+ INSERT INTO {person_publish_outbox} (team_id, kind, op_id)
+ SELECT team_id, op_type || '_op', op_id FROM done
+ )
+ SELECT count(*) AS "advanced!" FROM done
+ "#,
+ op_id,
+ from,
+ STEP_COMPLETED,
+ outcome
+ => fetch_one(&mut **tx)
+ )?;
+ Ok(advanced == 1)
+}
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index d1f9798e7289..952c19f39452 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -48,12 +48,12 @@ use personhog_proto::personhog::types::v1::{
ReleaseOutcome, SealedSourceSnapshot,
};
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::leader::LifecycleLeader;
use crate::lifecycle::detach::DetachedDrives;
use crate::lifecycle::engine::{
- advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
- STEP_COMPLETED,
+ abort_op_in_tx, advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx,
+ STEP_ABORTED, STEP_COMPLETED,
};
use crate::pools::{IdentityPools, Lane};
use personhog_common::query_tag;
@@ -353,6 +353,7 @@ pub struct MergeDriver {
leader: Arc<dyn LifecycleLeader>,
tables: IdentityTables,
leader_call_concurrency: usize,
+ outbox_writes: OutboxWrites,
}
impl MergeDriver {
@@ -360,6 +361,7 @@ impl MergeDriver {
leader: Arc<dyn LifecycleLeader>,
tables: IdentityTables,
leader_call_concurrency: usize,
+ outbox_writes: OutboxWrites,
) -> Self {
tables.validate().expect("invalid identity table set");
Self {
@@ -367,6 +369,7 @@ impl MergeDriver {
tables,
// Clamped to 1: a zero-width buffered stream never polls.
leader_call_concurrency: leader_call_concurrency.max(1),
+ outbox_writes,
}
}
}
@@ -1007,12 +1010,11 @@ async fn abort_in_claim_tx(
// The entrance discards flagged rows on the next presentation of the
// op id, so a plain retry re-runs where a recorded conflict replays.
outcome["claim_abort"] = Value::Bool(true);
- if !complete_op_in_tx(
+ if !abort_op_in_tx(
&mut tx,
tables,
op.op_id,
MergeStep::Started.as_str(),
- STEP_ABORTED,
&outcome,
)
.await?
@@ -1137,12 +1139,11 @@ impl MergeDriver {
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(
+ if !abort_op_in_tx(
&mut tx,
&self.tables,
op.op_id,
MergeStep::Claimed.as_str(),
- STEP_ABORTED,
&outcome,
)
.await?
@@ -1217,12 +1218,11 @@ impl MergeDriver {
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, &self.tables, op, Some(AbortOutcome::Refused)).await?;
- if !complete_op_in_tx(
+ if !abort_op_in_tx(
&mut tx,
&self.tables,
op.op_id,
from_step.as_str(),
- STEP_ABORTED,
&outcome,
)
.await?
@@ -1960,8 +1960,8 @@ impl MergeDriver {
&self.tables,
op.op_id,
MergeStep::Flipped.as_str(),
- STEP_COMPLETED,
&outcome,
+ self.outbox_writes,
)
.await?
{
diff --git a/rust/personhog-identity/src/lifecycle/mod.rs b/rust/personhog-identity/src/lifecycle/mod.rs
index 9d364f150d65..aa446402e541 100644
--- a/rust/personhog-identity/src/lifecycle/mod.rs
+++ b/rust/personhog-identity/src/lifecycle/mod.rs
@@ -23,6 +23,7 @@ use personhog_proto::personhog::lifecycle::v1::{
DeletePersonOutcome, DeletePersonResult, DeletePersonsRequest, DeletePersonsResponse,
};
+use crate::config::OutboxWrites;
use crate::leader::LifecycleLeader;
use crate::lifecycle::delete::{
DeleteDriver, DeleteOutcome, OUTCOME_DELETED, OUTCOME_NOT_FOUND, OUTCOME_SKIPPED_CONFLICT,
@@ -42,6 +43,7 @@ impl PersonHogLifecycleService {
tables: crate::config::IdentityTables,
leader_call_concurrency: usize,
num_partitions: u32,
+ outbox_writes: OutboxWrites,
) -> Self {
Self {
engine,
@@ -50,6 +52,7 @@ impl PersonHogLifecycleService {
tables,
leader_call_concurrency,
num_partitions,
+ outbox_writes,
),
}
}
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index f38eac84fcc6..f856683aff5f 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -112,10 +112,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.init();
- config
- .tables()
- .validate()
- .expect("Invalid identity table set");
+ let tables = config.tables();
+ tables.validate().expect("Invalid identity table set");
tracing::info!("Starting personhog-identity service");
tracing::info!("gRPC address: {}", config.grpc_address);
@@ -127,7 +125,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
router_channels = config.router_channels,
"Leader fan-out concurrency"
);
- tracing::info!("Tables: {:?}", config.tables());
+ tracing::info!("Tables: {:?}", tables);
+ let outbox_writes = config.outbox_writes();
+ if config.lifecycle_outbox_enabled {
+ tracing::info!(
+ outbox = %tables.person_publish_outbox,
+ "Lifecycle outbox enabled; a personhog-publisher on the same table set must drain it"
+ );
+ if tables.is_validation() {
+ tracing::warn!(
+ outbox = %tables.person_publish_outbox,
+ "Lifecycle outbox is on for the validation table set; the publisher draining it must point at capture topics, never the production names"
+ );
+ }
+ }
// The delete saga groups its fence calls by the leaders' partition
// count, which lives in etcd; a service that cannot read it would
@@ -290,12 +301,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
property_writer.clone(),
config.tables(),
config.lifecycle_leader_call_concurrency,
+ outbox_writes,
);
let sweeper_delete_driver = DeleteDriver::new(
lifecycle_leader.clone(),
config.tables(),
config.lifecycle_leader_call_concurrency,
num_partitions,
+ outbox_writes,
);
let sweeper_engine = engine.clone();
let sweep_interval = config.lifecycle_sweep_interval();
@@ -347,6 +360,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
property_writer.clone(),
config.tables(),
config.lifecycle_leader_call_concurrency,
+ outbox_writes,
),
detached_drives.clone(),
),
@@ -357,6 +371,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.tables(),
config.lifecycle_leader_call_concurrency,
num_partitions,
+ outbox_writes,
);
let service = PersonHogIdentityService::new(
storage,
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 9a924e4bce99..2a8a7c774a72 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -198,6 +198,13 @@ impl TestContext {
}
pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
+ sqlx::query(&format!(
+ "DELETE FROM {} WHERE team_id = $1",
+ self.tables.person_publish_outbox
+ ))
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await?;
sqlx::query(&format!(
"DELETE FROM {} WHERE team_id = $1",
self.tables.lifecycle_op
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
index 708bae0af33d..139b3df4dc0c 100644
--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -13,6 +13,7 @@ use personhog_common::partitioning::partition_for_person;
use tonic::{Request, Status};
use uuid::Uuid;
+use personhog_identity::config::OutboxWrites;
use personhog_identity::lifecycle::delete::{DeleteDriver, DeleteOutcome};
use personhog_identity::lifecycle::engine::{Engine, OpRow, SagaError};
use personhog_identity::lifecycle::PersonHogLifecycleService;
@@ -31,6 +32,7 @@ impl TestContext {
self.tables.clone(),
common::FAN_OUT_CONCURRENCY,
common::NUM_PARTITIONS,
+ OutboxWrites::Disabled,
)
}
@@ -563,6 +565,7 @@ impl FencedHarness {
ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
common::NUM_PARTITIONS,
+ OutboxWrites::Disabled,
);
Self {
ctx,
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index 3bab3e308b9f..15b3379c0411 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -22,28 +22,50 @@ use sqlx::postgres::PgPool;
use uuid::Uuid;
use personhog_common::grpc::semantic_refusal;
+use personhog_identity::config::OutboxWrites;
use personhog_identity::lifecycle::detach::DetachedDrives;
use personhog_identity::lifecycle::engine::{
- advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, STEP_COMPLETED,
+ abort_op_in_tx, advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError,
+ STEP_ABORTED, STEP_COMPLETED,
};
use personhog_identity::pools::IdentityPools;
-/// Two-step dummy op: `started → half → completed`. Counts step executions
-/// so tests can prove what did (or did not) re-run.
+/// Two-step dummy op: `started → half → <final step>`. Counts step
+/// executions so tests can prove what did (or did not) re-run.
struct DummyDriver {
steps_run: AtomicUsize,
pause: std::time::Duration,
+ final_step: &'static str,
+ outbox_writes: OutboxWrites,
}
impl DummyDriver {
fn new() -> Self {
- Self::paced(std::time::Duration::ZERO)
+ Self::with(
+ std::time::Duration::ZERO,
+ STEP_COMPLETED,
+ OutboxWrites::Disabled,
+ )
}
fn paced(pause: std::time::Duration) -> Self {
+ Self::with(pause, STEP_COMPLETED, OutboxWrites::Disabled)
+ }
+
+ fn settling(final_step: &'static str, outbox_writes: OutboxWrites) -> Self {
+ Self::with(std::time::Duration::ZERO, final_step, outbox_writes)
+ }
+
+ fn with(
+ pause: std::time::Duration,
+ final_step: &'static str,
+ outbox_writes: OutboxWrites,
+ ) -> Self {
Self {
steps_run: AtomicUsize::new(0),
pause,
+ final_step,
+ outbox_writes,
}
}
}
@@ -73,13 +95,23 @@ impl OpDriver for DummyDriver {
)
.await?
}
- "half" => {
+ "half" if self.final_step == STEP_COMPLETED => {
complete_op_in_tx(
&mut tx,
&common::default_tables(),
op.op_id,
"half",
- STEP_COMPLETED,
+ &json!({"ok": true}),
+ self.outbox_writes,
+ )
+ .await?
+ }
+ "half" => {
+ abort_op_in_tx(
+ &mut tx,
+ &common::default_tables(),
+ op.op_id,
+ "half",
&json!({"ok": true}),
)
.await?
@@ -261,37 +293,137 @@ async fn resume_picks_up_an_op_from_its_saved_step() {
ctx.cleanup().await.expect("cleanup");
}
+async fn pointer_kinds(ctx: &TestContext, op_id: Uuid) -> Vec<String> {
+ sqlx::query_scalar("SELECT kind FROM person_publish_outbox WHERE op_id = $1")
+ .bind(op_id)
+ .fetch_all(&ctx.pool)
+ .await
+ .expect("query runs")
+}
+
#[tokio::test]
-async fn gc_reaps_completed_ops_past_retention() {
+async fn only_a_completed_op_with_outbox_writes_enabled_enqueues_a_publish_pointer() {
let ctx = TestContext::new().await;
let engine = ctx.engine();
- let driver = DummyDriver::new();
- let op_id = Uuid::now_v7();
+ let cases = [
+ (
+ OutboxWrites::Enabled,
+ STEP_COMPLETED,
+ vec!["merge_op".to_string()],
+ ),
+ (OutboxWrites::Enabled, STEP_ABORTED, vec![]),
+ (OutboxWrites::Disabled, STEP_COMPLETED, vec![]),
+ ];
+ for (outbox_writes, final_step, expected) in cases {
+ let driver = DummyDriver::settling(final_step, outbox_writes);
+ let op_id = Uuid::now_v7();
+ engine
+ .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .await
+ .expect("op settles");
+ assert_eq!(
+ pointer_kinds(&ctx, op_id).await,
+ expected,
+ "{outbox_writes:?} {final_step}"
+ );
+ }
+ // The pointer rides the compare-and-swap: a completion that loses it
+ // (the row is not on `from`) commits nothing, pointer included.
+ let driver = DummyDriver::settling(STEP_COMPLETED, OutboxWrites::Enabled);
+ let op_id = Uuid::now_v7();
engine
- .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .create_or_attach(&driver, op_id, ctx.team_id, &json!({}))
.await
- .expect("op completes");
+ .expect("op created");
+ let mut tx = ctx.pool.begin().await.expect("begin");
+ let advanced = complete_op_in_tx(
+ &mut tx,
+ &common::default_tables(),
+ op_id,
+ "half",
+ &json!({}),
+ OutboxWrites::Enabled,
+ )
+ .await
+ .expect("statement runs");
+ tx.commit().await.expect("commit");
+ assert!(!advanced, "the row is on 'started', not 'half'");
+ assert!(pointer_kinds(&ctx, op_id).await.is_empty());
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+async fn remaining_ops(ctx: &TestContext, op_ids: &[Uuid]) -> Vec<Uuid> {
+ sqlx::query_scalar("SELECT op_id FROM lifecycle_op WHERE op_id = ANY($1) ORDER BY op_id")
+ .bind(op_ids)
+ .fetch_all(&ctx.pool)
+ .await
+ .expect("query runs")
+}
- // Backdate the completion past retention; GC reaps it (and cascades the
- // per-person rows) without touching other tests' fresh rows.
+#[tokio::test]
+async fn gc_reaps_completed_ops_past_retention_unless_a_publish_pointer_remains() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ // Three completed ops: no outbox row, a pending pointer, a given-up pointer.
+ let plain = Uuid::now_v7();
+ let pending = Uuid::now_v7();
+ let given_up = Uuid::now_v7();
+ let all = [plain, pending, given_up];
+
+ for op_id in all {
+ engine
+ .execute(&driver, op_id, ctx.team_id, &json!({}))
+ .await
+ .expect("op completes");
+ }
sqlx::query(
- "UPDATE lifecycle_op SET completed_at = now() - interval '2 hours' WHERE op_id = $1",
+ r#"
+ INSERT INTO person_publish_outbox (team_id, kind, op_id, given_up_at, last_error)
+ VALUES ($1, 'merge_op', $2, NULL, NULL), ($1, 'merge_op', $3, now(), 'poison')
+ "#,
)
- .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .bind(pending)
+ .bind(given_up)
+ .execute(&ctx.pool)
+ .await
+ .expect("queue pointers");
+
+ // Backdate the completions past retention; GC reaps only the op nobody
+ // still has to publish, and cascades its per-person rows, without
+ // touching other tests' fresh rows.
+ sqlx::query(
+ "UPDATE lifecycle_op SET completed_at = now() - interval '2 hours' WHERE op_id = ANY($1)",
+ )
+ .bind(&all[..])
.execute(&ctx.pool)
.await
- .expect("backdate completion");
+ .expect("backdate completions");
engine
.gc(std::time::Duration::from_secs(3600))
.await
.expect("gc runs");
- let gone: Option<(String,)> = sqlx::query_as("SELECT step FROM lifecycle_op WHERE op_id = $1")
- .bind(op_id)
- .fetch_optional(&ctx.pool)
+ assert_eq!(
+ remaining_ops(&ctx, &all).await,
+ vec![pending, given_up],
+ "ops with a pointer survive, the plain op is deleted"
+ );
+
+ // Once the pointers are gone (published, or cleared by an operator), the
+ // next pass reaps the ops.
+ sqlx::query("DELETE FROM person_publish_outbox WHERE op_id = ANY($1)")
+ .bind(&all[..])
+ .execute(&ctx.pool)
+ .await
+ .expect("clear pointers");
+ engine
+ .gc(std::time::Duration::from_secs(3600))
.await
- .expect("query runs");
- assert!(gone.is_none(), "completed op past retention is deleted");
+ .expect("gc runs");
+ assert!(remaining_ops(&ctx, &all).await.is_empty());
ctx.cleanup().await.expect("cleanup");
}
@@ -695,8 +827,8 @@ impl OpDriver for RefusingDriver {
&common::default_tables(),
op.op_id,
"started",
- STEP_COMPLETED,
&json!({}),
+ OutboxWrites::Disabled,
)
.await?;
if !advanced {
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 9db8adf9b776..5dad7a356ac2 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -24,6 +24,7 @@ use sqlx::Row;
use tonic::{Code, Status};
use uuid::Uuid;
+use personhog_identity::config::OutboxWrites;
use personhog_identity::lifecycle::detach::DetachedDrives;
use personhog_identity::lifecycle::engine::{
Engine, OpDriver, OpRow, SagaError, STEP_ABORTED, STEP_COMPLETED,
@@ -56,6 +57,7 @@ impl MergeHarness {
leader.clone(),
ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
);
Self {
ctx,
@@ -1759,6 +1761,7 @@ impl MergeHarness {
self.leader.clone(),
self.ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
),
self.drives.clone(),
),
@@ -1787,6 +1790,7 @@ impl MergeHarness {
self.leader.clone(),
self.ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
),
self.drives.clone(),
),
@@ -2144,6 +2148,7 @@ async fn an_executor_call_dropped_once_detached_still_drives_the_merge() {
h.leader.clone(),
h.ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
),
h.drives.clone(),
);
@@ -2192,6 +2197,7 @@ async fn a_retry_waiting_behind_a_live_lease_dies_with_its_caller_instead_of_det
h.leader.clone(),
h.ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
),
h.drives.clone(),
);
@@ -2419,6 +2425,7 @@ async fn a_create_race_loser_answers_retryable_unavailable() {
h.leader.clone(),
h.ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ OutboxWrites::Disabled,
),
h.drives.clone(),
);
diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rs
index 1cd5fa457d23..861042d428ce 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -47,6 +47,7 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
tables,
common::FAN_OUT_CONCURRENCY,
common::NUM_PARTITIONS,
+ personhog_identity::config::OutboxWrites::Disabled,
);
service
.delete_persons(Request::new(request))
diff --git a/rust/personhog-identity/tests/service_tests.rs b/rust/personhog-identity/tests/service_tests.rs
index 5f4d31db1d87..43a992ffbccf 100644
--- a/rust/personhog-identity/tests/service_tests.rs
+++ b/rust/personhog-identity/tests/service_tests.rs
@@ -98,6 +98,7 @@ impl ServiceTestContext {
Arc::new(common::UnusedLeader),
ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
+ personhog_identity::config::OutboxWrites::Disabled,
),
DetachedDrives::new(common::FAN_OUT_CONCURRENCY),
),
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index 639f8410504e..954f5b058743 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -72,6 +72,17 @@ pub fn lifecycle_tables_for(person_table: &str) -> (&'static str, &'static str)
}
}
+/// The publish outbox paired with a person table, derived the way identity
+/// derives it. Identity validates its six tables as one set, so a spawned
+/// identity must be told this one too.
+pub fn publish_outbox_table_for(person_table: &str) -> &'static str {
+ if person_table == "personhog_person_tmp" {
+ "person_publish_outbox_tmp"
+ } else {
+ "person_publish_outbox"
+ }
+}
+
/// 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 f2b224faa884..1f9804060b36 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -79,6 +79,7 @@ struct IdentityCompanionTables {
ff_hash_key_override: &'static str,
lifecycle_op: &'static str,
lifecycle_op_person: &'static str,
+ person_publish_outbox: &'static str,
}
pub struct Stack {
@@ -111,18 +112,21 @@ impl Stack {
/// id namespace as its person table, so the three always travel together.
fn identity_companion_tables(person_table: &str) -> Result<IdentityCompanionTables> {
let (lifecycle_op, lifecycle_op_person) = crate::seed::lifecycle_tables_for(person_table);
+ let person_publish_outbox = crate::seed::publish_outbox_table_for(person_table);
match person_table {
"posthog_person" => Ok(IdentityCompanionTables {
person_distinct_id: "posthog_persondistinctid",
ff_hash_key_override: "posthog_featureflaghashkeyoverride",
lifecycle_op,
lifecycle_op_person,
+ person_publish_outbox,
}),
"personhog_person_tmp" => Ok(IdentityCompanionTables {
person_distinct_id: "personhog_persondistinctid_tmp",
ff_hash_key_override: "personhog_featureflaghashkeyoverride_tmp",
lifecycle_op,
lifecycle_op_person,
+ person_publish_outbox,
}),
other => bail!(
"--create-via-identity has no known identity table set for \
@@ -291,6 +295,10 @@ impl Stack {
"LIFECYCLE_OP_PERSON_TABLE",
companions.lifecycle_op_person.to_string(),
),
+ (
+ "PERSON_PUBLISH_OUTBOX_TABLE",
+ companions.person_publish_outbox.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
diff --git a/rust/persons_migrations/20261013000001_add_person_publish_outbox.sql b/rust/persons_migrations/20261013000001_add_person_publish_outbox.sql
new file mode 100644
index 000000000000..0551312a484d
--- /dev/null
+++ b/rust/persons_migrations/20261013000001_add_person_publish_outbox.sql
@@ -0,0 +1,115 @@
+-- Outbox for the ClickHouse distinct id feed (clickhouse_person_distinct_id),
+-- written by personhog-identity and drained by the personhog-publisher
+-- deployment.
+--
+-- Two row shapes share the table. A create or attach settles inline with no
+-- op record, so it writes one row per mapping in the same transaction as the
+-- mapping insert. A merge or delete saga already records every repointed or
+-- tombstoned mapping in lifecycle_op_person.moved, so its completion writes
+-- one pointer row per op and the publisher resolves the pointer against
+-- `moved` when it drains. (cursor_person_id, cursor_mapping_ordinal) is the
+-- last (person_id, position in `moved`) already published; resolution reads
+-- the rows strictly after it, so a large op drains across several claims.
+--
+-- No foreign key to lifecycle_op on purpose: lifecycle GC skips an op that
+-- still has a pointer, and a cascade would silently drop unpublished work.
+--
+-- The publisher deletes a row once Kafka acks it, so the table is near empty
+-- at steady state and its statistics describe an empty table. The partial
+-- index on pending rows keeps the claim an index scan whatever the planner
+-- estimates; the fixed autovacuum thresholds run vacuum on churn instead of
+-- on size; fillfactor 90 keeps the cursor update a HOT update.
+--
+-- SAFE: creates new empty tables and indexes only; takes no locks on existing
+-- tables. Idempotent and safe to re-run.
+
+CREATE TABLE IF NOT EXISTS person_publish_outbox (
+ id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
+ team_id INTEGER NOT NULL,
+ kind TEXT NOT NULL,
+ -- create and attach rows
+ person_uuid UUID,
+ distinct_id VARCHAR(400),
+ version BIGINT,
+ -- op pointers
+ op_id UUID,
+ cursor_person_id BIGINT NOT NULL DEFAULT 0,
+ cursor_mapping_ordinal BIGINT NOT NULL DEFAULT 0,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ given_up_at TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT person_publish_outbox_kind_check
+ CHECK (kind IN ('create', 'attach', 'merge_op', 'delete_op')),
+ -- The two shapes are exclusive: a mapping row with an op_id would hold
+ -- back that op's GC for nothing.
+ CONSTRAINT person_publish_outbox_shape_check CHECK (
+ (kind IN ('create', 'attach')
+ AND person_uuid IS NOT NULL AND distinct_id IS NOT NULL AND version IS NOT NULL
+ AND op_id IS NULL)
+ OR (kind IN ('merge_op', 'delete_op')
+ AND op_id IS NOT NULL
+ AND person_uuid IS NULL AND distinct_id IS NULL AND version IS NULL)
+ )
+) WITH (
+ autovacuum_vacuum_scale_factor = 0,
+ autovacuum_vacuum_threshold = 10000,
+ autovacuum_analyze_scale_factor = 0,
+ autovacuum_analyze_threshold = 10000,
+ autovacuum_vacuum_cost_delay = 0,
+ fillfactor = 90
+);
+
+CREATE INDEX IF NOT EXISTS person_publish_outbox_pending
+ ON person_publish_outbox (id) WHERE given_up_at IS NULL;
+
+-- One pointer per op: completion inserts it once, inside the step's
+-- compare-and-swap transaction.
+CREATE UNIQUE INDEX IF NOT EXISTS person_publish_outbox_op_id
+ ON person_publish_outbox (op_id) WHERE op_id IS NOT NULL;
+
+COMMENT ON TABLE person_publish_outbox IS
+ 'Distinct id rows and lifecycle op pointers not yet published to Kafka by personhog-publisher. Rows with given_up_at set need an operator.';
+
+-- Validation set twin, used by an identity on the _tmp tables.
+CREATE TABLE IF NOT EXISTS person_publish_outbox_tmp (
+ id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
+ team_id INTEGER NOT NULL,
+ kind TEXT NOT NULL,
+ person_uuid UUID,
+ distinct_id VARCHAR(400),
+ version BIGINT,
+ op_id UUID,
+ cursor_person_id BIGINT NOT NULL DEFAULT 0,
+ cursor_mapping_ordinal BIGINT NOT NULL DEFAULT 0,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ given_up_at TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT person_publish_outbox_tmp_kind_check
+ CHECK (kind IN ('create', 'attach', 'merge_op', 'delete_op')),
+ CONSTRAINT person_publish_outbox_tmp_shape_check CHECK (
+ (kind IN ('create', 'attach')
+ AND person_uuid IS NOT NULL AND distinct_id IS NOT NULL AND version IS NOT NULL
+ AND op_id IS NULL)
+ OR (kind IN ('merge_op', 'delete_op')
+ AND op_id IS NOT NULL
+ AND person_uuid IS NULL AND distinct_id IS NULL AND version IS NULL)
+ )
+) WITH (
+ autovacuum_vacuum_scale_factor = 0,
+ autovacuum_vacuum_threshold = 10000,
+ autovacuum_analyze_scale_factor = 0,
+ autovacuum_analyze_threshold = 10000,
+ autovacuum_vacuum_cost_delay = 0,
+ fillfactor = 90
+);
+
+CREATE INDEX IF NOT EXISTS person_publish_outbox_tmp_pending
+ ON person_publish_outbox_tmp (id) WHERE given_up_at IS NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS person_publish_outbox_tmp_op_id
+ ON person_publish_outbox_tmp (op_id) WHERE op_id IS NOT NULL;
+
+COMMENT ON TABLE person_publish_outbox_tmp IS
+ 'Validation set twin of person_publish_outbox.';