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): write publish outbox rows for creates and attaches (#117053)

José Sequeira30659e6234bb
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 662a8987f4df..45eb82a6102c 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -196,10 +196,11 @@ pub struct Config {
#[envconfig(default = "10000")]
pub lifecycle_gc_batch_limit: i64,
- /// Write the publish outbox, one pointer per completed merge or delete
- /// op, for the separate personhog-publisher deployment 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
+ /// Write the publish outbox, one row per create or attach mapping and
+ /// one pointer per completed merge or delete op, for the separate
+ /// personhog-publisher deployment to drain. Off, identity writes nothing
+ /// there and never names the outbox table in a mapping or completion
+ /// statement. 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")]
@@ -263,9 +264,9 @@ impl IdentityTablesConfig {
}
/// 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.
+/// one row per create or attach mapping and 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,
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index f856683aff5f..9adab1c995f2 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -240,7 +240,36 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
let pools = create_pools(&config);
- let storage = Arc::new(PostgresIdentityStorage::new(pools.clone(), config.tables()));
+ if config.lifecycle_outbox_enabled {
+ // With the outbox on, every create, attach and op completion names
+ // the table; refuse to start without it instead of failing each
+ // request once the pod is ready. Any other error is left to the
+ // request path, as warm_pool leaves a connection failure.
+ let probe = format!("SELECT 1 FROM {} LIMIT 0", tables.person_publish_outbox);
+ if let Err(e) = sqlx::query(&query_tag!("startup_outbox_probe", probe))
+ .execute(pools.fast())
+ .await
+ {
+ let undefined_table =
+ e.as_database_error().and_then(|db| db.code()).as_deref() == Some("42P01");
+ if undefined_table {
+ panic!(
+ "LIFECYCLE_OUTBOX_ENABLED is set but {} does not exist; apply the persons migration first",
+ tables.person_publish_outbox
+ );
+ }
+ tracing::warn!(
+ error = %e,
+ table = %tables.person_publish_outbox,
+ "Could not probe the publish outbox table at startup"
+ );
+ }
+ }
+ let storage = Arc::new(PostgresIdentityStorage::new(
+ pools.clone(),
+ config.tables(),
+ outbox_writes,
+ ));
// Pre-warm the DB connection pools before accepting traffic.
// connect_lazy() starts with zero connections; without this, the first
diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rs
index 6c8e56114378..18c77c55c33d 100644
--- a/rust/personhog-identity/src/storage/postgres/attach.rs
+++ b/rust/personhog-identity/src/storage/postgres/attach.rs
@@ -5,7 +5,7 @@ use std::collections::HashMap;
use sqlx::Row;
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::types::AttachOutcome;
@@ -21,12 +21,17 @@ use personhog_common::query_tag;
/// no longer sweep: the join rejects committed deletions, and the mark
/// check rejects persons held by a live op. The rare statement that slips
/// both leaves an orphaned mapping the next resolve treats as absent.
+///
+/// With outbox writes on, the same statement also queues one publish
+/// outbox row per mapping it wrote, through a data-modifying CTE, so the
+/// mapping and its row commit together without a transaction.
pub(super) async fn attach_distinct_ids(
pools: &IdentityPools,
tables: &IdentityTables,
team_id: i64,
person_id: i64,
distinct_ids: &[String],
+ outbox_writes: OutboxWrites,
) -> StorageResult<HashMap<String, AttachOutcome>> {
if distinct_ids.is_empty() {
return Ok(HashMap::new());
@@ -34,7 +39,7 @@ pub(super) async fn attach_distinct_ids(
let mut sorted: Vec<String> = distinct_ids.to_vec();
sorted.sort_unstable();
- let insert_sql = format!(
+ let insert = format!(
r#"
INSERT INTO {pdi} (distinct_id, person_id, team_id, version)
SELECT u.d, p.id, p.team_id, 1
@@ -57,8 +62,31 @@ pub(super) async fn attach_distinct_ids(
person = tables.person,
lop = tables.lifecycle_op_person,
);
+ let insert_sql = match outbox_writes {
+ OutboxWrites::Enabled => format!(
+ r#"
+ WITH written AS ({insert}),
+ queued AS (
+ INSERT INTO {outbox} (team_id, kind, person_uuid, distinct_id, version)
+ SELECT $3, 'attach', p.uuid, w.distinct_id, w.version
+ FROM written w
+ JOIN {person} p ON p.team_id = $3 AND p.id = $2
+ )
+ SELECT distinct_id, version FROM written
+ "#,
+ outbox = tables.person_publish_outbox,
+ person = tables.person,
+ ),
+ OutboxWrites::Disabled => insert,
+ };
let mut conn = pools.acquire(Lane::Heavy).await?;
- let written = sqlx::query(&query_tag!("attach_mappings", insert_sql))
+ // Tagged apart so the statement that also writes the outbox is
+ // attributable on its own in query statistics.
+ let tagged = match outbox_writes {
+ OutboxWrites::Enabled => query_tag!("attach_mappings_with_outbox", insert_sql),
+ OutboxWrites::Disabled => query_tag!("attach_mappings", insert_sql),
+ };
+ let written = sqlx::query(&tagged)
.bind(&sorted)
.bind(person_id)
.bind(team_id as i32)
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index 7874ea79bd87..b8fbba3f5733 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -15,7 +15,7 @@ use sqlx::Row;
use personhog_common::grpc::{current_client_name, current_method_name};
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::types::{AttachOutcome, DistinctIdMapping, Person, PersonStub, StubOutcome};
@@ -60,12 +60,17 @@ pub(super) fn person_columns(p: &str) -> String {
pub struct PostgresIdentityStorage {
pools: IdentityPools,
tables: IdentityTables,
+ outbox_writes: OutboxWrites,
}
impl PostgresIdentityStorage {
- pub fn new(pools: IdentityPools, tables: IdentityTables) -> Self {
+ pub fn new(pools: IdentityPools, tables: IdentityTables, outbox_writes: OutboxWrites) -> Self {
tables.validate().expect("invalid identity table set");
- Self { pools, tables }
+ Self {
+ pools,
+ tables,
+ outbox_writes,
+ }
}
fn query_labels(operation: &str, lane: Lane) -> [(String, String); 4] {
@@ -119,7 +124,7 @@ impl IdentityStorage for PostgresIdentityStorage {
async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {
let labels = Self::query_labels("create_person_stubs", Lane::Heavy);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- stub_create::create_person_stubs(&self.pools, &self.tables, stubs).await
+ stub_create::create_person_stubs(&self.pools, &self.tables, stubs, self.outbox_writes).await
}
async fn attach_distinct_ids(
@@ -130,7 +135,14 @@ impl IdentityStorage for PostgresIdentityStorage {
) -> StorageResult<HashMap<String, AttachOutcome>> {
let labels = Self::query_labels("attach_distinct_ids", Lane::Heavy);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- attach::attach_distinct_ids(&self.pools, &self.tables, team_id, person_id, distinct_ids)
- .await
+ attach::attach_distinct_ids(
+ &self.pools,
+ &self.tables,
+ team_id,
+ person_id,
+ distinct_ids,
+ self.outbox_writes,
+ )
+ .await
}
}
diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rs
index 02b299dc545a..3d27729d39ca 100644
--- a/rust/personhog-identity/src/storage/postgres/stub_create.rs
+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs
@@ -1,4 +1,4 @@
-//! The stub-creation transaction: one transaction, four steps, each a
+//! The stub-creation transaction: one transaction, five steps, each a
//! function below, called in order by [`create_person_stubs`]:
//!
//! 1. [`insert_or_revive_persons`] — multi-row person insert; a conflict
@@ -10,6 +10,9 @@
//! tombstoned mappings revive, live conflicts keep the existing row.
//! 4. [`resolve_stub_outcomes`] — decide Committed/LostRace per stub and
//! undo the rows of stubs that lost their primary mapping.
+//! 5. [`enqueue_mapping_rows`] — with outbox writes on, one publish outbox
+//! row per mapping the transaction leaves live, at the version the row
+//! carries.
//!
//! Cross-cutting invariants:
//! - Every multi-row statement binds arrays sorted by its conflict key —
@@ -19,7 +22,7 @@
//! second time" on same-command duplicates (the cardinality check fires
//! before the WHERE qual).
//! - Rows created in this transaction are invisible outside it until commit,
-//! so step 5 can delete them without anything referencing them.
+//! so step 4 can delete them without anything referencing them.
//! - Revived tombstones predate the transaction and must survive an undo:
//! they are re-tombstoned with another version bump, never deleted.
@@ -31,7 +34,7 @@ use uuid::Uuid;
use personhog_common::persons::person_uuid;
-use crate::config::IdentityTables;
+use crate::config::{IdentityTables, OutboxWrites};
use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::postgres::{person_columns, person_from_row};
@@ -56,12 +59,20 @@ struct ResolvedPerson {
/// Persons keyed by their (team_id, uuid) conflict key.
type PersonsByKey = HashMap<(i64, Uuid), ResolvedPerson>;
+/// A mapping row as this transaction left it: its owner and the version
+/// the row now carries, which the publish outbox has to repeat exactly.
+#[derive(Clone, Copy)]
+struct WrittenMapping {
+ person_id: i64,
+ version: i64,
+}
+
/// What the multi-row distinct id insert actually wrote.
struct MappingOutcome {
- /// (team_id, distinct_id) → person_id for each mapping this transaction
- /// inserted or revived. Keys that conflicted with a live mapping are
- /// absent — the existing mapping stands.
- written: HashMap<(i64, String), i64>,
+ /// (team_id, distinct_id) → the mapping this transaction inserted or
+ /// revived. Keys that conflicted with a live mapping are absent — the
+ /// existing mapping stands.
+ written: HashMap<(i64, String), WrittenMapping>,
/// The subset of `written` that revived a tombstoned mapping; an undo
/// must re-tombstone these instead of deleting them.
revived: HashSet<(i64, String)>,
@@ -71,6 +82,7 @@ pub(super) async fn create_person_stubs(
pools: &IdentityPools,
tables: &IdentityTables,
stubs: &[PersonStub],
+ outbox_writes: OutboxWrites,
) -> StorageResult<Vec<StubOutcome>> {
if stubs.is_empty() {
return Ok(Vec::new());
@@ -99,8 +111,11 @@ pub(super) async fn create_person_stubs(
let mapping =
insert_distinct_id_mappings(&mut tx, &tables.person_distinct_id, stubs, &uuids, &persons)
.await?;
- let outcomes =
+ let (outcomes, undone) =
resolve_stub_outcomes(&mut tx, tables, stubs, &uuids, &persons, &mapping).await?;
+ if outbox_writes == OutboxWrites::Enabled {
+ enqueue_mapping_rows(&mut tx, tables, &persons, &mapping, &undone).await?;
+ }
tx.commit().await?;
Ok(outcomes)
@@ -304,7 +319,7 @@ async fn insert_distinct_id_mappings(
version = COALESCE({pdi_table}.version, 0) + 1,
is_deleted = false
WHERE {pdi_table}.is_deleted = true
- RETURNING team_id::bigint AS team_id, distinct_id, person_id,
+ RETURNING team_id::bigint AS team_id, distinct_id, person_id, version,
(xmax = 0) AS inserted
"#
);
@@ -319,11 +334,15 @@ async fn insert_distinct_id_mappings(
let team_id: i64 = row.try_get("team_id")?;
let distinct_id: String = row.try_get("distinct_id")?;
let person_id: i64 = row.try_get("person_id")?;
+ let version: i64 = row.try_get("version")?;
let inserted: bool = row.try_get("inserted")?;
if !inserted {
mapping.revived.insert((team_id, distinct_id.clone()));
}
- mapping.written.insert((team_id, distinct_id), person_id);
+ mapping.written.insert(
+ (team_id, distinct_id),
+ WrittenMapping { person_id, version },
+ );
}
Ok(mapping)
}
@@ -332,7 +351,8 @@ async fn insert_distinct_id_mappings(
/// id maps to its person; a stub whose primary mapping went elsewhere is a
/// lost race, and if this transaction created its person, the rows are
/// undone (created this transaction, so nothing can reference them) so the
-/// stub doesn't linger orphaned.
+/// stub doesn't linger orphaned. Returns the outcomes and the ids of the
+/// persons it undid, whose mappings step 5 must not publish.
async fn resolve_stub_outcomes(
tx: &mut Tx<'_>,
tables: &IdentityTables,
@@ -340,15 +360,16 @@ async fn resolve_stub_outcomes(
uuids: &[Uuid],
persons: &PersonsByKey,
mapping: &MappingOutcome,
-) -> StorageResult<Vec<StubOutcome>> {
+) -> StorageResult<(Vec<StubOutcome>, HashSet<i64>)> {
let mut outcomes = Vec::with_capacity(stubs.len());
+ let mut undone: HashSet<i64> = HashSet::new();
for (i, stub) in stubs.iter().enumerate() {
let Some(resolved) = persons.get(&(stub.team_id, uuids[i])) else {
outcomes.push(StubOutcome::LostRace);
continue;
};
let primary_key = (stub.team_id, stub.distinct_id.clone());
- if mapping.written.get(&primary_key) == Some(&resolved.person.id) {
+ if mapping.written.get(&primary_key).map(|w| w.person_id) == Some(resolved.person.id) {
outcomes.push(StubOutcome::Committed {
person: resolved.person.clone(),
created: resolved.created_by_us,
@@ -357,6 +378,7 @@ async fn resolve_stub_outcomes(
}
if resolved.created_by_us {
undo_created_person(tx, tables, stub.team_id, resolved, mapping).await?;
+ undone.insert(resolved.person.id);
outcomes.push(StubOutcome::LostRace);
continue;
}
@@ -381,7 +403,7 @@ async fn resolve_stub_outcomes(
outcomes.push(StubOutcome::LostRace);
}
}
- Ok(outcomes)
+ Ok((outcomes, undone))
}
/// Undo one lost-race stub's rows: its distinct id mappings, then its person
@@ -401,9 +423,9 @@ async fn undo_created_person(
let revived_dids: Vec<String> = mapping
.written
.iter()
- .filter(|((t, d), pid)| {
+ .filter(|((t, d), w)| {
*t == team_id
- && **pid == resolved.person.id
+ && w.person_id == resolved.person.id
&& mapping.revived.contains(&(*t, d.clone()))
})
.map(|((_, d), _)| d.clone())
@@ -460,3 +482,58 @@ async fn undo_created_person(
}
Ok(())
}
+
+/// Step 5: one publish outbox row per mapping this transaction leaves live,
+/// at the version the row carries. Mappings of a person step 4 undid are
+/// deleted or re-tombstoned, as they were before the transaction, so they
+/// emit nothing. Sorted like every other multi-row statement; the outbox
+/// has no unique key besides its identity, so the insert takes no row lock
+/// another transaction waits on.
+async fn enqueue_mapping_rows(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ persons: &PersonsByKey,
+ mapping: &MappingOutcome,
+ undone: &HashSet<i64>,
+) -> StorageResult<()> {
+ let uuids: HashMap<i64, Uuid> = persons
+ .values()
+ .map(|r| (r.person.id, r.person.uuid))
+ .collect();
+ let mut rows: Vec<(i32, Uuid, &str, i64)> = mapping
+ .written
+ .iter()
+ .filter(|(_, w)| !undone.contains(&w.person_id))
+ .map(|((team_id, distinct_id), w)| {
+ let uuid = *uuids
+ .get(&w.person_id)
+ .expect("written mappings point at resolved persons");
+ (*team_id as i32, uuid, distinct_id.as_str(), w.version)
+ })
+ .collect();
+ if rows.is_empty() {
+ return Ok(());
+ }
+ rows.sort_by(|a, b| (a.0, a.2).cmp(&(b.0, b.2)));
+ let team_ids: Vec<i32> = rows.iter().map(|r| r.0).collect();
+ let person_uuids: Vec<Uuid> = rows.iter().map(|r| r.1).collect();
+ let distinct_ids: Vec<&str> = rows.iter().map(|r| r.2).collect();
+ let versions: Vec<i64> = rows.iter().map(|r| r.3).collect();
+
+ let sql = format!(
+ r#"
+ INSERT INTO {outbox} (team_id, kind, person_uuid, distinct_id, version)
+ SELECT t, 'create', u, d, v
+ FROM unnest($1::int[], $2::uuid[], $3::text[], $4::bigint[]) AS r(t, u, d, v)
+ "#,
+ outbox = tables.person_publish_outbox,
+ );
+ sqlx::query(&query_tag!("stub_create_enqueue_outbox", sql))
+ .bind(&team_ids)
+ .bind(&person_uuids)
+ .bind(&distinct_ids)
+ .bind(&versions)
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index b08454e9850d..65d6a062568e 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -11,7 +11,7 @@ use rand::Rng;
use sqlx::postgres::PgPool;
use uuid::Uuid;
-use personhog_identity::config::IdentityTables;
+use personhog_identity::config::{IdentityTables, OutboxWrites};
use personhog_identity::pools::IdentityPools;
use personhog_identity::publish::messages::DistinctIdRow;
use personhog_identity::publish::sink::{PublishBatch, PublishError, PublishSink};
@@ -61,7 +61,11 @@ impl TestContext {
.await
.expect("Failed to connect to test database");
let pools = IdentityPools::shared(pool.clone());
- let storage = Arc::new(PostgresIdentityStorage::new(pools.clone(), tables.clone()));
+ let storage = Arc::new(PostgresIdentityStorage::new(
+ pools.clone(),
+ tables.clone(),
+ OutboxWrites::Disabled,
+ ));
let team_id = rand::thread_rng().gen_range(1_000_000..100_000_000);
Self {
pool,
@@ -208,6 +212,14 @@ impl TestContext {
Ok(())
}
+ /// Storage that writes the publish outbox, for tests that assert on the
+ /// rows a create or attach leaves there; `storage` never writes it.
+ /// Take [`hold_drain_lock`](Self::hold_drain_lock) before the first
+ /// write through it.
+ pub fn storage_with(&self, outbox_writes: OutboxWrites) -> PostgresIdentityStorage {
+ PostgresIdentityStorage::new(self.pools.clone(), self.tables.clone(), outbox_writes)
+ }
+
/// A transaction-level advisory lock that every test writing outbox
/// rows takes before it writes any row it will assert on, and holds
/// until its assertions are done. Dropping the returned transaction
diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rs
index e26cce0636d0..92bc98b7345a 100644
--- a/rust/personhog-identity/tests/storage_tests.rs
+++ b/rust/personhog-identity/tests/storage_tests.rs
@@ -1,11 +1,14 @@
mod common;
+use std::collections::BTreeSet;
use std::time::Duration;
use chrono::{TimeZone, Utc};
use common::TestContext;
+use uuid::Uuid;
use personhog_common::persons::person_uuid;
+use personhog_identity::config::OutboxWrites;
use personhog_identity::storage::{AttachOutcome, IdentityStorage, PersonStub, StubOutcome};
/// Storage-assertion helpers used only by this test binary.
@@ -981,3 +984,247 @@ async fn attach_refuses_a_person_held_by_a_live_lifecycle_op() {
.expect("cleanup op");
ctx.cleanup().await.ok();
}
+
+/// (distinct_id, owner uuid, version) of every live mapping of this team.
+async fn live_mappings(ctx: &TestContext) -> BTreeSet<(String, Uuid, i64)> {
+ let rows: Vec<(String, Uuid, i64)> = sqlx::query_as(
+ r#"
+ SELECT d.distinct_id, p.uuid, d.version
+ FROM posthog_persondistinctid d
+ JOIN posthog_person p ON p.team_id = d.team_id AND p.id = d.person_id
+ WHERE d.team_id = $1 AND d.is_deleted = false
+ "#,
+ )
+ .bind(ctx.team_id as i32)
+ .fetch_all(&ctx.pool)
+ .await
+ .expect("read live mappings");
+ rows.into_iter().collect()
+}
+
+/// (kind, distinct_id, owner uuid, version) of every mapping row this team
+/// has in the publish outbox, sorted. A vector, not a set, so a row written
+/// twice shows up.
+async fn outbox_mapping_rows(ctx: &TestContext) -> Vec<(String, String, Uuid, i64)> {
+ let mut rows: Vec<(String, String, Uuid, i64)> = sqlx::query_as(
+ r#"
+ SELECT kind, distinct_id, person_uuid, version
+ FROM person_publish_outbox WHERE team_id = $1 AND op_id IS NULL
+ "#,
+ )
+ .bind(ctx.team_id as i32)
+ .fetch_all(&ctx.pool)
+ .await
+ .expect("read outbox rows");
+ rows.sort();
+ rows
+}
+
+/// The outbox gained exactly the live mappings added since `before`, each
+/// under `kind`, then it is cleared for the next case.
+async fn assert_outbox_matches_added_mappings(
+ ctx: &TestContext,
+ label: &str,
+ kind: &str,
+ before: &BTreeSet<(String, Uuid, i64)>,
+) -> usize {
+ let added: BTreeSet<(String, Uuid, i64)> = live_mappings(ctx)
+ .await
+ .difference(before)
+ .cloned()
+ .collect();
+ let mut expected: Vec<(String, String, Uuid, i64)> = added
+ .iter()
+ .map(|(distinct_id, uuid, version)| {
+ (kind.to_string(), distinct_id.clone(), *uuid, *version)
+ })
+ .collect();
+ expected.sort();
+ assert_eq!(outbox_mapping_rows(ctx).await, expected, "{label}");
+ sqlx::query("DELETE FROM person_publish_outbox WHERE team_id = $1")
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("clear outbox");
+ added.len()
+}
+
+// The regression in every case is an outbox row whose owner or version
+// differs from the mapping Postgres holds, or a row for a mapping an undo
+// took back: either leaves ClickHouse on a stale mapping, and the version
+// cases (0 for a primary, 1 for an extra, old plus one for a revival) are
+// exactly where a hard-coded value would pass the outcome assertions.
+#[tokio::test]
+async fn the_outbox_holds_exactly_the_live_mappings_a_create_or_attach_added() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let storage = ctx.storage_with(OutboxWrites::Enabled);
+
+ // Fresh create with extras: the primary at 0, the extras at 1.
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[stub(&ctx, "ob-primary", &["ob-extra-a", "ob-extra-b"])])
+ .await
+ .expect("create");
+ let [StubOutcome::Committed {
+ person,
+ created: true,
+ }] = &outcomes[..]
+ else {
+ panic!("expected a created outcome, got {outcomes:?}");
+ };
+ let person_id = person.id;
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "fresh create", "create", &before).await,
+ 3
+ );
+
+ // Revival of a tombstoned primary: the row comes back above its
+ // tombstone, and only that row is published.
+ ctx.tombstone_person(person_id, 7).await;
+ ctx.tombstone_distinct_id("ob-primary", 3).await;
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[stub(&ctx, "ob-primary", &[])])
+ .await
+ .expect("recreate");
+ assert!(matches!(
+ outcomes[..],
+ [StubOutcome::Committed { created: true, .. }]
+ ));
+ assert_eq!(ctx.distinct_id_version("ob-primary").await, Some(4));
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "revived primary", "create", &before).await,
+ 1
+ );
+
+ // Lost race with a created person: the undo removes every row the stub
+ // wrote, so nothing is published.
+ ctx.insert_person_with_distinct_id("ob-taken").await;
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[stub(&ctx, "ob-taken", &["ob-taken-extra"])])
+ .await
+ .expect("lost race");
+ assert!(matches!(outcomes[..], [StubOutcome::LostRace]));
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "lost race, created person", "create", &before)
+ .await,
+ 0
+ );
+
+ // Lost race with a revived person: the revived extra is re-tombstoned
+ // by the undo, so it must not be published either.
+ ctx.insert_person_with_distinct_id("ob-steal").await;
+ let dead_id = ctx
+ .insert_tombstoned_person(person_uuid(ctx.team_id, "ob-steal"), 5)
+ .await;
+ ctx.insert_tombstoned_distinct_id("ob-dead-extra", dead_id, 2)
+ .await;
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[stub(&ctx, "ob-steal", &["ob-dead-extra"])])
+ .await
+ .expect("lost race with revival");
+ assert!(matches!(outcomes[..], [StubOutcome::LostRace]));
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "lost race, revived person", "create", &before)
+ .await,
+ 0
+ );
+
+ // Attach: one fresh id, one revived id and one already mapped id; only
+ // the two the attach took are published, at the versions it wrote.
+ let owner = ctx.insert_person_with_distinct_id("ob-attach-owner").await;
+ let target = ctx.insert_person_with_distinct_id("ob-attach-target").await;
+ ctx.insert_tombstoned_distinct_id("ob-attach-tomb", owner, 5)
+ .await;
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .attach_distinct_ids(
+ ctx.team_id,
+ target,
+ &[
+ "ob-attach-fresh".to_string(),
+ "ob-attach-tomb".to_string(),
+ "ob-attach-owner".to_string(),
+ ],
+ )
+ .await
+ .expect("attach");
+ assert_eq!(
+ outcomes.get("ob-attach-fresh"),
+ Some(&AttachOutcome::Attached { version: 1 })
+ );
+ assert_eq!(
+ outcomes.get("ob-attach-tomb"),
+ Some(&AttachOutcome::Attached { version: 6 })
+ );
+ assert_eq!(
+ outcomes.get("ob-attach-owner"),
+ Some(&AttachOutcome::AlreadyMapped { person_id: owner })
+ );
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "attach", "attach", &before).await,
+ 2
+ );
+
+ // Mixed batch: one stub commits with an extra it shares with a second
+ // stub that loses its race. The shared extra stays live under the
+ // winner and is published once; the loser's own rows are undone and
+ // publish nothing.
+ ctx.insert_person_with_distinct_id("ob-mix-taken").await;
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[
+ stub(&ctx, "ob-mix-winner", &["ob-mix-shared"]),
+ stub(&ctx, "ob-mix-taken", &["ob-mix-own", "ob-mix-shared"]),
+ ])
+ .await
+ .expect("mixed batch");
+ assert!(
+ matches!(
+ outcomes[..],
+ [
+ StubOutcome::Committed { created: true, .. },
+ StubOutcome::LostRace
+ ]
+ ),
+ "expected committed + lost race, got {outcomes:?}"
+ );
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "mixed batch", "create", &before).await,
+ 2
+ );
+
+ // An extra added to a person that already exists: the live primary
+ // mapping stays out, the new extra is published under that person's
+ // uuid.
+ let before = live_mappings(&ctx).await;
+ let outcomes = storage
+ .create_person_stubs(&[stub(&ctx, "ob-mix-winner", &["ob-mix-late"])])
+ .await
+ .expect("late extra");
+ assert!(
+ matches!(
+ outcomes[..],
+ [StubOutcome::Committed { created: false, .. }]
+ ),
+ "expected an existing-person outcome, got {outcomes:?}"
+ );
+ assert_eq!(
+ assert_outbox_matches_added_mappings(&ctx, "late extra", "create", &before).await,
+ 1
+ );
+
+ // With outbox writes off, a create adds a live mapping and no row.
+ let before = live_mappings(&ctx).await;
+ ctx.storage
+ .create_person_stubs(&[stub(&ctx, "ob-off", &[])])
+ .await
+ .expect("create with writes off");
+ assert_eq!(live_mappings(&ctx).await.len(), before.len() + 1);
+ assert!(outbox_mapping_rows(&ctx).await.is_empty(), "writes off");
+
+ ctx.cleanup().await.ok();
+}