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 personhog-publisher to drain the publish outbox (#116946)

José Sequeirac39087a929e7
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index 13be47c87630..35ffcdb6eabc 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -126,6 +126,13 @@
dockerfile: ./rust/Dockerfile
project: jfz76fgvqd
+# Second binary of the personhog-identity crate: drains the publish outbox
+# identity writes. Shares identity's Depot project like the flags-cache
+# binaries share feature-flags'.
+- image: personhog-publisher
+ dockerfile: ./rust/Dockerfile
+ project: jfz76fgvqd
+
- image: personhog-leader
dockerfile: ./rust/Dockerfile
project: g0kjbvxgqx
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index a8984a24f95a..5e17f13d9a17 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -481,6 +481,16 @@ procs:
layer: Product services
tech: Rust
+ personhog-publisher:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service personhog-publisher
+ capability: personhog
+ ready_pattern: 'Metrics server listening on *'
+ groups:
+ layer: Product services
+ tech: Rust
+
personhog-etcd-init:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start-rust-service b/bin/start-rust-service
index fb20269dd9ba..ab1b5a357d64 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -300,6 +300,18 @@ case "$RS_SVC" in
export METRICS_PORT=9108
;;
+ personhog-publisher)
+ SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
+ export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
+ export RUST_BACKTRACE=1
+ # Same database and table set as personhog-identity: it drains the outbox identity writes.
+ export PRIMARY_DATABASE_URL="${PRIMARY_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/posthog_persons}"
+ export KAFKA_HOSTS="${KAFKA_HOSTS:-localhost:9092}"
+ # The topic has no default; locally the ClickHouse Kafka table reads the Node name.
+ export PERSON_DISTINCT_ID_TOPIC="${PERSON_DISTINCT_ID_TOPIC:-clickhouse_person_distinct_id}"
+ export METRICS_PORT=9109
+ ;;
+
flags-consumer)
SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
diff --git a/rust/AGENTS.md b/rust/AGENTS.md
index 4959daa709c2..c03f50f95fc0 100644
--- a/rust/AGENTS.md
+++ b/rust/AGENTS.md
@@ -8,3 +8,7 @@ When emitting metrics via the `metrics` crate (`histogram!`, `counter!`, `gauge!
- `current_client_name()` already returns `Arc<str>`, so use `.clone()` directly. Never call `.to_string()` on it.
- When passing a dynamic label through multiple functions, pass `Arc<str>` by value, not `&str` — the downstream function will need to clone it into macros anyway.
- Static label values (`"ok"`, `"error"`, `"unavailable"`) can be passed as `&'static str` literals directly.
+
+## personhog
+
+- **A change to the publish outbox contract between `personhog-identity` and `personhog-publisher` lands in the publisher first, in its own PR, and in identity in a later PR.** The two are separate deployments with no ordering between them. The contract (the outbox row shapes, the `lifecycle_op_person.moved` entries, the pointer cursor, the GC guard) is listed under "Publish outbox contract" in [personhog-identity/README.md](personhog-identity/README.md). Read it before you change `rust/personhog-identity/src/publish/`, the outbox writers in `src/lifecycle/` and `src/storage/`, or a persons migration that touches the outbox or `lifecycle_op_person`.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 0017df7c4429..5e666ba85292 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3014,6 +3014,7 @@ dependencies = [
"common-liveness",
"envconfig",
"health",
+ "lifecycle",
"lz4",
"metrics",
"rdkafka",
@@ -8942,6 +8943,7 @@ dependencies = [
"chrono",
"common-alloc",
"common-database",
+ "common-kafka",
"common-metrics",
"common-sqlx-macros",
"envconfig",
@@ -8953,6 +8955,7 @@ dependencies = [
"personhog-coordination",
"personhog-proto",
"rand 0.8.5",
+ "rdkafka",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/common/kafka/Cargo.toml b/rust/common/kafka/Cargo.toml
index 6d72b0bc7210..815487f45267 100644
--- a/rust/common/kafka/Cargo.toml
+++ b/rust/common/kafka/Cargo.toml
@@ -11,6 +11,7 @@ chrono = { workspace = true }
common-liveness = { path = "../liveness" }
envconfig = { workspace = true }
health = { path = "../health" }
+lifecycle = { path = "../lifecycle" }
lz4 = { workspace = true }
metrics = { workspace = true }
rdkafka = { workspace = true }
diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rs
index 8e54607b0711..b22d2c084f30 100644
--- a/rust/common/kafka/src/kafka_producer.rs
+++ b/rust/common/kafka/src/kafka_producer.rs
@@ -1,8 +1,10 @@
use std::io::Write;
use std::sync::Arc;
+use std::time::Duration;
use crate::config::KafkaConfig;
use common_liveness::SyncLivenessReporter;
+use lifecycle::Handle;
use lz4::EncoderBuilder;
use rdkafka::error::KafkaError;
use rdkafka::producer::{
@@ -188,6 +190,60 @@ where
Ok(api)
}
+/// Completes the kafka-producer lifecycle component with a bounded
+/// flush instead of waiting for the last producer reference to drop.
+///
+/// The component's handle rides inside the producer context, which
+/// every clone of the producer shares — so without explicit shutdown
+/// work, the component completed only when everything holding the
+/// producer let go, and a queue wedged against a stalled broker held
+/// its shutdown phase to the global timeout. This task flushes what
+/// the queue holds within `bound` once the component's phase shuts
+/// down, then reports completion either way.
+///
+/// A timed-out flush drops only records nobody awaited: a caller that
+/// awaits each record's delivery before it commits or acks has already
+/// seen those records leave the queue, and anything left is best effort
+/// or retried by the caller's own redelivery.
+pub fn spawn_bounded_flush_on_shutdown(
+ producer: FutureProducer<KafkaContext>,
+ handle: Handle,
+ bound: Duration,
+) {
+ tokio::spawn(async move {
+ handle.shutdown_recv().await;
+ let queued = producer.in_flight_count();
+ // Flush blocks, and so can the producer teardown after it; both
+ // stay off the async workers. Completion is reported first, so
+ // a teardown that outlives the flush bound cannot hold the
+ // phase.
+ let flushed = tokio::task::spawn_blocking(move || {
+ let outcome = producer.flush(bound);
+ let remaining = producer.in_flight_count();
+ drop(producer);
+ (outcome, remaining)
+ })
+ .await;
+ match flushed {
+ Ok((Ok(()), _)) => {
+ info!(queued, "kafka producer flushed at shutdown");
+ }
+ Ok((Err(e), remaining)) => {
+ warn!(
+ queued,
+ remaining,
+ error = %e,
+ "kafka producer flush hit its shutdown bound; undelivered records dropped"
+ );
+ }
+ Err(e) => {
+ warn!(error = %e, "kafka producer shutdown flush task failed");
+ }
+ }
+ handle.work_completed();
+ });
+}
+
/// A producer context that reports liveness (like [`KafkaContext`]) and, for
/// each produced message, invokes a caller-supplied closure with the delivery
/// report. This lets a caller observe delivery outcomes — e.g. emit
diff --git a/rust/personhog-identity/.sqlx/query-01ded12e17a86b76a203d6ce4b9503ee55ddc00e628289bc4be9af35ec8b7800.json b/rust/personhog-identity/.sqlx/query-01ded12e17a86b76a203d6ce4b9503ee55ddc00e628289bc4be9af35ec8b7800.json
new file mode 100644
index 000000000000..fef12a25d352
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-01ded12e17a86b76a203d6ce4b9503ee55ddc00e628289bc4be9af35ec8b7800.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_outbox_oldest' */ \n SELECT EXTRACT(EPOCH FROM now() - created_at)::float8 AS \"lag_seconds!\"\n FROM person_publish_outbox\n WHERE given_up_at IS NULL ORDER BY id LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "lag_seconds!",
+ "type_info": "Float8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "01ded12e17a86b76a203d6ce4b9503ee55ddc00e628289bc4be9af35ec8b7800"
+}
diff --git a/rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json b/rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json
new file mode 100644
index 000000000000..b27460fc35c2
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT count(*) FROM lifecycle_op_person_tmp lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op_tmp op\n WHERE op.op_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "target_rows!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "malformed_moved_rows!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "1caac56dd992b4ff190a6fa1a88af273e94e77fb1aca4463dbe2cf128343a500"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3470b933e2fa66a9eac4f28c7e898b3cfbcbbb563b720227aba2d3f448b197a3.json b/rust/personhog-identity/.sqlx/query-3470b933e2fa66a9eac4f28c7e898b3cfbcbbb563b720227aba2d3f448b197a3.json
new file mode 100644
index 000000000000..34206c3b6895
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3470b933e2fa66a9eac4f28c7e898b3cfbcbbb563b720227aba2d3f448b197a3.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_delete_finished' */ DELETE FROM person_publish_outbox WHERE id = ANY($1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3470b933e2fa66a9eac4f28c7e898b3cfbcbbb563b720227aba2d3f448b197a3"
+}
diff --git a/rust/personhog-identity/.sqlx/query-3597a6ae6864f4efb399cd352e023042dc22902a129b1bb5bb64ffe39081d0a5.json b/rust/personhog-identity/.sqlx/query-3597a6ae6864f4efb399cd352e023042dc22902a129b1bb5bb64ffe39081d0a5.json
new file mode 100644
index 000000000000..908cdb7cb956
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-3597a6ae6864f4efb399cd352e023042dc22902a129b1bb5bb64ffe39081d0a5.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_outbox_oldest' */ \n SELECT EXTRACT(EPOCH FROM now() - created_at)::float8 AS \"lag_seconds!\"\n FROM person_publish_outbox_tmp\n WHERE given_up_at IS NULL ORDER BY id LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "lag_seconds!",
+ "type_info": "Float8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3597a6ae6864f4efb399cd352e023042dc22902a129b1bb5bb64ffe39081d0a5"
+}
diff --git a/rust/personhog-identity/.sqlx/query-83af92dcc5a424d9d787243813598a684b18fd057ce6dfcbb1843d290c094e60.json b/rust/personhog-identity/.sqlx/query-83af92dcc5a424d9d787243813598a684b18fd057ce6dfcbb1843d290c094e60.json
new file mode 100644
index 000000000000..9ea7c274958b
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-83af92dcc5a424d9d787243813598a684b18fd057ce6dfcbb1843d290c094e60.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_outbox_counts' */ \n SELECT count(*) FILTER (WHERE given_up_at IS NULL) AS \"pending!\",\n count(*) FILTER (WHERE given_up_at IS NOT NULL) AS \"given_up!\"\n FROM (SELECT given_up_at FROM person_publish_outbox LIMIT $1) AS scanned\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pending!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "given_up!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "83af92dcc5a424d9d787243813598a684b18fd057ce6dfcbb1843d290c094e60"
+}
diff --git a/rust/personhog-identity/.sqlx/query-94bf82b71494016b7a7a96a34f8dbb12b84bf61d9e13f82e1b41e4fc763b58bf.json b/rust/personhog-identity/.sqlx/query-94bf82b71494016b7a7a96a34f8dbb12b84bf61d9e13f82e1b41e4fc763b58bf.json
new file mode 100644
index 000000000000..babf87e57a47
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-94bf82b71494016b7a7a96a34f8dbb12b84bf61d9e13f82e1b41e4fc763b58bf.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_advance_cursors' */ \n UPDATE person_publish_outbox o\n SET cursor_person_id = u.person_id,\n cursor_mapping_ordinal = u.mapping_ordinal,\n attempts = o.attempts + 1,\n last_error = NULL\n FROM unnest($1::bigint[], $2::bigint[], $3::bigint[]) AS u(id, person_id, mapping_ordinal)\n WHERE o.id = u.id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array",
+ "Int8Array",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "94bf82b71494016b7a7a96a34f8dbb12b84bf61d9e13f82e1b41e4fc763b58bf"
+}
diff --git a/rust/personhog-identity/.sqlx/query-99e6d2d33f5eb2f757a07755ac9b7c9281ac38cd60cb30416438241c710d83e3.json b/rust/personhog-identity/.sqlx/query-99e6d2d33f5eb2f757a07755ac9b7c9281ac38cd60cb30416438241c710d83e3.json
new file mode 100644
index 000000000000..2f7565717980
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-99e6d2d33f5eb2f757a07755ac9b7c9281ac38cd60cb30416438241c710d83e3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_advance_cursors' */ \n UPDATE person_publish_outbox_tmp o\n SET cursor_person_id = u.person_id,\n cursor_mapping_ordinal = u.mapping_ordinal,\n attempts = o.attempts + 1,\n last_error = NULL\n FROM unnest($1::bigint[], $2::bigint[], $3::bigint[]) AS u(id, person_id, mapping_ordinal)\n WHERE o.id = u.id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array",
+ "Int8Array",
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "99e6d2d33f5eb2f757a07755ac9b7c9281ac38cd60cb30416438241c710d83e3"
+}
diff --git a/rust/personhog-identity/.sqlx/query-a202e27cea7759424b41d41c013975f8b6a239bd33a49f914c0c972dd6d4858f.json b/rust/personhog-identity/.sqlx/query-a202e27cea7759424b41d41c013975f8b6a239bd33a49f914c0c972dd6d4858f.json
new file mode 100644
index 000000000000..10fd2904790c
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a202e27cea7759424b41d41c013975f8b6a239bd33a49f914c0c972dd6d4858f.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_delete_finished' */ DELETE FROM person_publish_outbox_tmp WHERE id = ANY($1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a202e27cea7759424b41d41c013975f8b6a239bd33a49f914c0c972dd6d4858f"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ab8677b00d150a0a45954f5fe8b23e92ce84e08533cea1e3aaa1de2c55338911.json b/rust/personhog-identity/.sqlx/query-ab8677b00d150a0a45954f5fe8b23e92ce84e08533cea1e3aaa1de2c55338911.json
new file mode 100644
index 000000000000..504cd636fea8
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ab8677b00d150a0a45954f5fe8b23e92ce84e08533cea1e3aaa1de2c55338911.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_defer' */ \n UPDATE person_publish_outbox_tmp o\n SET last_error = u.last_error, attempts = o.attempts + 1\n FROM unnest($1::bigint[], $2::text[]) AS u(id, last_error)\n WHERE o.id = u.id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ab8677b00d150a0a45954f5fe8b23e92ce84e08533cea1e3aaa1de2c55338911"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b2dee7f45988a634973d8eed0fff6fda6324a2b610a3ef23332b8b4aa045cc90.json b/rust/personhog-identity/.sqlx/query-b2dee7f45988a634973d8eed0fff6fda6324a2b610a3ef23332b8b4aa045cc90.json
new file mode 100644
index 000000000000..eda6d7cabdaa
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b2dee7f45988a634973d8eed0fff6fda6324a2b610a3ef23332b8b4aa045cc90.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_resolve_pointer' */ \n WITH moved_rows AS (\n SELECT lop.person_id, lop.role, lop.person_uuid,\n CASE WHEN jsonb_typeof(e.value -> 'distinct_id') = 'string'\n THEN e.value ->> 'distinct_id' END AS distinct_id,\n CASE WHEN jsonb_typeof(e.value -> 'version') = 'number'\n AND (e.value ->> 'version')::numeric = trunc((e.value ->> 'version')::numeric)\n AND (e.value ->> 'version')::numeric BETWEEN -9223372036854775808 AND 9223372036854775807\n THEN (e.value ->> 'version')::bigint END AS version,\n e.ordinality AS mapping_ordinal\n FROM lifecycle_op_person_tmp lop\n CROSS JOIN LATERAL jsonb_array_elements(lop.moved) WITH ORDINALITY AS e(value, ordinality)\n WHERE lop.op_id = $1\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) = 'array'\n AND lop.person_id >= $2\n )\n SELECT m.person_id AS \"person_id!\",\n m.mapping_ordinal AS \"mapping_ordinal!\",\n CASE m.role WHEN 'victim' THEN m.person_uuid ELSE t.person_uuid END AS owner_uuid,\n m.distinct_id,\n m.version,\n (m.role = 'victim') AS \"is_deleted!\"\n FROM moved_rows m\n LEFT JOIN lifecycle_op_person_tmp t ON t.op_id = $1 AND t.role = 'target'\n WHERE (m.person_id, m.mapping_ordinal) > ($2, $3)\n ORDER BY m.person_id, m.mapping_ordinal\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "mapping_ordinal!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "distinct_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "is_deleted!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "b2dee7f45988a634973d8eed0fff6fda6324a2b610a3ef23332b8b4aa045cc90"
+}
diff --git a/rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json b/rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json
new file mode 100644
index 000000000000..2ff774bc398d
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_load_op' */ \n SELECT op.op_type, op.completed_at,\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id AND lop.role = 'target') AS \"target_rows!\",\n (SELECT count(*) FROM lifecycle_op_person lop\n WHERE lop.op_id = op.op_id\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) <> 'array') AS \"malformed_moved_rows!\"\n FROM lifecycle_op op\n WHERE op.op_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "op_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "target_rows!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "malformed_moved_rows!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "b389791503e2ac01778fcd7af7d175067fa7c9fc2f30254df1451203dca2e248"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ce4a22eb1a61cb97207fec2a0c921b4fa8d5a0de7240f68b25a06d39753ebf27.json b/rust/personhog-identity/.sqlx/query-ce4a22eb1a61cb97207fec2a0c921b4fa8d5a0de7240f68b25a06d39753ebf27.json
new file mode 100644
index 000000000000..ef7d63d06da4
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ce4a22eb1a61cb97207fec2a0c921b4fa8d5a0de7240f68b25a06d39753ebf27.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_defer' */ \n UPDATE person_publish_outbox o\n SET last_error = u.last_error, attempts = o.attempts + 1\n FROM unnest($1::bigint[], $2::text[]) AS u(id, last_error)\n WHERE o.id = u.id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8Array",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ce4a22eb1a61cb97207fec2a0c921b4fa8d5a0de7240f68b25a06d39753ebf27"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e5f595569c7aef10aaee453db6295b291b80edc109672927c50e51ae8fd74ec6.json b/rust/personhog-identity/.sqlx/query-e5f595569c7aef10aaee453db6295b291b80edc109672927c50e51ae8fd74ec6.json
new file mode 100644
index 000000000000..dff3f0249104
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e5f595569c7aef10aaee453db6295b291b80edc109672927c50e51ae8fd74ec6.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_resolve_pointer' */ \n WITH moved_rows AS (\n SELECT lop.person_id, lop.role, lop.person_uuid,\n CASE WHEN jsonb_typeof(e.value -> 'distinct_id') = 'string'\n THEN e.value ->> 'distinct_id' END AS distinct_id,\n CASE WHEN jsonb_typeof(e.value -> 'version') = 'number'\n AND (e.value ->> 'version')::numeric = trunc((e.value ->> 'version')::numeric)\n AND (e.value ->> 'version')::numeric BETWEEN -9223372036854775808 AND 9223372036854775807\n THEN (e.value ->> 'version')::bigint END AS version,\n e.ordinality AS mapping_ordinal\n FROM lifecycle_op_person lop\n CROSS JOIN LATERAL jsonb_array_elements(lop.moved) WITH ORDINALITY AS e(value, ordinality)\n WHERE lop.op_id = $1\n AND lop.role IN ('source', 'victim')\n AND lop.moved IS NOT NULL\n AND jsonb_typeof(lop.moved) = 'array'\n AND lop.person_id >= $2\n )\n SELECT m.person_id AS \"person_id!\",\n m.mapping_ordinal AS \"mapping_ordinal!\",\n CASE m.role WHEN 'victim' THEN m.person_uuid ELSE t.person_uuid END AS owner_uuid,\n m.distinct_id,\n m.version,\n (m.role = 'victim') AS \"is_deleted!\"\n FROM moved_rows m\n LEFT JOIN lifecycle_op_person t ON t.op_id = $1 AND t.role = 'target'\n WHERE (m.person_id, m.mapping_ordinal) > ($2, $3)\n ORDER BY m.person_id, m.mapping_ordinal\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "mapping_ordinal!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "distinct_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "is_deleted!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "e5f595569c7aef10aaee453db6295b291b80edc109672927c50e51ae8fd74ec6"
+}
diff --git a/rust/personhog-identity/.sqlx/query-ed9e9456c4a571ad42c17de6f39f6628bae4fe7c30628b314c30792e87aba9a7.json b/rust/personhog-identity/.sqlx/query-ed9e9456c4a571ad42c17de6f39f6628bae4fe7c30628b314c30792e87aba9a7.json
new file mode 100644
index 000000000000..8c85a1f7501b
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-ed9e9456c4a571ad42c17de6f39f6628bae4fe7c30628b314c30792e87aba9a7.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='publish_outbox_counts' */ \n SELECT count(*) FILTER (WHERE given_up_at IS NULL) AS \"pending!\",\n count(*) FILTER (WHERE given_up_at IS NOT NULL) AS \"given_up!\"\n FROM (SELECT given_up_at FROM person_publish_outbox_tmp LIMIT $1) AS scanned\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pending!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "given_up!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "ed9e9456c4a571ad42c17de6f39f6628bae4fe7c30628b314c30792e87aba9a7"
+}
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
index 08a41c7c6670..bd6b600f2bc6 100644
--- a/rust/personhog-identity/Cargo.toml
+++ b/rust/personhog-identity/Cargo.toml
@@ -11,6 +11,7 @@ personhog-proto = { path = "../personhog-proto" }
assignment-coordination = { path = "../common/assignment-coordination" }
common-database = { path = "../common/database" }
common-alloc = { path = "../common/alloc" }
+common-kafka = { path = "../common/kafka" }
common-metrics = { path = "../common/metrics" }
common-sqlx-macros = { path = "../common/sqlx-macros" }
lifecycle = { path = "../common/lifecycle" }
@@ -23,6 +24,7 @@ futures = { workspace = true }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
rand = { workspace = true }
+rdkafka = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
@@ -37,5 +39,12 @@ uuid = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+# Drains the publish outbox identity writes; a second binary of this crate
+# because everything it needs (config, table set, publish module) is the
+# identity lib, and it deploys and scales separately from identity.
+[[bin]]
+name = "personhog-publisher"
+path = "src/bin/publisher.rs"
+
[lints]
workspace = true
diff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.md
index 65e32a9af1bd..4a154dad50bc 100644
--- a/rust/personhog-identity/README.md
+++ b/rust/personhog-identity/README.md
@@ -52,3 +52,16 @@ A lifecycle op parks when the leader answers a semantic refusal after the point
## Delete retries must present a byte-stable request
A same-op-id delete retry is compared byte-for-byte against the frozen request, so the caller must present the identical `person_ids` list (same order, same duplicates) on every retry; a mismatch is refused `op_id_reused` and the deletion must be reissued under a fresh op id.
+
+## Publish outbox contract
+
+`personhog-publisher` (`src/bin/publisher.rs`, `src/publish/`) is a separate deployment that drains the `person_publish_outbox` table identity writes, and nothing orders the two deployments.
+Everything the publisher reads is a contract between the two binaries:
+
+- the outbox columns and the two row shapes the `CHECK` constraints keep exclusive: a mapping row (`create`, `attach`, carrying `person_uuid`, `distinct_id` and `version`) and an op pointer (`merge_op`, `delete_op`, carrying `op_id`, the cursor `cursor_person_id` and `cursor_mapping_ordinal`, `attempts`, `last_error` and `given_up_at`)
+- the `lifecycle_op` row a pointer resolves against (`op_type`, `completed_at`, `outcome`) and the `lifecycle_op_person.moved` array of `{distinct_id, version}` entries on source and victim rows, published in `(person_id, position in moved)` order
+- the lifecycle GC guard, which keeps an op while a pointer to it exists
+
+A change to any of these lands in the publisher first, in its own PR, and in identity (the writer) in a later PR once that publisher is deployed everywhere.
+Until the identity change has rolled out the publisher reads both the old and the new shape, and a column identity stops writing stays in the table while a pending row can still carry it.
+The schema change itself is a third PR ahead of both, as the migrations check requires.
diff --git a/rust/personhog-identity/src/bin/publisher.rs b/rust/personhog-identity/src/bin/publisher.rs
new file mode 100644
index 000000000000..76d8ae716096
--- /dev/null
+++ b/rust/personhog-identity/src/bin/publisher.rs
@@ -0,0 +1,148 @@
+//! `personhog-publisher`: drains the publish outbox that personhog-identity
+//! writes and produces the ClickHouse distinct id feed. A separate
+//! deployment because publish load follows the create rate and merge sizes
+//! while identity load follows RPC traffic, and because a Kafka outage must
+//! hold this process's connections, not identity's.
+
+use std::time::Duration;
+
+use axum::{routing::get, Router};
+use common_database::get_pool_with_config;
+use common_kafka::kafka_producer::{create_kafka_producer, spawn_bounded_flush_on_shutdown};
+use common_metrics::setup_metrics_routes;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Manager};
+use tracing::level_filters::LevelFilter;
+use tracing_subscriber::fmt;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::EnvFilter;
+
+use personhog_identity::publish::config::PublisherConfig;
+use personhog_identity::publish::sink::KafkaSink;
+use personhog_identity::publish::Publisher;
+
+common_alloc::used!();
+
+/// Headroom past the longest pass, so shutdown waits for an in-flight
+/// claim to commit or roll back before the producer flushes. The two
+/// phases add up to under the 30 s Kubernetes default termination grace
+/// period at the default timeouts.
+const SHUTDOWN_MARGIN: Duration = Duration::from_secs(2);
+const PRODUCER_FLUSH_BOUND: Duration = Duration::from_secs(10);
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let config = PublisherConfig::init_from_env().expect("Invalid configuration");
+
+ tracing_subscriber::registry()
+ .with(
+ fmt::layer()
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_level(true),
+ )
+ .with(
+ EnvFilter::builder()
+ .with_default_directive(LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .init();
+
+ let tables = config.tables();
+ tables.validate().expect("Invalid identity table set");
+ let drain_config = config.drain_config();
+
+ tracing::info!("Starting personhog-publisher");
+ tracing::info!("Metrics port: {}", config.metrics_port);
+ tracing::info!("Tables: {:?}", tables);
+ tracing::info!(
+ distinct_id_topic = %config.person_distinct_id_topic,
+ batch_size = drain_config.batch_size,
+ max_rows_per_pass = drain_config.max_rows_per_pass,
+ interval_ms = drain_config.interval.as_millis() as u64,
+ produce_timeout_ms = config.produce_timeout().as_millis() as u64,
+ "Publish settings"
+ );
+ if tables.is_validation() {
+ tracing::warn!(
+ outbox = %tables.person_publish_outbox,
+ distinct_id_topic = %config.person_distinct_id_topic,
+ "Publisher runs on the validation table set; its topics must be capture topics, never the production names"
+ );
+ }
+
+ let mut manager = Manager::builder("personhog-publisher").build();
+ let publisher_handle = manager.register(
+ "publisher",
+ ComponentOptions::new().with_graceful_shutdown(config.pass_deadline() + SHUTDOWN_MARGIN),
+ );
+ // Phase 1: the producer flushes only after the drain loop has stopped,
+ // so the last pass's records are in the queue it flushes.
+ let kafka_handle = manager.register(
+ "kafka-producer",
+ ComponentOptions::new()
+ .with_graceful_shutdown(PRODUCER_FLUSH_BOUND + SHUTDOWN_MARGIN)
+ .with_shutdown_phase(1),
+ );
+ let metrics_handle = manager.register(
+ "metrics-server",
+ ComponentOptions::new().is_observability(true),
+ );
+ let readiness = manager.readiness_handler();
+ let liveness = manager.liveness_handler();
+ let monitor = manager.monitor_background();
+
+ // Built before anything records a metric: this call installs the
+ // process-wide recorder.
+ let metrics_router = setup_metrics_routes(
+ Router::new()
+ .route(
+ "/_readiness",
+ get(move || {
+ let r = readiness.clone();
+ async move { r.check().await }
+ }),
+ )
+ .route("/_liveness", get(move || async move { liveness.check() })),
+ );
+ let metrics_port = config.metrics_port;
+ tokio::spawn(async move {
+ let _guard = metrics_handle.process_scope();
+ let bind = format!("0.0.0.0:{metrics_port}");
+ let listener = tokio::net::TcpListener::bind(&bind)
+ .await
+ .expect("Failed to bind metrics port");
+ tracing::info!("Metrics server listening on {}", bind);
+ axum::serve(listener, metrics_router)
+ .with_graceful_shutdown(metrics_handle.shutdown_signal())
+ .await
+ .expect("Metrics server error");
+ });
+
+ let pool = get_pool_with_config(&config.primary_database_url, config.pool_config())
+ .expect("Failed to create database pool");
+
+ let producer = match create_kafka_producer(&config.kafka, kafka_handle.clone()).await {
+ Ok(producer) => producer,
+ Err(e) => {
+ tracing::error!(error = %e, "failed to create Kafka producer");
+ return Err(e.into());
+ }
+ };
+ spawn_bounded_flush_on_shutdown(producer.clone(), kafka_handle, PRODUCER_FLUSH_BOUND);
+
+ let sink = KafkaSink::new(
+ producer,
+ config.person_distinct_id_topic.clone(),
+ config.produce_timeout(),
+ );
+ let publisher = Publisher::new(pool, tables, sink, drain_config);
+ tokio::spawn(async move {
+ let _guard = publisher_handle.process_scope();
+ publisher.run(&publisher_handle).await;
+ });
+
+ monitor.wait().await?;
+ Ok(())
+}
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 5e9b11ac232b..662a8987f4df 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -16,36 +16,8 @@ pub struct Config {
#[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
pub primary_database_url: String,
- /// Person table every identity query reads and writes (stub creation,
- /// resolution, and the delete saga's person mutations). Must pair with
- /// the leader's FALLBACK_TABLE and the writer's PG_TARGET_TABLE so the
- /// three services agree on where person rows live. Defaults to the
- /// validation table, matching the writer; set to "posthog_person" at
- /// production cutover — and flip all three services together.
- #[envconfig(default = "personhog_person_tmp")]
- pub person_table: String,
-
- /// Distinct id table paired with PERSON_TABLE. Person ids come from the
- /// person table's own sequence, so the mapping must live in the same
- /// namespace (and posthog_persondistinctid's FK rejects ids that are not
- /// in posthog_person). Set to "posthog_persondistinctid" at cutover.
- #[envconfig(default = "personhog_persondistinctid_tmp")]
- pub person_distinct_id_table: String,
-
- /// Feature-flag hash-key-override table the delete saga clears by
- /// person_id — same namespace rule as the distinct id table. Set to
- /// "posthog_featureflaghashkeyoverride" at cutover.
- #[envconfig(default = "personhog_featureflaghashkeyoverride_tmp")]
- pub ff_hash_key_override_table: String,
-
- /// 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(nested = true)]
+ pub tables: IdentityTablesConfig,
/// Fast pool (see `crate::pools`).
#[envconfig(default = "10")]
@@ -224,19 +196,70 @@ 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
+ /// retention, so turn this on only where a publisher runs against the
+ /// same table set.
+ #[envconfig(default = "false")]
+ pub lifecycle_outbox_enabled: bool,
+}
+
+/// The six table variables identity and the publisher both read. One
+/// struct, nested in both configs, so the names and defaults cannot drift
+/// between the deployment that writes the outbox and the one that drains it.
+#[derive(Envconfig, Clone, Debug)]
+pub struct IdentityTablesConfig {
+ /// Person table every identity query reads and writes (stub creation,
+ /// resolution, and the delete saga's person mutations). Must pair with
+ /// the leader's FALLBACK_TABLE and the writer's PG_TARGET_TABLE so the
+ /// three services agree on where person rows live. Defaults to the
+ /// validation table, matching the writer; set to "posthog_person" at
+ /// production cutover — and flip all three services together.
+ #[envconfig(default = "personhog_person_tmp")]
+ pub person_table: String,
+
+ /// Distinct id table paired with PERSON_TABLE. Person ids come from the
+ /// person table's own sequence, so the mapping must live in the same
+ /// namespace (and posthog_persondistinctid's FK rejects ids that are not
+ /// in posthog_person). Set to "posthog_persondistinctid" at cutover.
+ #[envconfig(default = "personhog_persondistinctid_tmp")]
+ pub person_distinct_id_table: String,
+
+ /// Feature-flag hash-key-override table the delete saga clears by
+ /// person_id — same namespace rule as the distinct id table. Set to
+ /// "posthog_featureflaghashkeyoverride" at cutover.
+ #[envconfig(default = "personhog_featureflaghashkeyoverride_tmp")]
+ pub ff_hash_key_override_table: String,
+
+ /// 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,
+
/// 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,
+impl IdentityTablesConfig {
+ pub fn tables(&self) -> IdentityTables {
+ IdentityTables {
+ person: self.person_table.clone(),
+ person_distinct_id: self.person_distinct_id_table.clone(),
+ ff_hash_key_override: self.ff_hash_key_override_table.clone(),
+ 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(),
+ }
+ }
}
/// Whether identity writes the publish outbox (`LIFECYCLE_OUTBOX_ENABLED`):
@@ -312,14 +335,7 @@ impl IdentityTables {
impl Config {
pub fn tables(&self) -> IdentityTables {
- IdentityTables {
- person: self.person_table.clone(),
- person_distinct_id: self.person_distinct_id_table.clone(),
- ff_hash_key_override: self.ff_hash_key_override_table.clone(),
- 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(),
- }
+ self.tables.tables()
}
pub fn outbox_writes(&self) -> OutboxWrites {
diff --git a/rust/personhog-identity/src/lib.rs b/rust/personhog-identity/src/lib.rs
index 30a9c9601098..9a8be18e8e1a 100644
--- a/rust/personhog-identity/src/lib.rs
+++ b/rust/personhog-identity/src/lib.rs
@@ -2,5 +2,6 @@ pub mod config;
pub mod leader;
pub mod lifecycle;
pub mod pools;
+pub mod publish;
pub mod service;
pub mod storage;
diff --git a/rust/personhog-identity/src/publish/claim.rs b/rust/personhog-identity/src/publish/claim.rs
new file mode 100644
index 000000000000..3c5301a6a266
--- /dev/null
+++ b/rust/personhog-identity/src/publish/claim.rs
@@ -0,0 +1,67 @@
+use chrono::{DateTime, Utc};
+use personhog_common::query_tag;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+use crate::config::IdentityTables;
+use crate::lifecycle::engine::Tx;
+
+pub const KIND_CREATE: &str = "create";
+pub const KIND_ATTACH: &str = "attach";
+pub const KIND_MERGE_OP: &str = "merge_op";
+pub const KIND_DELETE_OP: &str = "delete_op";
+
+/// One claimed outbox row. A mapping row carries `person_uuid`,
+/// `distinct_id` and `version`; a pointer carries `op_id` and its cursor.
+/// The CHECK constraint on the table keeps the two shapes exclusive.
+#[derive(Debug, Clone, FromRow)]
+pub struct ClaimedRow {
+ pub id: i64,
+ pub team_id: i32,
+ pub kind: String,
+ pub person_uuid: Option<Uuid>,
+ pub distinct_id: Option<String>,
+ pub version: Option<i64>,
+ pub op_id: Option<Uuid>,
+ pub cursor_person_id: i64,
+ pub cursor_mapping_ordinal: i64,
+ pub attempts: i32,
+ pub created_at: DateTime<Utc>,
+}
+
+impl ClaimedRow {
+ pub fn is_pointer(&self) -> bool {
+ self.op_id.is_some()
+ }
+}
+
+/// Built from a format string instead of the mirrored sqlx macros so the
+/// plan test can EXPLAIN the statement the drain really runs. The table
+/// name is one of the two validated sets, never user input.
+pub fn claim_sql(outbox: &str) -> String {
+ format!(
+ r#"
+ SELECT id, team_id, kind, person_uuid, distinct_id, version, op_id,
+ cursor_person_id, cursor_mapping_ordinal, attempts, created_at
+ FROM {outbox}
+ WHERE given_up_at IS NULL
+ ORDER BY id
+ LIMIT $1
+ FOR UPDATE SKIP LOCKED
+ "#
+ )
+}
+
+pub async fn claim(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ limit: i64,
+) -> Result<Vec<ClaimedRow>, sqlx::Error> {
+ sqlx::query_as(&query_tag!(
+ "publish_claim",
+ claim_sql(&tables.person_publish_outbox)
+ ))
+ .bind(limit)
+ .fetch_all(&mut **tx)
+ .await
+}
diff --git a/rust/personhog-identity/src/publish/config.rs b/rust/personhog-identity/src/publish/config.rs
new file mode 100644
index 000000000000..5c0001450a4b
--- /dev/null
+++ b/rust/personhog-identity/src/publish/config.rs
@@ -0,0 +1,117 @@
+use std::time::Duration;
+
+use common_database::PoolConfig;
+use common_kafka::config::KafkaConfig;
+use envconfig::Envconfig;
+
+use crate::config::{IdentityTables, IdentityTablesConfig};
+use crate::publish::DrainConfig;
+
+#[derive(Envconfig, Clone)]
+pub struct PublisherConfig {
+ /// The persons primary identity writes to; the outbox lives there.
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
+ pub primary_database_url: String,
+
+ #[envconfig(nested = true)]
+ pub tables: IdentityTablesConfig,
+
+ /// One pool: a replica holds one claim transaction at a time plus the
+ /// gauge query, so a small pool is a ceiling, not a target.
+ #[envconfig(default = "4")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub acquire_timeout_secs: u64,
+
+ /// Bounds any one statement of the claim transaction, so a stuck
+ /// resolution cannot hold the claimed rows past the produce timeout
+ /// by much.
+ #[envconfig(default = "5000")]
+ pub statement_timeout_ms: u64,
+
+ #[envconfig(default = "300")]
+ pub idle_timeout_secs: u64,
+
+ #[envconfig(default = "9109")]
+ pub metrics_port: u16,
+
+ /// Idle poll between passes; a pass that claims a full batch loops
+ /// again at once.
+ #[envconfig(default = "200")]
+ pub lifecycle_publish_interval_ms: u64,
+
+ #[envconfig(default = "1000")]
+ pub lifecycle_publish_batch_size: i64,
+
+ /// Distinct id rows one pass produces at most, across every row it
+ /// claimed. A large merge or delete drains across several passes, each
+ /// advancing its pointer's cursor, so no transaction stays open across
+ /// more produces than the produce timeout can carry.
+ #[envconfig(default = "10000")]
+ pub lifecycle_publish_max_rows_per_pass: i64,
+
+ /// How long one claim waits for Kafka acks before it rolls back and
+ /// retries. Keep it well under the database's
+ /// idle_in_transaction_session_timeout.
+ #[envconfig(default = "5000")]
+ pub lifecycle_publish_produce_timeout_ms: u64,
+
+ /// Lag above which the gauge refresh logs a warning. The page itself
+ /// lives in Grafana on the lag gauge.
+ #[envconfig(default = "300")]
+ pub lifecycle_publish_lag_alert_secs: u64,
+
+ /// No default on purpose. The table set defaults to the validation
+ /// tables, whose versions come from a different sequence than the real
+ /// tables and would win in ClickHouse, so a deployment must say which
+ /// topic it feeds: `clickhouse_person_distinct_id` only behind the real
+ /// tables, a capture topic behind the validation set.
+ pub person_distinct_id_topic: String,
+
+ #[envconfig(nested = true)]
+ pub kafka: KafkaConfig,
+}
+
+impl PublisherConfig {
+ pub fn tables(&self) -> IdentityTables {
+ self.tables.tables()
+ }
+
+ pub fn pool_config(&self) -> PoolConfig {
+ PoolConfig {
+ min_connections: 0,
+ max_connections: self.max_pg_connections,
+ acquire_timeout: Duration::from_secs(self.acquire_timeout_secs),
+ idle_timeout: (self.idle_timeout_secs != 0)
+ .then(|| Duration::from_secs(self.idle_timeout_secs)),
+ test_before_acquire: false,
+ statement_timeout_ms: (self.statement_timeout_ms != 0)
+ .then_some(self.statement_timeout_ms),
+ pool_name: Some("publisher".to_string()),
+ }
+ }
+
+ pub fn drain_config(&self) -> DrainConfig {
+ DrainConfig {
+ batch_size: self.lifecycle_publish_batch_size,
+ max_rows_per_pass: self.lifecycle_publish_max_rows_per_pass,
+ interval: Duration::from_millis(self.lifecycle_publish_interval_ms),
+ lag_alert: Duration::from_secs(self.lifecycle_publish_lag_alert_secs),
+ }
+ }
+
+ pub fn produce_timeout(&self) -> Duration {
+ Duration::from_millis(self.lifecycle_publish_produce_timeout_ms)
+ }
+
+ /// How long a pass usually takes at most: one produce wait plus one
+ /// slow statement. The publisher component's graceful shutdown covers
+ /// it so an in-flight claim normally commits or rolls back cleanly. It
+ /// is not a hard bound: a pass with many pointers runs two statements
+ /// per pointer, and a pass torn down past the window only rolls back,
+ /// because nothing commits before the acks.
+ pub fn pass_deadline(&self) -> Duration {
+ self.produce_timeout() + Duration::from_millis(self.statement_timeout_ms)
+ }
+}
diff --git a/rust/personhog-identity/src/publish/messages.rs b/rust/personhog-identity/src/publish/messages.rs
new file mode 100644
index 000000000000..8bcc1a283c68
--- /dev/null
+++ b/rust/personhog-identity/src/publish/messages.rs
@@ -0,0 +1,42 @@
+//! Wire payloads the publisher produces. Field names and types are the
+//! Node ingestion worker's, byte for byte: the ClickHouse Kafka engine
+//! table, `flags-consumer` and the hogflow subscription matcher all decode
+//! the same topic whichever path produced the row.
+
+use serde::Serialize;
+use uuid::Uuid;
+
+/// One `clickhouse_person_distinct_id` row. `person_id` is the owning
+/// person's uuid (ClickHouse never sees Postgres person ids), and
+/// `is_deleted` is a 0 or 1 integer rather than a boolean because the Kafka
+/// table column is `Int8`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct DistinctIdRow {
+ pub person_id: Uuid,
+ pub team_id: i64,
+ pub distinct_id: String,
+ pub version: i64,
+ pub is_deleted: u8,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // The consumers decode by field name; a rename or a boolean `is_deleted`
+ // would be dropped by the ClickHouse Kafka table without an error.
+ #[test]
+ fn distinct_id_row_serializes_exactly_as_the_node_producer_does() {
+ let row = DistinctIdRow {
+ person_id: Uuid::parse_str("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee").unwrap(),
+ team_id: 2,
+ distinct_id: "user-1".to_string(),
+ version: 3,
+ is_deleted: 1,
+ };
+ assert_eq!(
+ serde_json::to_string(&row).unwrap(),
+ r#"{"person_id":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","team_id":2,"distinct_id":"user-1","version":3,"is_deleted":1}"#
+ );
+ }
+}
diff --git a/rust/personhog-identity/src/publish/mod.rs b/rust/personhog-identity/src/publish/mod.rs
new file mode 100644
index 000000000000..e1b7508d449a
--- /dev/null
+++ b/rust/personhog-identity/src/publish/mod.rs
@@ -0,0 +1,482 @@
+//! The publish phase. The outbox carries two row shapes: a mapping row
+//! (kinds `create` and `attach`) that publishes as it is, and an op pointer
+//! (kinds `merge_op` and `delete_op`) that resolves against the saga's
+//! `moved` records. Identity enqueues pointers in
+//! [`crate::lifecycle::engine::complete_op_in_tx`]; this module drains the
+//! outbox to Kafka from the separate `personhog-publisher` binary.
+//!
+//! One pass is one transaction: claim the oldest pending rows with `FOR
+//! UPDATE SKIP LOCKED`, resolve pointers against `moved` within a per-pass
+//! row budget, produce, await every ack, then delete finished rows, advance
+//! unfinished pointers, defer rows that cannot be read, and commit. A
+//! produce error rolls the whole pass back, so the only failure mode is a
+//! repeat publish, which every consumer of these topics absorbs by version.
+//! A row the publisher cannot read (an op row that is gone, a `moved` entry
+//! the saga could not have written) stays pending with `last_error` and a
+//! raised `attempts`: the rest of its batch publishes, the row is retried
+//! on every pass and publishes on its own once the state is repaired, and
+//! the lag gauge reports it meanwhile. The publisher never parks a row;
+//! `given_up_at` is an operator's switch to take a row out of the claim.
+//! Kafka failures retry forever with backoff.
+
+pub mod claim;
+pub mod config;
+pub mod messages;
+pub mod pointer;
+pub mod sink;
+
+use std::time::{Duration, Instant};
+
+use common_sqlx_macros::mirrored_query;
+use lifecycle::Handle;
+use sqlx::PgPool;
+
+use crate::config::IdentityTables;
+use crate::lifecycle::engine::Tx;
+use crate::publish::claim::{claim, ClaimedRow};
+use crate::publish::messages::DistinctIdRow;
+use crate::publish::pointer::{load_op, outbox_depth, resolve_chunk, Cursor};
+use crate::publish::sink::{PublishBatch, PublishError, PublishSink};
+
+const PUBLISH_ROWS_TOTAL: &str = "personhog_lifecycle_publish_rows_total";
+const PUBLISH_FAILURES_TOTAL: &str = "personhog_lifecycle_publish_failures_total";
+const PUBLISH_BATCH_DURATION_MS: &str = "personhog_lifecycle_publish_batch_duration_ms";
+const PUBLISH_BACKLOG: &str = "personhog_lifecycle_publish_backlog";
+const PUBLISH_LAG_SECONDS: &str = "personhog_lifecycle_publish_lag_seconds";
+/// Rows an operator parked with `given_up_at`; the publisher never sets it.
+const PUBLISH_GIVEN_UP: &str = "personhog_lifecycle_publish_given_up";
+
+/// The gauges read the whole outbox, so they refresh on their own clock
+/// rather than once per pass.
+const GAUGE_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
+const MAX_BACKOFF: Duration = Duration::from_secs(30);
+
+#[derive(Clone, Debug)]
+pub struct DrainConfig {
+ pub batch_size: i64,
+ /// Distinct id rows one pass produces at most. A pointer's chunk is
+ /// bounded by what is left of it, so a pass of large ops stays inside
+ /// the produce timeout instead of failing the same way forever.
+ pub max_rows_per_pass: i64,
+ pub interval: Duration,
+ pub lag_alert: Duration,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum DrainError {
+ #[error("database error: {0}")]
+ Db(#[from] sqlx::Error),
+ #[error(transparent)]
+ Publish(#[from] PublishError),
+}
+
+impl DrainError {
+ fn reason(&self) -> &'static str {
+ match self {
+ DrainError::Db(_) => "db",
+ DrainError::Publish(PublishError::Kafka(_)) => "kafka",
+ DrainError::Publish(PublishError::Timeout(_)) => "kafka_timeout",
+ }
+ }
+}
+
+/// What one pass did. More work is waiting when the claim was full or the
+/// row budget stopped the pass before every claimed row was handled.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct PassReport {
+ pub claimed: usize,
+ pub finished: usize,
+ pub advanced: usize,
+ pub deferred: usize,
+ /// Claimed rows left untouched because the row budget ran out; they
+ /// stay pending with their cursors for the next pass.
+ pub unprocessed: usize,
+ pub messages: usize,
+}
+
+enum Disposition {
+ /// Published in full: the row is deleted.
+ Finished,
+ /// A pointer with rows left after this chunk: the cursor moves.
+ Advanced(Cursor),
+ /// State the saga could not have written: the row stays pending with
+ /// the reason and is retried on every pass, so it publishes on its own
+ /// once repaired and an operator can see why until then.
+ Deferred(String),
+}
+
+pub struct Publisher<S> {
+ pool: PgPool,
+ tables: IdentityTables,
+ sink: S,
+ config: DrainConfig,
+}
+
+impl<S: PublishSink> Publisher<S> {
+ pub fn new(pool: PgPool, tables: IdentityTables, sink: S, config: DrainConfig) -> Self {
+ tables.validate().expect("invalid identity table set");
+ assert!(config.batch_size > 0, "batch_size must be > 0");
+ assert!(
+ config.max_rows_per_pass > 0,
+ "max_rows_per_pass must be > 0"
+ );
+ Self {
+ pool,
+ tables,
+ sink,
+ config,
+ }
+ }
+
+ /// The drain loop, until `handle` shuts down. An in-flight pass runs
+ /// to its end first: it is bounded by the produce timeout, the
+ /// statement timeout and the row budget, and tearing it down
+ /// mid-transaction would only trade a clean rollback for an abandoned
+ /// connection.
+ pub async fn run(&self, handle: &Handle) {
+ let mut delay = Duration::ZERO;
+ let mut backoff = self.config.interval;
+ let mut gauges_refreshed_at: Option<Instant> = None;
+ loop {
+ // Biased, so a shutdown that arrives during a backlog (delay
+ // zero, both branches ready) wins over starting another pass.
+ tokio::select! {
+ biased;
+ _ = handle.shutdown_recv() => break,
+ _ = tokio::time::sleep(delay) => {}
+ }
+ if gauges_refreshed_at.is_none_or(|at| at.elapsed() >= GAUGE_REFRESH_INTERVAL) {
+ self.refresh_gauges().await;
+ gauges_refreshed_at = Some(Instant::now());
+ }
+ match self.drain_once().await {
+ Ok(report) => {
+ if report.claimed > 0 {
+ tracing::debug!(
+ claimed = report.claimed,
+ finished = report.finished,
+ advanced = report.advanced,
+ deferred = report.deferred,
+ unprocessed = report.unprocessed,
+ messages = report.messages,
+ "publish pass"
+ );
+ }
+ backoff = self.config.interval;
+ let more_waiting =
+ report.claimed as i64 >= self.config.batch_size || report.unprocessed > 0;
+ delay = if more_waiting {
+ Duration::ZERO
+ } else {
+ self.config.interval
+ };
+ }
+ Err(err) => {
+ common_metrics::inc(
+ PUBLISH_FAILURES_TOTAL,
+ &[("reason".to_string(), err.reason().to_string())],
+ 1,
+ );
+ tracing::warn!(
+ error = %err,
+ backoff_ms = backoff.as_millis() as u64,
+ "publish pass failed; its rows stay claimed by nobody until the retry"
+ );
+ delay = backoff;
+ backoff = (backoff * 2).min(MAX_BACKOFF);
+ }
+ }
+ }
+ }
+
+ /// One claim transaction. Nothing is awaited inside it except the
+ /// outbox statements and the sink.
+ pub async fn drain_once(&self) -> Result<PassReport, DrainError> {
+ let start = Instant::now();
+ let mut tx = self.pool.begin().await?;
+ let rows = claim(&mut tx, &self.tables, self.config.batch_size).await?;
+ if rows.is_empty() {
+ tx.rollback().await?;
+ return Ok(PassReport::default());
+ }
+
+ let mut batch = PublishBatch::default();
+ let mut dispositions: Vec<(&ClaimedRow, Disposition)> = Vec::with_capacity(rows.len());
+ let mut remaining = self.config.max_rows_per_pass;
+ for row in &rows {
+ if remaining <= 0 {
+ break;
+ }
+ let before = batch.distinct_id_rows.len();
+ let disposition = if row.is_pointer() {
+ self.resolve_pointer(&mut tx, row, &mut batch, remaining)
+ .await
+ .inspect_err(|e| {
+ // The failing row is the head of the queue until it
+ // is repaired, so name it.
+ tracing::warn!(
+ outbox_id = row.id,
+ op_id = ?row.op_id,
+ error = %e,
+ "resolving a publish pointer failed; the pass rolls back"
+ );
+ })?
+ } else {
+ batch.distinct_id_rows.push(mapping_row(row)?);
+ Disposition::Finished
+ };
+ remaining -= (batch.distinct_id_rows.len() - before) as i64;
+ dispositions.push((row, disposition));
+ }
+ let unprocessed = rows.len() - dispositions.len();
+
+ // A failure here drops `tx`, which rolls the claim back: every row
+ // stays pending with its cursor untouched.
+ self.sink.send(&batch).await?;
+
+ let mut finished: Vec<i64> = Vec::new();
+ let mut advanced: (Vec<i64>, Vec<i64>, Vec<i64>) = Default::default();
+ let mut deferred: (Vec<i64>, Vec<String>) = Default::default();
+ for (row, disposition) in &dispositions {
+ match disposition {
+ Disposition::Finished => finished.push(row.id),
+ Disposition::Advanced(cursor) => {
+ advanced.0.push(row.id);
+ advanced.1.push(cursor.person_id);
+ advanced.2.push(cursor.mapping_ordinal);
+ }
+ Disposition::Deferred(reason) => {
+ // The row is claimed on every pass, so log the first
+ // deferral and then every 300th.
+ if row.attempts % 300 == 0 {
+ tracing::error!(
+ outbox_id = row.id,
+ kind = %row.kind,
+ op_id = ?row.op_id,
+ attempts = row.attempts + 1,
+ reason = %reason,
+ "publish outbox row cannot be read; it stays pending until the state is repaired"
+ );
+ }
+ deferred.0.push(row.id);
+ deferred.1.push(reason.clone());
+ }
+ }
+ }
+ self.write_back(&mut tx, &finished, &advanced, &deferred)
+ .await?;
+ tx.commit().await?;
+
+ // Counted after the commit, so a pass that rolls back counts nothing.
+ for (row, disposition) in &dispositions {
+ let result = match disposition {
+ Disposition::Finished => "published",
+ Disposition::Deferred(_) => "deferred",
+ Disposition::Advanced(_) => continue,
+ };
+ record_row(&row.kind, result);
+ }
+ common_metrics::histogram(
+ PUBLISH_BATCH_DURATION_MS,
+ &[],
+ start.elapsed().as_secs_f64() * 1000.0,
+ );
+ Ok(PassReport {
+ claimed: rows.len(),
+ finished: finished.len(),
+ advanced: advanced.0.len(),
+ deferred: deferred.0.len(),
+ unprocessed,
+ messages: batch.distinct_id_rows.len(),
+ })
+ }
+
+ /// Resolve one pointer's next chunk, at most `limit` rows, into
+ /// `batch`. Rows are added only once the whole chunk decodes, so a
+ /// poisoned pointer contributes nothing to the batch it is deferred in.
+ async fn resolve_pointer(
+ &self,
+ tx: &mut Tx<'_>,
+ row: &ClaimedRow,
+ batch: &mut PublishBatch,
+ limit: i64,
+ ) -> Result<Disposition, sqlx::Error> {
+ let op_id = row.op_id.expect("pointer rows carry an op_id");
+ let Some(op) = load_op(tx, &self.tables, op_id).await? else {
+ return Ok(Disposition::Deferred(format!(
+ "op {op_id} no longer exists; its moved rows cannot be published"
+ )));
+ };
+ // Pointers are written only by a completed op's own commit, so any
+ // of these is corrupt state rather than a case to handle.
+ if op.completed_at.is_none() {
+ return Ok(Disposition::Deferred(format!(
+ "op {op_id} is not completed"
+ )));
+ }
+ if format!("{}_op", op.op_type) != row.kind {
+ return Ok(Disposition::Deferred(format!(
+ "op {op_id} is a {} op but the pointer kind is {}",
+ op.op_type, row.kind
+ )));
+ }
+ if op.op_type == "merge" && op.target_rows != 1 {
+ return Ok(Disposition::Deferred(format!(
+ "merge op {op_id} has {} target rows",
+ op.target_rows
+ )));
+ }
+ if op.malformed_moved_rows > 0 {
+ return Ok(Disposition::Deferred(format!(
+ "op {op_id} has {} source or victim rows whose moved is not an array",
+ op.malformed_moved_rows
+ )));
+ }
+ let cursor = Cursor {
+ person_id: row.cursor_person_id,
+ mapping_ordinal: row.cursor_mapping_ordinal,
+ };
+ let chunk = resolve_chunk(tx, &self.tables, op_id, cursor, limit).await?;
+
+ let mut rows = Vec::with_capacity(chunk.len());
+ for resolved in &chunk {
+ let (Some(owner), Some(distinct_id), Some(version)) = (
+ resolved.owner_uuid,
+ resolved.distinct_id.as_ref(),
+ resolved.version,
+ ) else {
+ return Ok(Disposition::Deferred(format!(
+ "op {op_id} person {} moved entry {} is malformed (owner {:?}, distinct_id {:?}, version {:?})",
+ resolved.person_id,
+ resolved.mapping_ordinal,
+ resolved.owner_uuid,
+ resolved.distinct_id,
+ resolved.version
+ )));
+ };
+ rows.push(DistinctIdRow {
+ person_id: owner,
+ team_id: row.team_id as i64,
+ distinct_id: distinct_id.clone(),
+ version,
+ is_deleted: u8::from(resolved.is_deleted),
+ });
+ }
+ batch.distinct_id_rows.extend(rows);
+
+ // A chunk shorter than the limit it was asked for is the last one.
+ // A chunk exactly at the limit may also be the last, which costs
+ // one more pass that finds nothing; cheaper than probing past the
+ // limit on every chunk.
+ Ok(match chunk.last() {
+ Some(last) if chunk.len() as i64 >= limit => Disposition::Advanced(last.cursor()),
+ _ => Disposition::Finished,
+ })
+ }
+
+ async fn write_back(
+ &self,
+ tx: &mut Tx<'_>,
+ finished: &[i64],
+ advanced: &(Vec<i64>, Vec<i64>, Vec<i64>),
+ deferred: &(Vec<i64>, Vec<String>),
+ ) -> Result<(), sqlx::Error> {
+ if !finished.is_empty() {
+ mirrored_query!(
+ self.tables.is_validation(),
+ op = "publish_delete_finished",
+ "DELETE FROM {person_publish_outbox} WHERE id = ANY($1)",
+ finished
+ => execute(&mut **tx)
+ )?;
+ }
+ if !advanced.0.is_empty() {
+ mirrored_query!(
+ self.tables.is_validation(),
+ op = "publish_advance_cursors",
+ r#"
+ UPDATE {person_publish_outbox} o
+ SET cursor_person_id = u.person_id,
+ cursor_mapping_ordinal = u.mapping_ordinal,
+ attempts = o.attempts + 1,
+ last_error = NULL
+ FROM unnest($1::bigint[], $2::bigint[], $3::bigint[]) AS u(id, person_id, mapping_ordinal)
+ WHERE o.id = u.id
+ "#,
+ &advanced.0,
+ &advanced.1,
+ &advanced.2
+ => execute(&mut **tx)
+ )?;
+ }
+ if !deferred.0.is_empty() {
+ mirrored_query!(
+ self.tables.is_validation(),
+ op = "publish_defer",
+ r#"
+ UPDATE {person_publish_outbox} o
+ SET last_error = u.last_error, attempts = o.attempts + 1
+ FROM unnest($1::bigint[], $2::text[]) AS u(id, last_error)
+ WHERE o.id = u.id
+ "#,
+ &deferred.0,
+ &deferred.1
+ => execute(&mut **tx)
+ )?;
+ }
+ Ok(())
+ }
+
+ async fn refresh_gauges(&self) {
+ match outbox_depth(&self.pool, &self.tables).await {
+ Ok(depth) => {
+ common_metrics::gauge(PUBLISH_BACKLOG, &[], depth.pending as f64);
+ common_metrics::gauge(PUBLISH_GIVEN_UP, &[], depth.given_up as f64);
+ common_metrics::gauge(PUBLISH_LAG_SECONDS, &[], depth.lag_seconds);
+ if depth.lag_seconds > self.config.lag_alert.as_secs_f64() {
+ tracing::warn!(
+ lag_seconds = depth.lag_seconds,
+ backlog = depth.pending,
+ "publish lag is above the alert threshold"
+ );
+ }
+ }
+ Err(e) => tracing::warn!(error = %e, "failed to refresh the publish outbox gauges"),
+ }
+ }
+}
+
+/// A create or attach row carries its message inline. The CHECK constraint
+/// makes the three columns non-null for these kinds, so a null is a schema
+/// change the code has not followed.
+fn mapping_row(row: &ClaimedRow) -> Result<DistinctIdRow, sqlx::Error> {
+ let (Some(person_uuid), Some(distinct_id), Some(version)) =
+ (row.person_uuid, row.distinct_id.as_ref(), row.version)
+ else {
+ return Err(sqlx::Error::Decode(
+ format!(
+ "outbox row {} of kind {} lacks a mapping column",
+ row.id, row.kind
+ )
+ .into(),
+ ));
+ };
+ Ok(DistinctIdRow {
+ person_id: person_uuid,
+ team_id: row.team_id as i64,
+ distinct_id: distinct_id.clone(),
+ version,
+ is_deleted: 0,
+ })
+}
+
+fn record_row(kind: &str, result: &str) {
+ common_metrics::inc(
+ PUBLISH_ROWS_TOTAL,
+ &[
+ ("kind".to_string(), kind.to_string()),
+ ("result".to_string(), result.to_string()),
+ ],
+ 1,
+ );
+}
diff --git a/rust/personhog-identity/src/publish/pointer.rs b/rust/personhog-identity/src/publish/pointer.rs
new file mode 100644
index 000000000000..a3332d83e109
--- /dev/null
+++ b/rust/personhog-identity/src/publish/pointer.rs
@@ -0,0 +1,210 @@
+//! Resolving an op pointer against the saga's own records. A merge or
+//! delete op records every repointed or tombstoned mapping in
+//! `lifecycle_op_person.moved` in the same commit that moved it, so the
+//! pointer carries nothing but the op id and a keyset cursor over those
+//! records.
+//!
+//! Only `source` (merge) and `victim` (delete) rows hold mappings. A merge
+//! target's `moved` holds the per-distinct-id claim dispositions, an
+//! object, and must never be read as repoints.
+
+use chrono::{DateTime, Utc};
+use common_sqlx_macros::{mirrored_query_as, mirrored_query_scalar};
+use uuid::Uuid;
+
+use crate::config::IdentityTables;
+use crate::lifecycle::engine::Tx;
+
+/// The last `(person_id, mapping ordinal)` already published for a
+/// pointer. `(0, 0)` is before every row: person ids are positive and
+/// ordinality starts at 1. `moved` never changes after its commit, so the
+/// order is stable across claims.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Cursor {
+ pub person_id: i64,
+ pub mapping_ordinal: i64,
+}
+
+impl Cursor {
+ pub const START: Cursor = Cursor {
+ person_id: 0,
+ mapping_ordinal: 0,
+ };
+}
+
+#[derive(Debug, Clone)]
+pub struct PointerOp {
+ pub op_type: String,
+ pub completed_at: Option<DateTime<Utc>>,
+ /// Rows with `role = 'target'`. A merge has exactly one; more would
+ /// fan the resolution join out and repeat every source entry under
+ /// the same cursor key.
+ pub target_rows: i64,
+ /// Source or victim rows whose `moved` is not a JSON array. The
+ /// resolution query skips them, so a count above zero is the only way
+ /// to see the corruption instead of silently publishing nothing.
+ pub malformed_moved_rows: i64,
+}
+
+/// A pointer's op row, or `None` when the op is gone, which GC must never
+/// cause while the pointer exists and is therefore corrupt state.
+pub async fn load_op(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+) -> Result<Option<PointerOp>, sqlx::Error> {
+ mirrored_query_as!(
+ PointerOp,
+ tables.is_validation(),
+ op = "publish_load_op",
+ r#"
+ SELECT op.op_type, op.completed_at,
+ (SELECT count(*) FROM {lifecycle_op_person} lop
+ WHERE lop.op_id = op.op_id AND lop.role = 'target') AS "target_rows!",
+ (SELECT count(*) FROM {lifecycle_op_person} lop
+ WHERE lop.op_id = op.op_id
+ AND lop.role IN ('source', 'victim')
+ AND lop.moved IS NOT NULL
+ AND jsonb_typeof(lop.moved) <> 'array') AS "malformed_moved_rows!"
+ FROM {lifecycle_op} op
+ WHERE op.op_id = $1
+ "#,
+ op_id
+ => fetch_optional(&mut **tx)
+ )
+}
+
+/// One `moved` entry, positioned for the cursor. The payload columns are
+/// nullable on purpose: the query extracts them without casting anything
+/// that could raise, so a malformed entry reaches Rust as `None` and gives
+/// the pointer up instead of aborting the claim transaction.
+#[derive(Debug, Clone)]
+pub struct ResolvedRow {
+ pub person_id: i64,
+ pub mapping_ordinal: i64,
+ pub owner_uuid: Option<Uuid>,
+ pub distinct_id: Option<String>,
+ pub version: Option<i64>,
+ pub is_deleted: bool,
+}
+
+impl ResolvedRow {
+ pub fn cursor(&self) -> Cursor {
+ Cursor {
+ person_id: self.person_id,
+ mapping_ordinal: self.mapping_ordinal,
+ }
+ }
+}
+
+/// The next `limit` moved entries after `cursor`, in `(person_id, element
+/// ordinal)` order. A repointed mapping's owner is the merge target's uuid;
+/// a tombstoned mapping keeps its victim's uuid and is flagged deleted.
+///
+/// Nothing in this statement can raise on data. `distinct_id` is taken
+/// only from a JSON string, `version` only from a JSON number that is an
+/// integer inside the `bigint` range (checked as `numeric`, which holds
+/// any JSON number, because a decimal or an out-of-range number would fail
+/// the `bigint` cast), and persons before the cursor are not expanded at
+/// all, so a large op does not pay for its finished persons on every
+/// chunk.
+pub async fn resolve_chunk(
+ tx: &mut Tx<'_>,
+ tables: &IdentityTables,
+ op_id: Uuid,
+ cursor: Cursor,
+ limit: i64,
+) -> Result<Vec<ResolvedRow>, sqlx::Error> {
+ mirrored_query_as!(
+ ResolvedRow,
+ tables.is_validation(),
+ op = "publish_resolve_pointer",
+ r#"
+ WITH moved_rows AS (
+ SELECT lop.person_id, lop.role, lop.person_uuid,
+ CASE WHEN jsonb_typeof(e.value -> 'distinct_id') = 'string'
+ THEN e.value ->> 'distinct_id' END AS distinct_id,
+ CASE WHEN jsonb_typeof(e.value -> 'version') = 'number'
+ AND (e.value ->> 'version')::numeric = trunc((e.value ->> 'version')::numeric)
+ AND (e.value ->> 'version')::numeric BETWEEN -9223372036854775808 AND 9223372036854775807
+ THEN (e.value ->> 'version')::bigint END AS version,
+ e.ordinality AS mapping_ordinal
+ FROM {lifecycle_op_person} lop
+ CROSS JOIN LATERAL jsonb_array_elements(lop.moved) WITH ORDINALITY AS e(value, ordinality)
+ WHERE lop.op_id = $1
+ AND lop.role IN ('source', 'victim')
+ AND lop.moved IS NOT NULL
+ AND jsonb_typeof(lop.moved) = 'array'
+ AND lop.person_id >= $2
+ )
+ SELECT m.person_id AS "person_id!",
+ m.mapping_ordinal AS "mapping_ordinal!",
+ CASE m.role WHEN 'victim' THEN m.person_uuid ELSE t.person_uuid END AS owner_uuid,
+ m.distinct_id,
+ m.version,
+ (m.role = 'victim') AS "is_deleted!"
+ FROM moved_rows m
+ LEFT JOIN {lifecycle_op_person} t ON t.op_id = $1 AND t.role = 'target'
+ WHERE (m.person_id, m.mapping_ordinal) > ($2, $3)
+ ORDER BY m.person_id, m.mapping_ordinal
+ LIMIT $4
+ "#,
+ op_id,
+ cursor.person_id,
+ cursor.mapping_ordinal,
+ limit
+ => fetch_all(&mut **tx)
+ )
+}
+
+/// Pending and given-up rows, and the age of the oldest pending one, for
+/// the gauges. The age is one index probe and is measured on the database
+/// clock, so a skewed publisher clock cannot fake or hide lag; it is the
+/// alerting signal. The counts scan at most `GAUGE_SCAN_CAP` rows and
+/// saturate there, so a backlog of millions does not turn every refresh
+/// into a full scan.
+pub struct OutboxDepth {
+ pub pending: i64,
+ pub given_up: i64,
+ pub lag_seconds: f64,
+}
+
+pub const GAUGE_SCAN_CAP: i64 = 1_000_000;
+
+pub async fn outbox_depth(
+ pool: &sqlx::PgPool,
+ tables: &IdentityTables,
+) -> Result<OutboxDepth, sqlx::Error> {
+ let counts = mirrored_query_as!(
+ Counts,
+ tables.is_validation(),
+ op = "publish_outbox_counts",
+ r#"
+ SELECT count(*) FILTER (WHERE given_up_at IS NULL) AS "pending!",
+ count(*) FILTER (WHERE given_up_at IS NOT NULL) AS "given_up!"
+ FROM (SELECT given_up_at FROM {person_publish_outbox} LIMIT $1) AS scanned
+ "#,
+ GAUGE_SCAN_CAP
+ => fetch_one(pool)
+ )?;
+ let lag_seconds = mirrored_query_scalar!(
+ tables.is_validation(),
+ op = "publish_outbox_oldest",
+ r#"
+ SELECT EXTRACT(EPOCH FROM now() - created_at)::float8 AS "lag_seconds!"
+ FROM {person_publish_outbox}
+ WHERE given_up_at IS NULL ORDER BY id LIMIT 1
+ "#
+ => fetch_optional(pool)
+ )?;
+ Ok(OutboxDepth {
+ pending: counts.pending,
+ given_up: counts.given_up,
+ lag_seconds: lag_seconds.unwrap_or(0.0).max(0.0),
+ })
+}
+
+struct Counts {
+ pending: i64,
+ given_up: i64,
+}
diff --git a/rust/personhog-identity/src/publish/sink.rs b/rust/personhog-identity/src/publish/sink.rs
new file mode 100644
index 000000000000..3c4c25502459
--- /dev/null
+++ b/rust/personhog-identity/src/publish/sink.rs
@@ -0,0 +1,95 @@
+//! Where a drained batch goes. The drain commits its outbox write-back only
+//! after [`PublishSink::send`] returns `Ok`, so a sink must not report
+//! success before every message is acked; tests substitute recording and
+//! failing sinks for the Kafka one.
+
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common_kafka::kafka_producer::{send_iter_to_kafka, KafkaContext};
+use rdkafka::producer::FutureProducer;
+
+use crate::publish::messages::DistinctIdRow;
+
+const PUBLISH_MESSAGES_TOTAL: &str = "personhog_lifecycle_publish_messages_total";
+
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct PublishBatch {
+ pub distinct_id_rows: Vec<DistinctIdRow>,
+}
+
+impl PublishBatch {
+ pub fn is_empty(&self) -> bool {
+ self.distinct_id_rows.is_empty()
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PublishError {
+ #[error("kafka produce failed: {0}")]
+ Kafka(String),
+ #[error("kafka produce did not complete within {0:?}")]
+ Timeout(Duration),
+}
+
+#[async_trait]
+pub trait PublishSink: Send + Sync {
+ /// Resolves only after every message in the batch is acked. An error
+ /// means none of them may be treated as published; some may still
+ /// arrive later, which every consumer of these topics absorbs.
+ async fn send(&self, batch: &PublishBatch) -> Result<(), PublishError>;
+}
+
+pub struct KafkaSink {
+ producer: FutureProducer<KafkaContext>,
+ distinct_id_topic: String,
+ produce_timeout: Duration,
+}
+
+impl KafkaSink {
+ pub fn new(
+ producer: FutureProducer<KafkaContext>,
+ distinct_id_topic: String,
+ produce_timeout: Duration,
+ ) -> Self {
+ Self {
+ producer,
+ distinct_id_topic,
+ produce_timeout,
+ }
+ }
+}
+
+#[async_trait]
+impl PublishSink for KafkaSink {
+ async fn send(&self, batch: &PublishBatch) -> Result<(), PublishError> {
+ if batch.is_empty() {
+ return Ok(());
+ }
+ // Null keys, like the Node producer: the consumers order by
+ // `version`, not by partition.
+ let sent = tokio::time::timeout(
+ self.produce_timeout,
+ send_iter_to_kafka(
+ &self.producer,
+ &self.distinct_id_topic,
+ &batch.distinct_id_rows,
+ ),
+ )
+ .await
+ .map_err(|_| PublishError::Timeout(self.produce_timeout))?;
+ let failed = sent.iter().filter(|r| r.is_err()).count();
+ if let Some(Err(first)) = sent.iter().find(|r| r.is_err()) {
+ return Err(PublishError::Kafka(format!(
+ "{failed} of {} messages failed; first error: {first}",
+ sent.len()
+ )));
+ }
+ common_metrics::inc(
+ PUBLISH_MESSAGES_TOTAL,
+ &[("topic".to_string(), self.distinct_id_topic.clone())],
+ sent.len() as u64,
+ );
+ Ok(())
+ }
+}
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 2a8a7c774a72..b08454e9850d 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -4,15 +4,26 @@
pub mod sim_leader;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
use rand::Rng;
use sqlx::postgres::PgPool;
+use uuid::Uuid;
use personhog_identity::config::IdentityTables;
use personhog_identity::pools::IdentityPools;
+use personhog_identity::publish::messages::DistinctIdRow;
+use personhog_identity::publish::sink::{PublishBatch, PublishError, PublishSink};
+use personhog_identity::publish::{DrainConfig, Publisher};
use personhog_identity::storage::postgres::PostgresIdentityStorage;
+/// Serializes every test that drains the publish outbox, across the
+/// processes nextest runs tests in: the drain claims the oldest pending
+/// rows of every team, so two concurrent drains would take each other's
+/// rows. See [`TestContext::hold_drain_lock`].
+const DRAIN_LOCK_KEY: i64 = 0x5048_5055_424c_4953;
+
/// The production table set. Most tests run here; the raw-SQL assertion
/// helpers in the test binaries assume it.
/// Leader fan-out width the suites run with; production reads it from config.
@@ -197,6 +208,69 @@ impl TestContext {
Ok(())
}
+ /// 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
+ /// releases it, on a panic too.
+ ///
+ /// Once the lock is held, every other team's outbox row is a leftover
+ /// of a test that panicked before its cleanup, because every writer
+ /// takes this lock first. They are deleted here: the claim takes the
+ /// oldest rows across all teams, and leftovers would spend this test's
+ /// pass budget and change what its own rows resolve to.
+ pub async fn hold_drain_lock(&self) -> sqlx::Transaction<'static, sqlx::Postgres> {
+ let mut tx = self.pool.begin().await.expect("begin lock transaction");
+ sqlx::query("SELECT pg_advisory_xact_lock($1)")
+ .bind(DRAIN_LOCK_KEY)
+ .execute(&mut *tx)
+ .await
+ .expect("take the drain lock");
+ sqlx::query(&format!(
+ "DELETE FROM {} WHERE team_id <> $1",
+ self.tables.person_publish_outbox
+ ))
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("clear leftover outbox rows");
+ tx
+ }
+
+ /// A publisher over this context's pool and table set. The batch is
+ /// large so rows another test left behind when it crashed before its
+ /// cleanup cannot crowd this test's rows out of a pass; they drain into
+ /// the sink, where [`RecordingSink::rows_for_team`] ignores them. The
+ /// row budget is the caller's, so a test can make it small enough that
+ /// its own pointer drains in chunks.
+ pub fn publisher<S: PublishSink>(&self, sink: S, max_rows_per_pass: i64) -> Publisher<S> {
+ Publisher::new(
+ self.pool.clone(),
+ self.tables.clone(),
+ sink,
+ DrainConfig {
+ batch_size: 10_000,
+ max_rows_per_pass,
+ interval: Duration::from_millis(10),
+ lag_alert: Duration::from_secs(300),
+ },
+ )
+ }
+
+ pub async fn outbox_rows(&self) -> Vec<OutboxRow> {
+ sqlx::query_as(&format!(
+ r#"
+ SELECT id, kind, op_id, cursor_person_id, cursor_mapping_ordinal, attempts,
+ given_up_at IS NOT NULL AS given_up, last_error
+ FROM {} WHERE team_id = $1 ORDER BY id
+ "#,
+ self.tables.person_publish_outbox
+ ))
+ .bind(self.team_id as i32)
+ .fetch_all(&self.pool)
+ .await
+ .expect("read outbox rows")
+ }
+
pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
sqlx::query(&format!(
"DELETE FROM {} WHERE team_id = $1",
@@ -230,6 +304,58 @@ impl TestContext {
}
}
+#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)]
+pub struct OutboxRow {
+ pub id: i64,
+ pub kind: String,
+ pub op_id: Option<Uuid>,
+ pub cursor_person_id: i64,
+ pub cursor_mapping_ordinal: i64,
+ pub attempts: i32,
+ pub given_up: bool,
+ pub last_error: Option<String>,
+}
+
+/// A sink that keeps every batch it acked. Clones share the record, so a
+/// test hands one clone to the publisher and reads the other.
+#[derive(Default, Clone)]
+pub struct RecordingSink {
+ batches: Arc<Mutex<Vec<PublishBatch>>>,
+}
+
+impl RecordingSink {
+ pub fn batches(&self) -> Vec<PublishBatch> {
+ self.batches.lock().unwrap().clone()
+ }
+
+ /// Every distinct id row published for `team_id`, in publish order.
+ /// Rows of other teams are leftovers of other tests and are ignored.
+ pub fn rows_for_team(&self, team_id: i64) -> Vec<DistinctIdRow> {
+ self.batches()
+ .into_iter()
+ .flat_map(|b| b.distinct_id_rows)
+ .filter(|r| r.team_id == team_id)
+ .collect()
+ }
+}
+
+#[async_trait::async_trait]
+impl PublishSink for RecordingSink {
+ async fn send(&self, batch: &PublishBatch) -> Result<(), PublishError> {
+ self.batches.lock().unwrap().push(batch.clone());
+ Ok(())
+ }
+}
+
+pub struct FailingSink;
+
+#[async_trait::async_trait]
+impl PublishSink for FailingSink {
+ async fn send(&self, _batch: &PublishBatch) -> Result<(), PublishError> {
+ Err(PublishError::Kafka("brokers unreachable".to_string()))
+ }
+}
+
/// Leader-surface stubs for test binaries whose flows never reach the
/// leader: an accidental call surfaces as a clean unimplemented error
/// instead of a hang or a panic mid-transaction.
diff --git a/rust/personhog-identity/tests/lifecycle_delete_tests.rs b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
index 139b3df4dc0c..9afac8986b07 100644
--- a/rust/personhog-identity/tests/lifecycle_delete_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_delete_tests.rs
@@ -8,7 +8,7 @@ use std::sync::Arc;
use chrono::Utc;
use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};
-use common::TestContext;
+use common::{RecordingSink, TestContext};
use personhog_common::partitioning::partition_for_person;
use tonic::{Request, Status};
use uuid::Uuid;
@@ -17,6 +17,7 @@ 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;
+use personhog_identity::publish::messages::DistinctIdRow;
use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePersonsRequest};
@@ -24,6 +25,10 @@ use personhog_proto::personhog::lifecycle::v1::{DeletePersonOutcome, DeletePerso
/// Storage-assertion helpers used only by this test binary.
impl TestContext {
fn lifecycle_service(&self) -> PersonHogLifecycleService {
+ self.lifecycle_service_with(OutboxWrites::Disabled)
+ }
+
+ fn lifecycle_service_with(&self, outbox_writes: OutboxWrites) -> PersonHogLifecycleService {
let engine = Arc::new(self.engine());
let leader = Arc::new(SimLeader::new(self.pool.clone(), self.tables.clone()));
PersonHogLifecycleService::new(
@@ -32,7 +37,7 @@ impl TestContext {
self.tables.clone(),
common::FAN_OUT_CONCURRENCY,
common::NUM_PARTITIONS,
- OutboxWrites::Disabled,
+ outbox_writes,
)
}
@@ -169,7 +174,8 @@ fn outcomes(
#[tokio::test]
async fn delete_destroys_the_person_and_its_satellite_rows() {
let ctx = TestContext::new().await;
- let service = ctx.lifecycle_service();
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let service = ctx.lifecycle_service_with(OutboxWrites::Enabled);
let person_id = ctx.insert_person_with_distinct_id("victim-primary").await;
sqlx::query(
@@ -237,6 +243,33 @@ async fn delete_destroys_the_person_and_its_satellite_rows() {
assert_eq!(moved_ids.len(), 2);
assert!(moved_ids.contains(&"victim-primary") && moved_ids.contains(&"victim-extra"));
+ // One publish pass resolves the op's pointer to the tombstones at their
+ // tombstoned versions, flagged deleted and still owned by the victim's
+ // uuid, never as live rows.
+ let sink = RecordingSink::default();
+ ctx.publisher(sink.clone(), 100)
+ .drain_once()
+ .await
+ .expect("publish pass");
+ let victim_uuid: Uuid = sqlx::query_scalar("SELECT uuid FROM posthog_person WHERE id = $1")
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .unwrap();
+ let mut published = sink.rows_for_team(ctx.team_id);
+ published.sort_by(|a, b| a.distinct_id.cmp(&b.distinct_id));
+ assert_eq!(
+ published,
+ [("victim-extra", 2), ("victim-primary", 1)].map(|(did, version)| DistinctIdRow {
+ person_id: victim_uuid,
+ team_id: ctx.team_id,
+ distinct_id: did.to_string(),
+ version,
+ is_deleted: 1,
+ })
+ );
+ assert!(ctx.outbox_rows().await.is_empty(), "the pointer is deleted");
+
ctx.cleanup().await.expect("cleanup");
}
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index 15b3379c0411..1a3604f487a4 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -304,6 +304,9 @@ async fn pointer_kinds(ctx: &TestContext, op_id: Uuid) -> Vec<String> {
#[tokio::test]
async fn only_a_completed_op_with_outbox_writes_enabled_enqueues_a_publish_pointer() {
let ctx = TestContext::new().await;
+ // The pointers this test asserts on are pending rows a draining test
+ // in another process would otherwise claim and delete.
+ let _drain_lock = ctx.hold_drain_lock().await;
let engine = ctx.engine();
let cases = [
(
@@ -365,6 +368,9 @@ async fn remaining_ops(ctx: &TestContext, op_ids: &[Uuid]) -> Vec<Uuid> {
#[tokio::test]
async fn gc_reaps_completed_ops_past_retention_unless_a_publish_pointer_remains() {
let ctx = TestContext::new().await;
+ // The pending pointer must survive until GC has seen it, so no
+ // draining test in another process may claim it meanwhile.
+ let _drain_lock = ctx.hold_drain_lock().await;
let engine = ctx.engine();
let driver = DummyDriver::new();
// Three completed ops: no outbox row, a pending pointer, a given-up pointer.
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 5dad7a356ac2..100917f451dc 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -15,7 +15,7 @@ use std::sync::Arc;
use chrono::Utc;
use common::sim_leader::{LeaderCall, Rpc, SimLeader, FENCED_METADATA_KEY};
-use common::TestContext;
+use common::{RecordingSink, TestContext};
use personhog_common::grpc::semantic_refusal;
use personhog_common::persons::{person_uuid, COOKIELESS_SENTINEL_VALUE};
use serde_json::json;
@@ -34,6 +34,7 @@ use personhog_identity::lifecycle::merge::{
OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,
OUTCOME_SKIPPED_MOVE_LIMIT,
};
+use personhog_identity::publish::messages::DistinctIdRow;
use personhog_proto::personhog::types::v1::LifecycleOpType;
struct MergeHarness {
@@ -46,10 +47,22 @@ struct MergeHarness {
impl MergeHarness {
async fn new() -> Self {
- Self::new_with_tables(common::default_tables()).await
+ Self::new_with(common::default_tables(), OutboxWrites::Disabled).await
+ }
+
+ /// A harness whose completed merges enqueue a publish pointer.
+ async fn new_publishing() -> Self {
+ Self::new_with(common::default_tables(), OutboxWrites::Enabled).await
}
async fn new_with_tables(tables: personhog_identity::config::IdentityTables) -> Self {
+ Self::new_with(tables, OutboxWrites::Disabled).await
+ }
+
+ async fn new_with(
+ tables: personhog_identity::config::IdentityTables,
+ outbox_writes: OutboxWrites,
+ ) -> Self {
let ctx = TestContext::new_with_tables(tables).await;
let engine = ctx.engine();
let leader = Arc::new(SimLeader::new(ctx.pool.clone(), ctx.tables.clone()));
@@ -57,7 +70,7 @@ impl MergeHarness {
leader.clone(),
ctx.tables.clone(),
common::FAN_OUT_CONCURRENCY,
- OutboxWrites::Disabled,
+ outbox_writes,
);
Self {
ctx,
@@ -404,7 +417,8 @@ async fn a_completing_fold_leaves_a_moved_away_target_unstamped() {
#[tokio::test]
async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {
- let h = MergeHarness::new().await;
+ let h = MergeHarness::new_publishing().await;
+ let _drain_lock = h.ctx.hold_drain_lock().await;
let target = h.ctx.insert_person_with_distinct_id("merge-target").await;
let source = h.ctx.insert_person_with_distinct_id("merge-source").await;
h.add_distinct_id(source, "merge-source-alias").await;
@@ -516,6 +530,38 @@ async fn a_merge_folds_repoints_tombstones_and_records_the_outcome() {
assert_eq!(h.op_person_status(op_id, target).await, "cleared");
assert_eq!(h.op_person_status(op_id, source).await, "deleted");
+ // The completion left one publish pointer, and one pass resolves it to
+ // exactly the repointed mappings: the source's ids, owned by the
+ // target's uuid at their bumped versions. The target row's own `moved`
+ // is its claim record and contributes nothing.
+ let sink = RecordingSink::default();
+ h.ctx
+ .publisher(sink.clone(), 100)
+ .drain_once()
+ .await
+ .expect("publish pass");
+ let target_uuid: Uuid = sqlx::query_scalar("SELECT uuid FROM posthog_person WHERE id = $1")
+ .bind(target)
+ .fetch_one(&h.ctx.pool)
+ .await
+ .unwrap();
+ let mut published = sink.rows_for_team(h.ctx.team_id);
+ published.sort_by(|a, b| a.distinct_id.cmp(&b.distinct_id));
+ assert_eq!(
+ published,
+ ["merge-source", "merge-source-alias"].map(|did| DistinctIdRow {
+ person_id: target_uuid,
+ team_id: h.ctx.team_id,
+ distinct_id: did.to_string(),
+ version: 1,
+ is_deleted: 0,
+ })
+ );
+ assert!(
+ h.ctx.outbox_rows().await.is_empty(),
+ "the pointer is deleted"
+ );
+
h.ctx.cleanup().await.expect("cleanup");
}
diff --git a/rust/personhog-identity/tests/publish_tests.rs b/rust/personhog-identity/tests/publish_tests.rs
new file mode 100644
index 000000000000..e94d8a7dc6b1
--- /dev/null
+++ b/rust/personhog-identity/tests/publish_tests.rs
@@ -0,0 +1,543 @@
+//! The drain against real Postgres with recording and failing sinks: what
+//! one claim transaction publishes, keeps, advances, or gives up. Every
+//! test that commits outbox rows holds the drain lock (see
+//! `common::TestContext::hold_drain_lock`) because the claim is not scoped
+//! to a team.
+
+mod common;
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use common::{FailingSink, RecordingSink, TestContext};
+use serde_json::{json, Value};
+use uuid::Uuid;
+
+use personhog_identity::publish::claim::claim_sql;
+use personhog_identity::publish::messages::DistinctIdRow;
+use personhog_identity::publish::{DrainError, PassReport};
+
+impl TestContext {
+ async fn insert_completed_op(&self, op_type: &str) -> Uuid {
+ let op_id = Uuid::now_v7();
+ sqlx::query(
+ r#"
+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, outcome, completed_at)
+ VALUES ($1, $2, $3, 'completed', '{}'::jsonb, '{}'::jsonb, now())
+ "#,
+ )
+ .bind(op_id)
+ .bind(op_type)
+ .bind(self.team_id as i32)
+ .execute(&self.pool)
+ .await
+ .expect("insert op");
+ op_id
+ }
+
+ async fn insert_op_person(
+ &self,
+ op_id: Uuid,
+ person_id: i64,
+ person_uuid: Uuid,
+ role: &str,
+ moved: Option<Value>,
+ ) {
+ let status = if role == "target" {
+ "cleared"
+ } else {
+ "deleted"
+ };
+ sqlx::query(
+ r#"
+ INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status, moved)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ "#,
+ )
+ .bind(op_id)
+ .bind(self.team_id as i32)
+ .bind(person_id)
+ .bind(person_uuid)
+ .bind(role)
+ .bind(status)
+ .bind(moved)
+ .execute(&self.pool)
+ .await
+ .expect("insert op person");
+ }
+
+ async fn insert_pointer(&self, op_id: Uuid, kind: &str) -> i64 {
+ sqlx::query_scalar(
+ "INSERT INTO person_publish_outbox (team_id, kind, op_id) VALUES ($1, $2, $3) RETURNING id",
+ )
+ .bind(self.team_id as i32)
+ .bind(kind)
+ .bind(op_id)
+ .fetch_one(&self.pool)
+ .await
+ .expect("insert pointer")
+ }
+
+ async fn insert_mapping_row(&self, person_uuid: Uuid, distinct_id: &str, version: i64) -> i64 {
+ sqlx::query_scalar(
+ r#"
+ INSERT INTO person_publish_outbox (team_id, kind, person_uuid, distinct_id, version)
+ VALUES ($1, 'create', $2, $3, $4) RETURNING id
+ "#,
+ )
+ .bind(self.team_id as i32)
+ .bind(person_uuid)
+ .bind(distinct_id)
+ .bind(version)
+ .fetch_one(&self.pool)
+ .await
+ .expect("insert mapping row")
+ }
+
+ /// A completed merge op with one source whose `moved` is `source_moved`
+ /// and, unless `with_target` is false, one target whose `moved` is its
+ /// claim record, an object, as the merge saga writes it. Returns the
+ /// op id and its pointer's outbox id.
+ async fn insert_merge_pointer(
+ &self,
+ target_uuid: Uuid,
+ source_moved: Option<Value>,
+ with_target: bool,
+ ) -> (Uuid, i64) {
+ let op_id = self.insert_completed_op("merge").await;
+ if with_target {
+ self.insert_op_person(
+ op_id,
+ next_person_id(),
+ target_uuid,
+ "target",
+ Some(json!({"dispositions": []})),
+ )
+ .await;
+ }
+ self.insert_op_person(
+ op_id,
+ next_person_id(),
+ Uuid::now_v7(),
+ "source",
+ source_moved,
+ )
+ .await;
+ let outbox_id = self.insert_pointer(op_id, "merge_op").await;
+ (op_id, outbox_id)
+ }
+
+ fn row(
+ &self,
+ person_id: Uuid,
+ distinct_id: &str,
+ version: i64,
+ is_deleted: u8,
+ ) -> DistinctIdRow {
+ DistinctIdRow {
+ person_id,
+ team_id: self.team_id,
+ distinct_id: distinct_id.to_string(),
+ version,
+ is_deleted,
+ }
+ }
+}
+
+fn moved(entries: &[(&str, i64)]) -> Value {
+ Value::Array(
+ entries
+ .iter()
+ .map(|(distinct_id, version)| json!({"distinct_id": distinct_id, "version": version}))
+ .collect(),
+ )
+}
+
+fn as_refs(entries: &[(String, i64)]) -> Vec<(&str, i64)> {
+ entries.iter().map(|(d, v)| (d.as_str(), *v)).collect()
+}
+
+/// Person ids for per-person rows. The fixtures never touch the person
+/// table, so any id works; they only need to be distinct within an op and
+/// increasing within a test so the keyset order is the insertion order.
+fn next_person_id() -> i64 {
+ static NEXT: AtomicI64 = AtomicI64::new(0);
+ let base = i64::from(std::process::id()) << 20;
+ base + NEXT.fetch_add(1, Ordering::Relaxed)
+}
+
+#[tokio::test]
+async fn a_failed_send_leaves_every_claimed_row_in_place_for_the_next_pass() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let created = Uuid::now_v7();
+ let target = Uuid::now_v7();
+ let mapping_id = ctx.insert_mapping_row(created, "did-created", 0).await;
+ let (_, pointer_id) = ctx
+ .insert_merge_pointer(target, Some(moved(&[("did-x", 1), ("did-y", 2)])), true)
+ .await;
+ let before = ctx.outbox_rows().await;
+ assert_eq!(before.len(), 2);
+
+ let err = ctx
+ .publisher(FailingSink, 5)
+ .drain_once()
+ .await
+ .expect_err("a sink failure fails the pass");
+ assert!(matches!(err, DrainError::Publish(_)), "{err}");
+ assert_eq!(
+ ctx.outbox_rows().await,
+ before,
+ "nothing deleted, no cursor moved, no attempt counted"
+ );
+
+ let sink = RecordingSink::default();
+ ctx.publisher(sink.clone(), 5)
+ .drain_once()
+ .await
+ .expect("the next pass publishes");
+ assert_eq!(
+ sink.rows_for_team(ctx.team_id),
+ vec![
+ ctx.row(created, "did-created", 0, 0),
+ ctx.row(target, "did-x", 1, 0),
+ ctx.row(target, "did-y", 2, 0),
+ ],
+ "claim order: the mapping row ({mapping_id}) then the pointer ({pointer_id})"
+ );
+ assert!(ctx.outbox_rows().await.is_empty());
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+// Every shape here is state the sagas cannot write. Each must leave its own
+// pointer pending with a reason and a counted attempt, leave the rest of the
+// batch alone, and publish on its own once the state is repaired; a raise in
+// the resolution SQL would instead fail the pass and, since the poisoned row
+// stays the oldest, every pass after it.
+#[tokio::test]
+async fn a_poisoned_pointer_is_deferred_while_the_rest_of_its_batch_publishes() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ let target = Uuid::now_v7();
+
+ let (healthy, _) = ctx
+ .insert_merge_pointer(target, Some(moved(&[("did-h", 3)])), true)
+ .await;
+ // The largest version the mapping table can hold is healthy too.
+ let (largest, _) = ctx
+ .insert_merge_pointer(target, Some(moved(&[("did-max", i64::MAX)])), true)
+ .await;
+ // Moved nothing: a source with no live distinct ids.
+ let (empty, _) = ctx.insert_merge_pointer(target, None, true).await;
+ let vanished = Uuid::now_v7();
+ ctx.insert_pointer(vanished, "delete_op").await;
+
+ let poison: Vec<(&str, Option<Value>, bool, &str)> = vec![
+ (
+ "moved is a string",
+ Some(json!("garbage")),
+ true,
+ "not an array",
+ ),
+ (
+ "decimal version",
+ Some(json!([{"distinct_id": "bad", "version": 1.5}])),
+ true,
+ "malformed",
+ ),
+ (
+ // 1e20 lands in jsonb as a 21-digit integer, past bigint.
+ "out-of-range version",
+ Some(json!([{"distinct_id": "bad", "version": 1e20}])),
+ true,
+ "malformed",
+ ),
+ (
+ "string version",
+ Some(json!([{"distinct_id": "bad", "version": "3"}])),
+ true,
+ "malformed",
+ ),
+ (
+ "numeric distinct_id",
+ Some(json!([{"distinct_id": 7, "version": 1}])),
+ true,
+ "malformed",
+ ),
+ (
+ "null distinct_id",
+ Some(json!([{"distinct_id": null, "version": 1}])),
+ true,
+ "malformed",
+ ),
+ (
+ "bare string element",
+ Some(json!(["did-bare"])),
+ true,
+ "malformed",
+ ),
+ (
+ "merge without a target row",
+ Some(moved(&[("did-orphan", 1)])),
+ false,
+ "target rows",
+ ),
+ ];
+ let mut expected_errors: HashMap<Uuid, (&str, &str)> = HashMap::new();
+ for (label, source_moved, with_target, error_fragment) in &poison {
+ let (op_id, _) = ctx
+ .insert_merge_pointer(target, source_moved.clone(), *with_target)
+ .await;
+ expected_errors.insert(op_id, (label, error_fragment));
+ }
+ expected_errors.insert(vanished, ("vanished op", "no longer exists"));
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher(sink.clone(), 5);
+ publisher.drain_once().await.expect("the pass commits");
+ assert_eq!(
+ sink.rows_for_team(ctx.team_id),
+ vec![
+ ctx.row(target, "did-h", 3, 0),
+ ctx.row(target, "did-max", i64::MAX, 0)
+ ],
+ "only the healthy pointers publish"
+ );
+ let snapshot = |rows: Vec<common::OutboxRow>| -> HashMap<Uuid, (bool, i32, String)> {
+ rows.into_iter()
+ .map(|r| {
+ (
+ r.op_id.unwrap(),
+ (r.given_up, r.attempts, r.last_error.unwrap_or_default()),
+ )
+ })
+ .collect()
+ };
+ let left = snapshot(ctx.outbox_rows().await);
+ assert!(
+ !left.contains_key(&healthy) && !left.contains_key(&largest) && !left.contains_key(&empty),
+ "healthy and empty pointers are deleted: {left:?}"
+ );
+ assert_eq!(left.len(), expected_errors.len(), "{left:?}");
+ for (op_id, (label, error_fragment)) in &expected_errors {
+ let (given_up, attempts, last_error) = &left[op_id];
+ assert!(!given_up, "{label}: parked, but the publisher never parks");
+ assert_eq!(*attempts, 1, "{label}: attempts");
+ assert!(
+ last_error.contains(error_fragment),
+ "{label}: last_error {last_error:?} lacks {error_fragment:?}"
+ );
+ }
+
+ publisher
+ .drain_once()
+ .await
+ .expect("the second pass commits");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len(), 2);
+ for (op_id, (_, attempts, _)) in snapshot(ctx.outbox_rows().await) {
+ assert_eq!(attempts, 2, "{op_id}: attempts after the second pass");
+ }
+
+ let (repaired, _) = expected_errors
+ .iter()
+ .find(|(_, (label, _))| *label == "moved is a string")
+ .expect("the string-moved op is in the table");
+ sqlx::query("UPDATE lifecycle_op_person SET moved = $1 WHERE op_id = $2 AND role = 'source'")
+ .bind(moved(&[("did-fixed", 2)]))
+ .bind(repaired)
+ .execute(&ctx.pool)
+ .await
+ .expect("repair moved");
+ publisher
+ .drain_once()
+ .await
+ .expect("the third pass commits");
+ assert_eq!(
+ sink.rows_for_team(ctx.team_id),
+ vec![
+ ctx.row(target, "did-h", 3, 0),
+ ctx.row(target, "did-max", i64::MAX, 0),
+ ctx.row(target, "did-fixed", 2, 0)
+ ]
+ );
+ let left = snapshot(ctx.outbox_rows().await);
+ assert!(
+ !left.contains_key(repaired),
+ "the repaired pointer is deleted"
+ );
+ assert_eq!(left.len(), expected_errors.len() - 1);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_large_pointer_drains_in_cursor_chunks_without_a_gap_or_a_repeat() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ // Two victims, 5 and 7 tombstoned ids, drained 5 at a time: the first
+ // person ends exactly at the limit, so the second chunk must start on
+ // the next person without repeating the last entry or skipping the
+ // first; the third chunk is short.
+ let op_id = ctx.insert_completed_op("delete").await;
+ let (victim_a, victim_b) = (Uuid::now_v7(), Uuid::now_v7());
+ let (person_a, person_b) = (next_person_id(), next_person_id());
+ let a_entries: Vec<(String, i64)> = (1..=5).map(|i| (format!("a-{i}"), i)).collect();
+ let b_entries: Vec<(String, i64)> = (1..=7).map(|i| (format!("b-{i}"), 10 + i)).collect();
+ ctx.insert_op_person(
+ op_id,
+ person_a,
+ victim_a,
+ "victim",
+ Some(moved(&as_refs(&a_entries))),
+ )
+ .await;
+ ctx.insert_op_person(
+ op_id,
+ person_b,
+ victim_b,
+ "victim",
+ Some(moved(&as_refs(&b_entries))),
+ )
+ .await;
+ ctx.insert_pointer(op_id, "delete_op").await;
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher(sink.clone(), 5);
+ let cursor_after = |rows: Vec<common::OutboxRow>| {
+ rows.into_iter()
+ .map(|r| (r.cursor_person_id, r.cursor_mapping_ordinal, r.attempts))
+ .collect::<Vec<_>>()
+ };
+
+ publisher.drain_once().await.expect("first chunk");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len(), 5);
+ assert_eq!(
+ cursor_after(ctx.outbox_rows().await),
+ vec![(person_a, 5, 1)]
+ );
+
+ publisher.drain_once().await.expect("second chunk");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len(), 10);
+ assert_eq!(
+ cursor_after(ctx.outbox_rows().await),
+ vec![(person_b, 5, 2)]
+ );
+
+ publisher.drain_once().await.expect("final chunk");
+ assert_eq!(sink.rows_for_team(ctx.team_id).len(), 12);
+ assert!(ctx.outbox_rows().await.is_empty());
+
+ let expected: Vec<DistinctIdRow> = a_entries
+ .iter()
+ .map(|(d, v)| ctx.row(victim_a, d, *v, 1))
+ .chain(b_entries.iter().map(|(d, v)| ctx.row(victim_b, d, *v, 1)))
+ .collect();
+ assert_eq!(sink.rows_for_team(ctx.team_id), expected);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn the_row_budget_spans_claimed_rows_and_the_rest_wait_for_the_next_pass() {
+ let ctx = TestContext::new().await;
+ let _drain_lock = ctx.hold_drain_lock().await;
+ // Three rows under a budget of 10: a merge of 6 ids takes 6, a second
+ // merge of 6 gets the other 4 and advances, and the mapping row behind
+ // them is left alone, attempts included, until the next pass.
+ let (target_a, target_b) = (Uuid::now_v7(), Uuid::now_v7());
+ let a_entries: Vec<(String, i64)> = (1..=6).map(|i| (format!("a-{i}"), i)).collect();
+ let b_entries: Vec<(String, i64)> = (1..=6).map(|i| (format!("b-{i}"), 10 + i)).collect();
+ ctx.insert_merge_pointer(target_a, Some(moved(&as_refs(&a_entries))), true)
+ .await;
+ let (_, pointer_b) = ctx
+ .insert_merge_pointer(target_b, Some(moved(&as_refs(&b_entries))), true)
+ .await;
+ let late = Uuid::now_v7();
+ let mapping = ctx.insert_mapping_row(late, "late", 0).await;
+
+ let sink = RecordingSink::default();
+ let publisher = ctx.publisher(sink.clone(), 10);
+
+ let report = publisher.drain_once().await.expect("first pass");
+ assert_eq!(
+ report,
+ PassReport {
+ claimed: 3,
+ finished: 1,
+ advanced: 1,
+ deferred: 0,
+ unprocessed: 1,
+ messages: 10,
+ }
+ );
+ let left: Vec<(i64, i64, i32)> = ctx
+ .outbox_rows()
+ .await
+ .into_iter()
+ .map(|r| (r.id, r.cursor_mapping_ordinal, r.attempts))
+ .collect();
+ assert_eq!(left, vec![(pointer_b, 4, 1), (mapping, 0, 0)]);
+
+ publisher.drain_once().await.expect("second pass");
+ assert!(ctx.outbox_rows().await.is_empty());
+ let expected: Vec<DistinctIdRow> = a_entries
+ .iter()
+ .map(|(d, v)| ctx.row(target_a, d, *v, 0))
+ .chain(b_entries.iter().map(|(d, v)| ctx.row(target_b, d, *v, 0)))
+ .chain([ctx.row(late, "late", 0, 0)])
+ .collect();
+ assert_eq!(sink.rows_for_team(ctx.team_id), expected);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
+// A backlog must be claimed in id order through the pending partial index,
+// bounded by LIMIT, never by sorting every pending row. The statement the
+// drain really runs and the index have to agree on that: a claim ordered
+// by a column the index does not cover, or a dropped or re-predicated
+// index, turns every claim on a backlog into a sort of the whole backlog.
+//
+// The planner costs a sort's input by the heap's real page count and the
+// index scan by the rows LIMIT needs, so on a heap of any size a sort plan
+// loses whatever the row estimate says; it can win only while the heap is
+// a few dozen pages, where sorting is as cheap as not. The burst here is
+// large enough that the two plans diverge, and it is analyzed so the
+// assertion does not hinge on whatever statistics an earlier test left.
+//
+// Everything runs in one transaction that is rolled back: the burst is
+// never visible to another test's drain, the statistics revert, and a
+// panic cannot leave rows behind, so no drain lock is needed.
+#[tokio::test]
+async fn an_analyzed_backlog_is_claimed_through_the_pending_index_without_a_sort() {
+ let ctx = TestContext::new().await;
+ let mut tx = ctx.pool.begin().await.expect("begin");
+ sqlx::query(
+ r#"
+ INSERT INTO person_publish_outbox (team_id, kind, person_uuid, distinct_id, version)
+ SELECT $1, 'create', gen_random_uuid(), 'burst-' || n, 0 FROM generate_series(1, 20000) AS n
+ "#,
+ )
+ .bind(ctx.team_id as i32)
+ .execute(&mut *tx)
+ .await
+ .expect("seed a burst");
+ sqlx::query("ANALYZE person_publish_outbox")
+ .execute(&mut *tx)
+ .await
+ .expect("analyze");
+ let plan: Vec<String> =
+ sqlx::query_scalar(&format!("EXPLAIN {}", claim_sql("person_publish_outbox")))
+ .bind(1000i64)
+ .fetch_all(&mut *tx)
+ .await
+ .expect("explain runs");
+ tx.rollback().await.expect("rollback");
+
+ let plan = plan.join("\n");
+ assert!(
+ plan.contains("Index Scan using person_publish_outbox_pending"),
+ "claim plan:\n{plan}"
+ );
+ assert!(!plan.contains("Sort"), "claim plan:\n{plan}");
+}
diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rs
index 272006289561..23a894b0322a 100644
--- a/rust/personhog-leader/src/kafka.rs
+++ b/rust/personhog-leader/src/kafka.rs
@@ -1,9 +1,3 @@
-use std::time::Duration;
-
-use common_kafka::kafka_producer::KafkaContext;
-use lifecycle::Handle;
-use rdkafka::producer::{FutureProducer, Producer};
-
/// Formats the Kafka message key for person state changelog messages.
/// The topic must include `compact` in its `cleanup.policy` so Kafka
/// retains the latest state per person. Deployed config is
@@ -13,57 +7,3 @@ use rdkafka::producer::{FutureProducer, Producer};
pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
format!("{team_id}:{person_id}")
}
-
-/// Completes the kafka-producer lifecycle component with a bounded
-/// flush instead of waiting for the last producer reference to drop.
-///
-/// The component's handle rides inside the producer context, which
-/// every clone of the producer shares — so without explicit shutdown
-/// work, the component completed only when everything holding the
-/// producer let go, and a queue wedged against a stalled broker held
-/// its shutdown phase to the global timeout. This task flushes what
-/// the queue holds within `bound` once the component's phase shuts
-/// down, then reports completion either way.
-///
-/// A timed-out flush drops only records nobody acked: the changelog
-/// path awaits each record's delivery before acking (so anything acked
-/// is already off the queue, and unacked writes retry via redelivery),
-/// and the rest of this producer's traffic is best-effort warnings.
-pub fn spawn_bounded_flush_on_shutdown(
- producer: FutureProducer<KafkaContext>,
- handle: Handle,
- bound: Duration,
-) {
- tokio::spawn(async move {
- handle.shutdown_recv().await;
- let queued = producer.in_flight_count();
- // Flush blocks, and so can the producer teardown after it; both
- // stay off the async workers. Completion is reported first, so
- // a teardown that outlives the flush bound cannot hold the
- // phase.
- let flushed = tokio::task::spawn_blocking(move || {
- let outcome = producer.flush(bound);
- let remaining = producer.in_flight_count();
- drop(producer);
- (outcome, remaining)
- })
- .await;
- match flushed {
- Ok((Ok(()), _)) => {
- tracing::info!(queued, "kafka producer flushed at shutdown");
- }
- Ok((Err(e), remaining)) => {
- tracing::warn!(
- queued,
- remaining,
- error = %e,
- "kafka producer flush hit its shutdown bound; undelivered records dropped"
- );
- }
- Err(e) => {
- tracing::warn!(error = %e, "kafka producer shutdown flush task failed");
- }
- }
- handle.work_completed();
- });
-}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 462035c7ff7a..1b266f1b428c 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -3,7 +3,7 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{routing::get, Router};
-use common_kafka::kafka_producer::create_kafka_producer;
+use common_kafka::kafka_producer::{create_kafka_producer, spawn_bounded_flush_on_shutdown};
use common_metrics::{setup_metrics_routes_with_overrides, Matcher};
use dashmap::DashMap;
use envconfig::Envconfig;
@@ -295,8 +295,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
};
// Runs at phase 1, after the coordination drain, so the drain's last
- // records are in the queue it flushes.
- personhog_leader::kafka::spawn_bounded_flush_on_shutdown(
+ // records are in the queue it flushes. The changelog path awaits each
+ // record's delivery before acking, so a timed-out flush drops only
+ // records nobody acked.
+ spawn_bounded_flush_on_shutdown(
kafka_producer.clone(),
kafka_handle,
Duration::from_secs(10),
diff --git a/rust/personhog-leader/tests/producer_flush.rs b/rust/personhog-leader/tests/producer_flush.rs
index 09ac9e81a8e2..3193f33ad91c 100644
--- a/rust/personhog-leader/tests/producer_flush.rs
+++ b/rust/personhog-leader/tests/producer_flush.rs
@@ -5,9 +5,8 @@
use std::time::{Duration, Instant};
-use common_kafka::kafka_producer::KafkaContext;
+use common_kafka::kafka_producer::{spawn_bounded_flush_on_shutdown, KafkaContext};
use lifecycle::{ComponentOptions, Manager};
-use personhog_leader::kafka::spawn_bounded_flush_on_shutdown;
use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::ClientConfig;