: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): verify the publish plane in the e2e gate (#117263)
José Sequeira41215f2399a9
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 9efb6d9a5021..74efea4f5893 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -760,6 +760,24 @@ jobs:--merge-wide-persons 3 --merge-wide-distinct-ids 1000 --merge-wide-role source \--kill-after 5s --scale-up-after 8s+ # The publish plane: the identity service writes an outbox row for+ # every create, attach, merge and delete, two publisher replicas+ # drain it to per-run topics, and the gate reads the topics back+ # once the outbox is empty. The latest row per distinct id must+ # equal the Postgres mapping, the merge event pairs must equal the+ # merged sources, and every mapping must carry a tombstone after+ # the delete leg, through a leader kill, an identity crash and a+ # publisher crash. Small wide merges keep the pointer cursor busy.+ - name: Run the e2e gate publishing to Kafka under chaos (kill + identity crash + publisher crash)+ run: |+ ./target/debug/personhog-test-harness gate \+ --publish --pg-target-table posthog_person \+ --leaders 3 --partitions 8 --persons 200 \+ --concurrency 10 --duration 15s --merge-concurrency 4 --merge-rate 5 \+ --merge-sources 2 \+ --merge-wide-persons 2 --merge-wide-distinct-ids 500 --merge-wide-role source \+ --kill-after 5s --identity-crash-after 7s --publisher-crash-after 9s+# Regression gate for eviction under writer lag: the cache is# sized far below the person count so dirty entries evict while# the paused writer guarantees their PG rows are stale. Beforediff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.mdindex cc0635ac9aab..2e1dad8efbb3 100644--- a/rust/personhog-test-harness/README.md+++ b/rust/personhog-test-harness/README.md@@ -14,9 +14,11 @@ The docker-compose dev dependencies must be running: Postgres (`posthog_persons`For `gate` without `--external-router-url`, build the service binaries first:```bash-cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-test-harness+cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-identity -p personhog-test-harness```+The identity crate also builds `personhog-publisher`, which `--publish` spawns.+## `gate` — the e2e correctness gateBrings up an isolated stack (replica, writer, N leaders, leader-mode router hosting the coordinator), seeds persons, drives update traffic, verifies strong reads and Postgres, cleans up, and tears down.@@ -110,6 +112,32 @@ target/debug/personhog-test-harness gate --leaders 3 --partitions 8 \--kill-after 5s --scale-up-after 8s```+### Publishing to Kafka++`--publish` adds the plane that feeds ClickHouse and the cohort processor: the spawned identity writes an outbox row for every create, attach, merge and delete, `--publishers` replicas of `personhog-publisher` (default 2, so the claim's `SKIP LOCKED` is contended) drain it to two per-run topics (`personhog_test_harness_<run_id>_distinct_ids` and `_merge_events`, deleted on teardown), and the gate reads the topics back once the outbox is empty.+It implies `--create-via-identity`. The publishers claim every team's rows, so the gate refuses to start while another team has pending outbox rows in the database; clear them or use a dedicated database.++- Distinct ids: after the Postgres quiesce, the highest-version row per distinct id on the topic must equal the Postgres mapping (person uuid, `is_deleted`, version), and no distinct id may be on the topic that Postgres does not hold. Rows repeated at the same version are fine: a replay after a crash is the publisher's contract, and the consumers absorb it. Two different rows at one version are a violation, because a ReplacingMergeTree would keep either.+- Merge events: the set of (old, new) person uuid pairs on the topic must equal the merged sources the merge lane journaled, each event carrying `schema_version` 1, a positive `merged_at_ms` and the key `<team_id>:<old uuid>` the cohort processor places it by. A source whose merge op never settled is excused either way; those are violations already. The event count is printed next to the pair count, so a replay shows in the output without failing the gate.+- Deletes: after the delete leg, Postgres must hold every mapping as a tombstone under the same uuid, and the topic must match those rows exactly, version included.+- The outbox must drain within 60 s after the Postgres quiesce, and again after the delete leg. A row the publisher cannot read stays pending with its `last_error` and is listed when the drain misses its deadline; a row parked by hand (`given_up_at`) is a violation, because only an operator sets it.++`--publish-rows-per-pass` (default 100) keeps `LIFECYCLE_PUBLISH_MAX_ROWS_PER_PASS` small, so a wide merge drains across several passes and the pointer cursor is exercised.+`--publisher-crash-after` crash-restarts one publisher mid-traffic (its in-flight claim rolls back, and whatever it had produced republishes); `--identity-crash-after` crash-restarts the identity service, which the merge lane and the delete leg must survive.++```bash+# Creates, wide merges drained in chunks, deletes, all read back from Kafka+target/debug/personhog-test-harness gate --publish --pg-target-table posthog_person \+ --persons 100 --duration 10s --merge-concurrency 2 --merge-rate 2 \+ --merge-wide-persons 2 --merge-wide-distinct-ids 500++# Through a leader kill, an identity crash and a publisher crash+target/debug/personhog-test-harness gate --publish --pg-target-table posthog_person \+ --leaders 3 --partitions 8 --persons 200 --duration 15s \+ --merge-concurrency 4 --merge-rate 5 --merge-sources 2 \+ --kill-after 5s --identity-crash-after 7s --publisher-crash-after 9s+```+### Chaos disruptionsDisruptions fire mid-traffic, scheduled relative to the start of the traffic phase (spawned stack only).@@ -145,6 +173,10 @@ target/debug/personhog-test-harness gate --leaders 3 --duration 15s --restart-aftarget/debug/personhog-test-harness gate --duration 15s --writer-crash-after 5starget/debug/personhog-test-harness gate --duration 15s --writer-pause-after 3s --writer-pause-duration 8s+# Identity crash-restart while the merge lane runs: in-flight merges lose+# their response and settle from the op record; the delete leg must still work+target/debug/personhog-test-harness gate --merge-concurrency 2 --duration 15s --identity-crash-after 5s+# Kill the coordinator: the kill resolves the live election holder from etcd# (the traffic router never campaigns, so it can never be the target),# revokes the election lease so failover is immediate, and a later handoffdiff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rsindex 218e20e19ed6..a5234024c0ce 100644--- a/rust/personhog-test-harness/src/cli.rs+++ b/rust/personhog-test-harness/src/cli.rs@@ -379,6 +379,40 @@ pub struct GateArgs {#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]pub merge_identified_sources: bool,+ /// Publish through the outbox: the spawned identity writes an outbox+ /// row for every create, attach, merge and delete, `--publishers`+ /// copies of `personhog-publisher` drain it to two per-run topics, and+ /// once the outbox is empty the gate asserts that the latest row per+ /// distinct id on Kafka equals the Postgres mapping, that the merge+ /// events name exactly the merged sources, and that every mapping is+ /// tombstoned after the delete leg. Implies --create-via-identity.+ #[arg(long, default_value_t = false)]+ pub publish: bool,++ /// Publisher replicas with --publish. Two contend on the claim's+ /// `SKIP LOCKED`.+ #[arg(long, default_value_t = 2)]+ pub publishers: u32,++ /// Distinct id rows one publish pass produces at most+ /// (LIFECYCLE_PUBLISH_MAX_ROWS_PER_PASS). Small, so a wide merge drains+ /// across several passes and the pointer cursor is exercised.+ #[arg(long, default_value_t = 100)]+ pub publish_rows_per_pass: i64,++ /// Crash-restart (SIGKILL + respawn) one publisher this long into the+ /// traffic phase. Its in-flight claim rolls back, and whatever it had+ /// already produced is republished. Requires --publish.+ #[arg(long, value_parser = humantime::parse_duration)]+ pub publisher_crash_after: Option<Duration>,++ /// Crash-restart (SIGKILL + respawn) the identity service this long+ /// into the traffic phase. In-flight merges lose their response and+ /// settle from the op record; the sweeper re-drives abandoned sagas.+ /// Requires the identity path.+ #[arg(long, value_parser = humantime::parse_duration)]+ pub identity_crash_after: Option<Duration>,+/// Leave the spawned stack running after the gate finishes (for/// poking at it manually). Ignored with --external-router-url.#[arg(long, default_value_t = false)]diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rsindex 3198d1f66d04..619a1b0da6d2 100644--- a/rust/personhog-test-harness/src/main.rs+++ b/rust/personhog-test-harness/src/main.rs@@ -5,6 +5,7 @@ use tracing_subscriber::EnvFilter;mod cli;mod client;mod pool;+mod publish;mod report;mod scenarios;mod seed;diff --git a/rust/personhog-test-harness/src/publish.rs b/rust/personhog-test-harness/src/publish.rsnew file mode 100644index 000000000000..4d798e4b0111--- /dev/null+++ b/rust/personhog-test-harness/src/publish.rs@@ -0,0 +1,756 @@+//! The publish plane of the gate: what `personhog-publisher` put on Kafka,+//! read back and held against Postgres and the journal. The distinct id+//! topic is compared as a final state, the highest version per distinct+//! id, and the merge events topic as a set of (old, new) pairs, because a+//! replay after a crash legitimately repeats rows and the consumers of+//! both topics absorb that.++use std::collections::{HashMap, HashSet};+use std::time::{Duration, Instant};++use anyhow::{bail, Context, Result};+use serde_json::{json, Value};+use sqlx::postgres::PgPool;+use sqlx::Row;+use uuid::Uuid;++use crate::report::ConsistencyViolation;+use crate::stack::kafka::read_to_end;+use crate::state::MergedSource;++/// How long the outbox may take to drain once traffic has stopped. The+/// publishers poll every 50 ms under a small row budget, so a run's rows+/// drain in seconds; the margin covers a crash-restart mid-drain.+pub const DRAIN_DEADLINE: Duration = Duration::from_secs(60);+const READ_DEADLINE: Duration = Duration::from_secs(30);++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PublishedMapping {+ pub person_uuid: Uuid,+ pub is_deleted: bool,+ pub version: i64,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExpectedMapping {+ pub person_id: i64,+ pub person_uuid: Uuid,+ pub is_deleted: bool,+ pub version: i64,+}++pub struct PublishedMappings {+ pub rows: HashMap<String, PublishedMapping>,+ /// Two rows that differ at the same version, one violation each. A+ /// ReplacingMergeTree keeps whichever arrived last, so the final state+ /// would depend on produce order.+ pub conflicts: Vec<ConsistencyViolation>,+ /// Rows of other teams, which the shared outbox also drains.+ pub foreign_rows: usize,+}++pub struct PublishedMerges {+ pub pairs: HashSet<(Uuid, Uuid)>,+ /// Events read, duplicates included. More events than pairs is a+ /// replay, which only a crash or a produce timeout should cause.+ pub events: usize,+ pub foreign_events: usize,+}++pub struct ExpectedMerges {+ /// Old person uuid to the survivor's uuid.+ pub pairs: HashMap<Uuid, Uuid>,+ /// Sources whose op never settled. Those are violations already, and an+ /// event for one is neither owed nor wrong.+ pub uncertain: HashSet<Uuid>,+ pub ids: HashMap<Uuid, i64>,+}++/// Poll until no row of the team is pending in the outbox, or the deadline+/// passes. A parked row (`given_up_at`) is a violation: only an operator+/// sets it, so a spawned stack must have none. A row the publisher could+/// not read stays pending with its `last_error`, so a deadline miss lists+/// those rows next to the pending count. Returns the drain time.+pub async fn wait_outbox_drained(+ pool: &PgPool,+ outbox_table: &str,+ team_id: i64,+ deadline: Duration,+) -> Result<(Duration, Vec<ConsistencyViolation>)> {+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;+ let counts = format!(+ "SELECT count(*) FILTER (WHERE given_up_at IS NULL) AS pending, \+ count(*) FILTER (WHERE given_up_at IS NOT NULL) AS parked \+ FROM {outbox_table} WHERE team_id = $1"+ );+ let parked_rows = format!(+ "SELECT id, kind, last_error FROM {outbox_table} \+ WHERE team_id = $1 AND given_up_at IS NOT NULL ORDER BY id"+ );+ let deferred_rows = format!(+ "SELECT id, kind, last_error FROM {outbox_table} \+ WHERE team_id = $1 AND given_up_at IS NULL AND last_error IS NOT NULL \+ ORDER BY id LIMIT 20"+ );+ let row_violations = |rows: Vec<sqlx::postgres::PgRow>, key: &str| {+ rows.into_iter()+ .map(|row| {+ let id: i64 = row.get("id");+ let kind: String = row.get("kind");+ let last_error: Option<String> = row.get("last_error");+ ConsistencyViolation {+ person_id: 0,+ key: format!("{key}:{kind}:{id}"),+ expected: json!("published"),+ actual: json!(last_error),+ }+ })+ .collect::<Vec<_>>()+ };+ let start = Instant::now();+ loop {+ let row = sqlx::query(&counts)+ .bind(team)+ .fetch_one(pool)+ .await+ .context("counting outbox rows")?;+ let pending: i64 = row.get("pending");+ let parked: i64 = row.get("parked");+ if pending == 0 {+ let mut violations = Vec::new();+ if parked > 0 {+ let rows = sqlx::query(&parked_rows)+ .bind(team)+ .fetch_all(pool)+ .await+ .context("reading parked outbox rows")?;+ violations.extend(row_violations(rows, "__publish_outbox_parked"));+ }+ return Ok((start.elapsed(), violations));+ }+ if start.elapsed() > deadline {+ let mut violations = vec![ConsistencyViolation {+ person_id: 0,+ key: "__publish_outbox_pending".to_string(),+ expected: json!("0 rows pending"),+ actual: json!(pending),+ }];+ let rows = sqlx::query(&deferred_rows)+ .bind(team)+ .fetch_all(pool)+ .await+ .context("reading deferred outbox rows")?;+ violations.extend(row_violations(rows, "__publish_outbox_deferred"));+ return Ok((start.elapsed(), violations));+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+}++/// Every mapping of the team in Postgres, live or tombstoned, as the row+/// the topic must end on. A mapping without a person row is a Postgres+/// integrity failure, not a publish result, and fails the read outright.+pub async fn expected_mappings(+ pool: &PgPool,+ person_table: &str,+ team_id: i64,+) -> Result<HashMap<String, ExpectedMapping>> {+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;+ let pdi_table = crate::seed::distinct_id_tables_for(person_table)+ .first()+ .context("no distinct id table for the person table")?;+ let query = format!(+ "SELECT d.distinct_id, d.person_id, d.is_deleted, COALESCE(d.version, 0) AS version, \+ p.uuid \+ FROM {pdi_table} d \+ LEFT JOIN {person_table} p ON p.team_id = d.team_id AND p.id = d.person_id \+ WHERE d.team_id = $1"+ );+ let mut expected = HashMap::new();+ for row in sqlx::query(&query)+ .bind(team)+ .fetch_all(pool)+ .await+ .context("reading the distinct id mappings from Postgres")?+ {+ let distinct_id: String = row.get("distinct_id");+ let person_id: i64 = row.get("person_id");+ let person_uuid: Option<Uuid> = row.get("uuid");+ let Some(person_uuid) = person_uuid else {+ bail!("distinct id {distinct_id} maps to person {person_id}, which has no row");+ };+ expected.insert(+ distinct_id,+ ExpectedMapping {+ person_id,+ person_uuid,+ is_deleted: row.get("is_deleted"),+ version: row.get("version"),+ },+ );+ }+ Ok(expected)+}++/// The delete leg's effect on the mappings: every mapping that was live+/// before it is now a tombstone under the same uuid. Without this, the+/// topic comparison after the deletes could pass against mappings the+/// deletes never touched.+pub fn verify_tombstoned_in_postgres(+ before: &HashMap<String, ExpectedMapping>,+ after: &HashMap<String, ExpectedMapping>,+) -> Vec<ConsistencyViolation> {+ let mut violations = Vec::new();+ let mut distinct_ids: Vec<&String> = before.keys().collect();+ distinct_ids.sort();+ for distinct_id in distinct_ids {+ let was = &before[distinct_id];+ let Some(now) = after.get(distinct_id) else {+ violations.push(ConsistencyViolation {+ person_id: was.person_id,+ key: format!("__mapping_gone_after_delete:{distinct_id}"),+ expected: json!("a tombstoned mapping row"),+ actual: Value::Null,+ });+ continue;+ };+ if !now.is_deleted {+ violations.push(ConsistencyViolation {+ person_id: was.person_id,+ key: format!("__mapping_live_after_delete:{distinct_id}"),+ expected: json!("is_deleted"),+ actual: json!(false),+ });+ }+ if now.person_uuid != was.person_uuid {+ violations.push(ConsistencyViolation {+ person_id: was.person_id,+ key: format!("__mapping_owner_changed_by_delete:{distinct_id}"),+ expected: json!(was.person_uuid),+ actual: json!(now.person_uuid),+ });+ }+ }+ violations+}++pub async fn read_published_mappings(+ kafka_hosts: &str,+ topic: &str,+ team_id: i64,+) -> Result<PublishedMappings> {+ let records = read_to_end(kafka_hosts, topic, READ_DEADLINE).await?;+ fold_published_mappings(records.iter().map(|r| r.payload.as_slice()), team_id)+}++/// Fold distinct id rows into the state a ClickHouse reader would see: the+/// highest version per distinct id. Two rows that differ at one version+/// are a conflict whatever the version, because partition order decides+/// which one a reader sees. Rows of other teams are counted and skipped; a+/// row that does not decode is a publisher bug and fails the read outright.+pub fn fold_published_mappings<'a>(+ payloads: impl IntoIterator<Item = &'a [u8]>,+ team_id: i64,+) -> Result<PublishedMappings> {+ let mut rows: HashMap<String, PublishedMapping> = HashMap::new();+ let mut seen: HashMap<(String, i64), PublishedMapping> = HashMap::new();+ let mut conflicted: HashSet<(String, i64)> = HashSet::new();+ let mut conflicts = Vec::new();+ let mut foreign_rows = 0;+ for payload in payloads {+ let value: Value = serde_json::from_slice(payload).context("decoding a distinct id row")?;+ let Some(row_team) = value["team_id"].as_i64() else {+ bail!("distinct id row without an integer team_id");+ };+ if row_team != team_id {+ foreign_rows += 1;+ continue;+ }+ let distinct_id = value["distinct_id"]+ .as_str()+ .context("distinct id row without a distinct_id")?+ .to_string();+ let person_uuid = value["person_id"]+ .as_str()+ .and_then(|s| Uuid::parse_str(s).ok())+ .context("distinct id row without a person uuid")?;+ let version = value["version"]+ .as_i64()+ .context("distinct id row without an integer version")?;+ let is_deleted = match value["is_deleted"].as_u64() {+ Some(0) => false,+ Some(1) => true,+ other => bail!("distinct id row with is_deleted {other:?}, expected 0 or 1"),+ };+ let row = PublishedMapping {+ person_uuid,+ is_deleted,+ version,+ };+ let versioned = (distinct_id.clone(), version);+ match seen.get(&versioned) {+ Some(first) if *first != row && !conflicted.contains(&versioned) => {+ conflicts.push(ConsistencyViolation {+ person_id: 0,+ key: format!("__published_mapping_conflict:{distinct_id}"),+ expected: json!(format!("one row at version {version}")),+ actual: json!([mapping_json(first), mapping_json(&row)]),+ });+ conflicted.insert(versioned);+ }+ Some(_) => {}+ None => {+ seen.insert(versioned, row.clone());+ }+ }+ match rows.get(&distinct_id) {+ Some(current) if current.version >= version => {}+ _ => {+ rows.insert(distinct_id, row);+ }+ }+ }+ Ok(PublishedMappings {+ rows,+ conflicts,+ foreign_rows,+ })+}++fn mapping_json(row: &PublishedMapping) -> Value {+ json!({+ "person_uuid": row.person_uuid,+ "is_deleted": row.is_deleted,+ "version": row.version,+ })+}++pub fn verify_published_mappings(+ expected: &HashMap<String, ExpectedMapping>,+ published: &HashMap<String, PublishedMapping>,+) -> Vec<ConsistencyViolation> {+ let mut violations = Vec::new();+ let mut distinct_ids: Vec<&String> = expected.keys().collect();+ distinct_ids.sort();+ for distinct_id in distinct_ids {+ let want = &expected[distinct_id];+ let Some(got) = published.get(distinct_id) else {+ violations.push(ConsistencyViolation {+ person_id: want.person_id,+ key: format!("__published_mapping_missing:{distinct_id}"),+ expected: json!("a row on the topic"),+ actual: Value::Null,+ });+ continue;+ };+ if got.person_uuid != want.person_uuid {+ violations.push(ConsistencyViolation {+ person_id: want.person_id,+ key: format!("__published_mapping_person:{distinct_id}"),+ expected: json!(want.person_uuid),+ actual: json!(got.person_uuid),+ });+ }+ if got.is_deleted != want.is_deleted {+ violations.push(ConsistencyViolation {+ person_id: want.person_id,+ key: format!("__published_mapping_tombstone:{distinct_id}"),+ expected: json!(want.is_deleted),+ actual: json!(got.is_deleted),+ });+ }+ if got.version != want.version {+ violations.push(ConsistencyViolation {+ person_id: want.person_id,+ key: format!("__published_mapping_version:{distinct_id}"),+ expected: json!(want.version),+ actual: json!(got.version),+ });+ }+ }+ let mut unexpected: Vec<&String> = published+ .keys()+ .filter(|distinct_id| !expected.contains_key(*distinct_id))+ .collect();+ unexpected.sort();+ for distinct_id in unexpected {+ violations.push(ConsistencyViolation {+ person_id: 0,+ key: format!("__published_mapping_unexpected:{distinct_id}"),+ expected: json!("no row: Postgres holds no such mapping"),+ actual: mapping_json(&published[distinct_id]),+ });+ }+ violations+}++/// The merged sources the journal holds, resolved to uuids. The sagas+/// tombstone person rows in place, so every id still has one.+pub async fn expected_merges(+ pool: &PgPool,+ person_table: &str,+ team_id: i64,+ merged: &HashMap<i64, MergedSource>,+ uncertain_ids: &[i64],+) -> Result<ExpectedMerges> {+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;+ let mut person_ids: Vec<i64> = merged+ .iter()+ .flat_map(|(source, edge)| [*source, edge.survivor])+ .chain(uncertain_ids.iter().copied())+ .collect();+ person_ids.sort_unstable();+ person_ids.dedup();+ let query = format!("SELECT id, uuid FROM {person_table} WHERE team_id = $1 AND id = ANY($2)");+ let mut uuids: HashMap<i64, Uuid> = HashMap::new();+ for row in sqlx::query(&query)+ .bind(team)+ .bind(&person_ids)+ .fetch_all(pool)+ .await+ .context("reading person uuids for the merge events")?+ {+ let id: i64 = row.get("id");+ let uuid: Uuid = row.get("uuid");+ uuids.insert(id, uuid);+ }+ let uuid_of = |id: i64| {+ uuids+ .get(&id)+ .copied()+ .with_context(|| format!("person {id} has no row; cannot resolve its merge event"))+ };+ let mut pairs = HashMap::new();+ for (source, edge) in merged {+ pairs.insert(uuid_of(*source)?, uuid_of(edge.survivor)?);+ }+ let mut uncertain = HashSet::new();+ for id in uncertain_ids {+ uncertain.insert(uuid_of(*id)?);+ }+ let ids = uuids.into_iter().map(|(id, uuid)| (uuid, id)).collect();+ Ok(ExpectedMerges {+ pairs,+ uncertain,+ ids,+ })+}++pub async fn read_published_merges(+ kafka_hosts: &str,+ topic: &str,+ team_id: i64,+) -> Result<PublishedMerges> {+ let records = read_to_end(kafka_hosts, topic, READ_DEADLINE).await?;+ fold_published_merges(+ records+ .iter()+ .map(|r| (r.key.as_deref(), r.payload.as_slice())),+ team_id,+ )+}++/// The (old, new) pairs on the merge events topic. Every event must carry+/// the wire shape and the key the cohort stream processor depends on; one+/// that does not is a publisher bug and fails the read outright.+pub fn fold_published_merges<'a>(+ records: impl IntoIterator<Item = (Option<&'a [u8]>, &'a [u8])>,+ team_id: i64,+) -> Result<PublishedMerges> {+ let mut pairs = HashSet::new();+ let mut events = 0;+ let mut foreign_events = 0;+ for (key, payload) in records {+ let value: Value = serde_json::from_slice(payload).context("decoding a merge event")?;+ let Some(event_team) = value["team_id"].as_i64() else {+ bail!("merge event without an integer team_id");+ };+ if event_team != team_id {+ foreign_events += 1;+ continue;+ }+ let uuid = |field: &str| {+ value[field]+ .as_str()+ .and_then(|s| Uuid::parse_str(s).ok())+ .with_context(|| format!("merge event without a {field} uuid"))+ };+ let old = uuid("old_person_uuid")?;+ let new = uuid("new_person_uuid")?;+ if value["schema_version"].as_u64() != Some(1) {+ bail!(+ "merge event with schema_version {}, expected 1",+ value["schema_version"]+ );+ }+ if value["merged_at_ms"].as_i64().is_none_or(|ms| ms <= 0) {+ bail!(+ "merge event with merged_at_ms {}, expected a positive integer",+ value["merged_at_ms"]+ );+ }+ // The processor keeps the old person's state on the worker this+ // key selects, so a different key misplaces the merge silently.+ let expected_key = format!("{team_id}:{old}");+ if key != Some(expected_key.as_bytes()) {+ bail!(+ "merge event {old} -> {new} produced under key {:?}, expected {expected_key:?}",+ key.map(String::from_utf8_lossy)+ );+ }+ events += 1;+ pairs.insert((old, new));+ }+ Ok(PublishedMerges {+ pairs,+ events,+ foreign_events,+ })+}++pub fn verify_published_merges(+ expected: &ExpectedMerges,+ published: &HashSet<(Uuid, Uuid)>,+) -> Vec<ConsistencyViolation> {+ let mut violations = Vec::new();+ let mut pairs: Vec<(&Uuid, &Uuid)> = expected.pairs.iter().collect();+ pairs.sort();+ for (old, new) in pairs {+ if expected.uncertain.contains(old) || published.contains(&(*old, *new)) {+ continue;+ }+ violations.push(ConsistencyViolation {+ person_id: expected.ids.get(old).copied().unwrap_or_default(),+ key: "__published_merge_missing".to_string(),+ expected: json!(format!("merge event {old} -> {new}")),+ actual: Value::Null,+ });+ }+ let mut extra: Vec<&(Uuid, Uuid)> = published+ .iter()+ .filter(|(old, new)| {+ !expected.uncertain.contains(old) && expected.pairs.get(old) != Some(new)+ })+ .collect();+ extra.sort();+ for (old, new) in extra {+ violations.push(ConsistencyViolation {+ person_id: expected.ids.get(old).copied().unwrap_or_default(),+ key: "__published_merge_unexpected".to_string(),+ expected: json!("no merge event: the journal holds no such merge"),+ actual: json!(format!("{old} -> {new}")),+ });+ }+ violations+}++#[cfg(test)]+mod tests {+ use super::*;++ fn keys(violations: Vec<ConsistencyViolation>) -> Vec<String> {+ violations.into_iter().map(|v| v.key).collect()+ }++ fn uuid(n: u128) -> Uuid {+ Uuid::from_u128(n)+ }++ fn mapping(+ person_id: i64,+ person_uuid: Uuid,+ is_deleted: bool,+ version: i64,+ ) -> ExpectedMapping {+ ExpectedMapping {+ person_id,+ person_uuid,+ is_deleted,+ version,+ }+ }++ fn published(person_uuid: Uuid, is_deleted: bool, version: i64) -> PublishedMapping {+ PublishedMapping {+ person_uuid,+ is_deleted,+ version,+ }+ }++ // A verifier that passes on a missing or stale row looks exactly like+ // a healthy publisher, so every disagreement has its own row here.+ #[test]+ fn published_mapping_decision_table() {+ let expected = HashMap::from([("d".to_string(), mapping(7, uuid(1), false, 3))]);+ let check = |row: Option<PublishedMapping>| {+ let topic: HashMap<String, PublishedMapping> =+ row.into_iter().map(|r| ("d".to_string(), r)).collect();+ keys(verify_published_mappings(&expected, &topic))+ };+ assert!(check(Some(published(uuid(1), false, 3))).is_empty());+ assert_eq!(check(None), vec!["__published_mapping_missing:d"]);+ assert_eq!(+ check(Some(published(uuid(1), false, 2))),+ vec!["__published_mapping_version:d"]+ );+ assert_eq!(+ check(Some(published(uuid(1), false, 4))),+ vec!["__published_mapping_version:d"]+ );+ assert_eq!(+ check(Some(published(uuid(2), false, 3))),+ vec!["__published_mapping_person:d"]+ );+ assert_eq!(+ check(Some(published(uuid(1), true, 3))),+ vec!["__published_mapping_tombstone:d"]+ );++ let topic = HashMap::from([+ ("d".to_string(), published(uuid(1), false, 3)),+ ("ghost".to_string(), published(uuid(9), false, 0)),+ ]);+ assert_eq!(+ keys(verify_published_mappings(&expected, &topic)),+ vec!["__published_mapping_unexpected:ghost"]+ );+ }++ // The delete leg must leave every mapping tombstoned in Postgres before+ // the topic is compared again, or the second comparison proves nothing.+ #[test]+ fn tombstoned_in_postgres_decision_table() {+ let before = HashMap::from([("d".to_string(), mapping(7, uuid(1), false, 3))]);+ let check = |after: Option<ExpectedMapping>| {+ let after: HashMap<String, ExpectedMapping> =+ after.into_iter().map(|m| ("d".to_string(), m)).collect();+ keys(verify_tombstoned_in_postgres(&before, &after))+ };+ assert!(check(Some(mapping(7, uuid(1), true, 4))).is_empty());+ assert_eq!(check(None), vec!["__mapping_gone_after_delete:d"]);+ assert_eq!(+ check(Some(mapping(7, uuid(1), false, 3))),+ vec!["__mapping_live_after_delete:d"]+ );+ assert_eq!(+ check(Some(mapping(7, uuid(2), true, 4))),+ vec!["__mapping_owner_changed_by_delete:d"]+ );+ }++ // A crash between the acks and the commit republishes rows; the fold+ // must land on the highest version whatever the order, identical+ // duplicates must not count as anything, and two different rows at one+ // version must, because a ReplacingMergeTree would keep either.+ #[test]+ fn duplicate_and_replayed_rows_fold_to_the_highest_version() {+ let row = |uuid: u128, version: i64, is_deleted: u8| {+ format!(+ r#"{{"person_id":"{}","team_id":5,"distinct_id":"d","version":{version},"is_deleted":{is_deleted}}}"#,+ Uuid::from_u128(uuid)+ )+ };+ let other_team = r#"{"person_id":"00000000-0000-0000-0000-000000000002","team_id":6,"distinct_id":"d","version":9,"is_deleted":0}"#.to_string();+ let payloads = [+ row(1, 1, 0),+ row(1, 2, 0),+ row(1, 2, 0),+ row(1, 1, 0),+ other_team,+ ];+ let folded =+ fold_published_mappings(payloads.iter().map(|p| p.as_bytes()), 5).expect("decodes");+ assert_eq!(+ folded.rows,+ HashMap::from([("d".to_string(), published(uuid(1), false, 2))])+ );+ assert!(folded.conflicts.is_empty());+ assert_eq!(folded.foreign_rows, 1);++ let conflicting = [row(1, 2, 0), row(2, 2, 0), row(1, 3, 0)];+ let folded =+ fold_published_mappings(conflicting.iter().map(|p| p.as_bytes()), 5).expect("decodes");+ assert_eq!(+ keys(folded.conflicts),+ vec!["__published_mapping_conflict:d"]+ );+ assert_eq!(folded.rows["d"].version, 3);+ // The same disagreement read after a higher version is still one.+ let later = [row(1, 3, 0), row(1, 2, 0), row(2, 2, 0), row(2, 2, 0)];+ let folded =+ fold_published_mappings(later.iter().map(|p| p.as_bytes()), 5).expect("decodes");+ assert_eq!(+ keys(folded.conflicts),+ vec!["__published_mapping_conflict:d"]+ );+ assert!(fold_published_mappings(+ [br#"{"person_id":"00000000-0000-0000-0000-000000000001","team_id":"5","distinct_id":"d","version":1,"is_deleted":0}"#.as_slice()],+ 5+ )+ .is_err());++ assert!(+ fold_published_mappings([br#"{"team_id":5,"distinct_id":"d"}"#.as_slice()], 5).is_err()+ );+ assert!(fold_published_mappings([row(1, 3, 2).as_bytes()], 5).is_err());+ }++ #[test]+ fn merge_pair_decision_table() {+ let expected = ExpectedMerges {+ pairs: HashMap::from([(uuid(1), uuid(2))]),+ uncertain: HashSet::from([uuid(3)]),+ ids: HashMap::from([(uuid(1), 1), (uuid(2), 2), (uuid(3), 3)]),+ };+ let check = |pairs: &[(Uuid, Uuid)]| {+ keys(verify_published_merges(+ &expected,+ &pairs.iter().copied().collect(),+ ))+ };+ assert!(check(&[(uuid(1), uuid(2))]).is_empty());+ assert_eq!(check(&[]), vec!["__published_merge_missing"]);+ assert_eq!(+ check(&[(uuid(1), uuid(2)), (uuid(4), uuid(5))]),+ vec!["__published_merge_unexpected"]+ );+ assert_eq!(+ check(&[(uuid(1), uuid(5))]),+ vec!["__published_merge_missing", "__published_merge_unexpected"]+ );+ // An uncertain source may or may not have merged.+ assert!(check(&[(uuid(1), uuid(2)), (uuid(3), uuid(2))]).is_empty());+ }++ // The processor places a merge by its key; an event under another key+ // decodes fine and still lands on the wrong worker.+ #[test]+ fn merge_events_fold_to_pairs_and_keep_their_key() {+ let event = |schema_version: u32, merged_at_ms: i64| {+ format!(+ r#"{{"team_id":5,"old_person_uuid":"{}","new_person_uuid":"{}","merged_at_ms":{merged_at_ms},"schema_version":{schema_version}}}"#,+ uuid(1),+ uuid(2)+ )+ };+ let key = format!("5:{}", uuid(1));+ let keyed = |payload: &str| -> (Option<Vec<u8>>, Vec<u8>) {+ (Some(key.clone().into_bytes()), payload.as_bytes().to_vec())+ };+ let twice = [keyed(&event(1, 10)), keyed(&event(1, 10))];+ let folded =+ fold_published_merges(twice.iter().map(|(k, p)| (k.as_deref(), p.as_slice())), 5)+ .expect("decodes");+ assert_eq!(folded.pairs, HashSet::from([(uuid(1), uuid(2))]));+ assert_eq!(folded.events, 2);++ let bad = |key: Option<&[u8]>, payload: String| {+ fold_published_merges([(key, payload.as_bytes())], 5).is_err()+ };+ assert!(bad(Some(key.as_bytes()), event(2, 10)));+ assert!(bad(Some(key.as_bytes()), event(1, 0)));+ assert!(bad(None, event(1, 10)));+ assert!(bad(Some(b"5:wrong".as_slice()), event(1, 10)));+ }+}diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rsindex 0fa9b7e299cd..650072d47c23 100644--- a/rust/personhog-test-harness/src/scenarios/gate.rs+++ b/rust/personhog-test-harness/src/scenarios/gate.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::fmt;use std::path::{Path, PathBuf};use std::sync::atomic::AtomicBool;@@ -13,11 +13,12 @@ use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;use crate::cli::{GateArgs, DEFAULT_KEYS_PER_PERSON};use crate::client::{HarnessClient, IdentityClient};use crate::pool::TargetPool;-use crate::report::print_report;+use crate::publish;+use crate::report::{print_report, ConsistencyViolation};use crate::scenarios::merge::{self, MergeLane, WideRole};use crate::scenarios::{blast, consistency};use crate::seed;-use crate::stack::{Stack, StackConfig};+use crate::stack::{PublishConfig, Stack, StackConfig};use crate::state::PersonState;use crate::stats::StatsCollector;use crate::verify::verify_postgres;@@ -41,6 +42,8 @@ enum ChaosEvent {RouterShutdown,FencePersons,ReleaseFences,+ PublisherCrash,+ IdentityCrash,}impl fmt::Display for ChaosEvent {@@ -63,6 +66,8 @@ impl fmt::Display for ChaosEvent {ChaosEvent::FencePersons => write!(f, "fence persons (lifecycle delete op)"),ChaosEvent::ReleaseFences => write!(f, "release fences (aborted)"),ChaosEvent::RouterShutdown => write!(f, "coordinator router graceful shutdown"),+ ChaosEvent::PublisherCrash => write!(f, "publisher crash-restart"),+ ChaosEvent::IdentityCrash => write!(f, "identity crash-restart"),}}}@@ -116,6 +121,12 @@ fn chaos_timeline(args: &GateArgs) -> Vec<(Duration, ChaosEvent)> {ChaosEvent::ReleaseFences,));}+ if let Some(after) = args.publisher_crash_after {+ events.push((after, ChaosEvent::PublisherCrash));+ }+ if let Some(after) = args.identity_crash_after {+ events.push((after, ChaosEvent::IdentityCrash));+ }events.sort_by_key(|(after, _)| *after);events}@@ -158,7 +169,8 @@ pub async fn run(args: GateArgs) -> Result<()> {}// Merges need distinct ids. Only the identity create path provides// them.- let create_via_identity = args.create_via_identity || args.merge_concurrency > 0;+ let create_via_identity =+ args.create_via_identity || args.merge_concurrency > 0 || args.publish;if create_via_identity&& args.external_router_url.is_some()&& args.external_identity_url.is_none()@@ -206,6 +218,66 @@ pub async fn run(args: GateArgs) -> Result<()> {if args.fence_after.is_some() && args.fence_count == 0 {bail!("--fence-count must be at least 1 with --fence-after");}+ if args.publish && args.external_router_url.is_some() {+ bail!("--publish requires a spawned stack; it cannot target --external-router-url");+ }+ if args.publish && args.publishers == 0 {+ bail!("--publishers must be at least 1 with --publish");+ }+ if args.publish && args.publish_rows_per_pass <= 0 {+ bail!("--publish-rows-per-pass must be positive");+ }+ if args.publisher_crash_after.is_some() && !args.publish {+ bail!("--publisher-crash-after needs --publish");+ }+ if args.identity_crash_after.is_some() && !create_via_identity {+ bail!(+ "--identity-crash-after needs the identity path (--create-via-identity, \+ --merge-concurrency or --publish)"+ );+ }++ let pool = PgPool::connect(&args.persons_db_url)+ .await+ .context("connecting to persons DB")?;+ let outbox_table = seed::publish_outbox_table_for(&args.pg_target_table);+ let (lifecycle_op, lifecycle_op_person) = seed::lifecycle_tables_for(&args.pg_target_table);++ // A crashed prior run may have left rows behind; the team id belongs to+ // the harness, so start from a clean slate before anything spawns.+ // Lifecycle ops included: a leftover mark would make this run's+ // takeover scan install a stale fence for this team. Outbox rows too:+ // the publishers would drain a previous run's rows onto this run's+ // topics.+ seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;+ sqlx::query(&format!("DELETE FROM {lifecycle_op} WHERE team_id = $1"))+ .bind(args.team_id as i32)+ .execute(&pool)+ .await+ .context("cleaning lifecycle ops")?;+ if args.publish {+ sqlx::query(&format!("DELETE FROM {outbox_table} WHERE team_id = $1"))+ .bind(args.team_id as i32)+ .execute(&pool)+ .await+ .context("cleaning the publish outbox")?;+ // The publishers claim every team's rows, so another team's pending+ // rows would drain onto this run's topics and vanish with them.+ let foreign_pending: i64 = sqlx::query_scalar(&format!(+ "SELECT count(*) FROM {outbox_table} WHERE given_up_at IS NULL AND team_id <> $1"+ ))+ .bind(args.team_id as i32)+ .fetch_one(&pool)+ .await+ .context("counting other teams' outbox rows")?;+ if foreign_pending > 0 {+ bail!(+ "{foreign_pending} pending outbox rows belong to other teams and the harness \+ publishers would drain them onto this run's topics; clear {outbox_table} or \+ use a dedicated persons database for --publish"+ );+ }+ }let mut stack = match &args.external_router_url {Some(_) => None,@@ -227,39 +299,114 @@ pub async fn run(args: GateArgs) -> Result<()> {recovery_pool_size: args.recovery_pool_size,leader_lease_ttl: args.leader_lease_ttl,spawn_identity: create_via_identity,+ publish: args.publish.then_some(PublishConfig {+ publishers: args.publishers,+ rows_per_pass: args.publish_rows_per_pass,+ }),}).await?,)}};- let router_url = match (&args.external_router_url, &stack) {+ let outcome = run_gate(+ GateContext {+ args: &args,+ pool: &pool,+ outbox_table,+ lifecycle_op,+ lifecycle_op_person,+ create_via_identity,+ },+ &mut stack,+ wide_role,+ chaos,+ )+ .await;++ // Teardown runs whatever the gate found, so a failed verification does+ // not leave the per-run topics behind. Only a passing run honors+ // --keep-stack.+ if let Some(stack) = stack {+ match &outcome {+ Ok(_) if args.keep_stack => {+ println!(+ "Stack left running (logs at {}); services die with this process",+ stack.log_dir.display()+ );+ // Hold the stack (and its kill-on-drop children) until the user+ // interrupts, since child processes die with the harness.+ tokio::signal::ctrl_c().await?;+ stack.down().await?;+ }+ Ok(_) => stack.down().await?,+ Err(_) => {+ if let Err(e) = stack.down().await {+ tracing::warn!(error = %e, "stack teardown failed after the gate failed");+ }+ }+ }+ }++ let run = outcome?;+ if !run.violations.is_empty() {+ bail!("{} consistency violations detected", run.violations.len());+ }+ // The invariant is "acked implies visible", which zero acks satisfy+ // vacuously — a stack that failed every write must not pass the gate.+ if run.acked_writes == 0 {+ bail!("no writes were acked; the gate asserted nothing");+ }+ println!("Gate passed: every acked write visible in strong reads and Postgres");+ Ok(())+}++struct GateContext<'a> {+ args: &'a GateArgs,+ pool: &'a PgPool,+ outbox_table: &'static str,+ lifecycle_op: &'static str,+ lifecycle_op_person: &'static str,+ create_via_identity: bool,+}++struct GateRun {+ violations: Vec<ConsistencyViolation>,+ acked_writes: u64,+}++/// Everything between stack bring-up and teardown: seed, traffic, chaos,+/// verification, the delete leg and the data cleanup. Apart from `run` so+/// the stack comes down whatever this returns.+async fn run_gate(+ ctx: GateContext<'_>,+ stack: &mut Option<Stack>,+ wide_role: WideRole,+ chaos: Vec<(Duration, ChaosEvent)>,+) -> Result<GateRun> {+ let GateContext {+ args,+ pool,+ outbox_table,+ lifecycle_op,+ lifecycle_op_person,+ create_via_identity,+ } = ctx;+ let router_url = match (&args.external_router_url, &*stack) {(Some(url), _) => url.clone(),(None, Some(stack)) => stack.router_url.clone(),(None, None) => unreachable!(),};let client = HarnessClient::connect(&router_url).await?;+ let publish_topics = stack+ .as_ref()+ .and_then(|stack| stack.publish_topics().cloned());- let pool = PgPool::connect(&args.persons_db_url)- .await- .context("connecting to persons DB")?;-- // A crashed prior run may have left rows behind; the team id belongs to- // the harness, so start from a clean slate. Lifecycle ops included: a- // leftover mark would make a later run's takeover scan install a stale- // fence for this team.- seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;- let (lifecycle_op, lifecycle_op_person) = seed::lifecycle_tables_for(&args.pg_target_table);- sqlx::query(&format!("DELETE FROM {lifecycle_op} WHERE team_id = $1"))- .bind(args.team_id as i32)- .execute(&pool)- .await- .context("cleaning lifecycle ops")?;let state = PersonState::new();// A spawned stack always uses its own identity service — the gate's// assertions target that stack, so an external identity service pointed// elsewhere would only produce confusing failures.- let identity_url = match (&args.external_identity_url, &stack) {+ let identity_url = match (&args.external_identity_url, &*stack) {_ if !create_via_identity => None,(_, Some(stack)) => stack.identity_url.clone(),(Some(url), None) => Some(url.clone()),@@ -280,8 +427,8 @@ pub async fn run(args: GateArgs) -> Result<()> {ids}None => {- let ids = seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.persons)- .await?;+ let ids =+ seed::seed_persons(pool, &args.pg_target_table, args.team_id, args.persons).await?;println!("Seeded {} persons for team {}", ids.len(), args.team_id);ids}@@ -444,7 +591,7 @@ pub async fn run(args: GateArgs) -> Result<()> {)).bind(fence_op).bind(args.team_id as i32)- .execute(&pool)+ .execute(pool).await.context("inserting fence op row")?;for &person_id in person_ids.snapshot().iter().take(args.fence_count) {@@ -456,7 +603,7 @@ pub async fn run(args: GateArgs) -> Result<()> {.bind(fence_op).bind(args.team_id as i32).bind(person_id)- .execute(&pool)+ .execute(pool).await.context("inserting fence mark")?;}@@ -511,14 +658,14 @@ pub async fn run(args: GateArgs) -> Result<()> {"UPDATE {lifecycle_op_person} SET status = 'skipped_conflict' WHERE op_id = $1")).bind(fence_op)- .execute(&pool)+ .execute(pool).await.context("settling fence marks")?;sqlx::query(&format!("UPDATE {lifecycle_op} SET step = 'aborted', completed_at = now() WHERE op_id = $1")).bind(fence_op)- .execute(&pool)+ .execute(pool).await.context("completing fence op")?;println!(@@ -552,6 +699,14 @@ pub async fn run(args: GateArgs) -> Result<()> {}ChaosEvent::RouterKill { fast } => Some(stack.kill_coordinator_router(fast).await?),ChaosEvent::RouterShutdown => Some(stack.shutdown_coordinator_router().await?),+ ChaosEvent::PublisherCrash => {+ stack.crash_restart_publisher().await?;+ None+ }+ ChaosEvent::IdentityCrash => {+ stack.crash_restart_identity().await?;+ None+ }ChaosEvent::FencePersons | ChaosEvent::ReleaseFences => {unreachable!("fence events are dispatched before the stack match")}@@ -618,7 +773,7 @@ pub async fn run(args: GateArgs) -> Result<()> {let mut violations = prober_violations;violations.extend(merge::settle_unresolved(- &pool,+ pool,&args.pg_target_table,&state,unresolved_merges,@@ -636,15 +791,60 @@ pub async fn run(args: GateArgs) -> Result<()> {let journal = state.snapshot().await;let merged = state.snapshot_merged().await;violations.extend(- verify_postgres(- &pool,+ verify_postgres(pool, &args.pg_target_table, args.team_id, &journal, &merged).await?,+ );++ // The publish plane: once the outbox has drained, the topics must hold+ // the Postgres mappings and the journaled merges. This pass compares+ // the live mappings; the delete leg below turns them into tombstones,+ // which the second pass compares.+ let mut publish_expected = None;+ if let Some(topics) = &publish_topics {+ println!("Waiting for the publish outbox to drain, then verifying Kafka...");+ let (drained_in, outbox_violations) =+ publish::wait_outbox_drained(pool, outbox_table, args.team_id, publish::DRAIN_DEADLINE)+ .await?;+ println!(" Outbox drained in {:.1}s", drained_in.as_secs_f64());+ // A publisher that died mid-drain is hidden by its replica.+ if let Some(stack) = stack.as_mut() {+ stack.check_alive()?;+ }+ violations.extend(outbox_violations);+ let expected =+ publish::expected_mappings(pool, &args.pg_target_table, args.team_id).await?;+ let publish::PublishedMappings {+ rows,+ conflicts,+ foreign_rows,+ } = publish::read_published_mappings(&args.kafka_hosts, &topics.distinct_ids, args.team_id)+ .await?;+ violations.extend(conflicts);+ violations.extend(publish::verify_published_mappings(&expected, &rows));+ let uncertain = state.merge_uncertain_ids().await;+ let expected_merges = publish::expected_merges(+ pool,&args.pg_target_table,args.team_id,- &journal,&merged,+ &uncertain,)- .await?,- );+ .await?;+ let published_merges =+ publish::read_published_merges(&args.kafka_hosts, &topics.merge_events, args.team_id)+ .await?;+ violations.extend(publish::verify_published_merges(+ &expected_merges,+ &published_merges.pairs,+ ));+ println!(+ " {} mappings and {} merge events for {} pairs read back from Kafka ({foreign_rows} rows and {} events of other teams skipped)",+ rows.len(),+ published_merges.events,+ published_merges.pairs.len(),+ published_merges.foreign_events+ );+ publish_expected = Some(expected);+ }print_report("gate", &collector, args.team_id, created_count, &violations);let mut disputed: HashMap<i64, Vec<String>> = HashMap::new();@@ -687,36 +887,65 @@ pub async fn run(args: GateArgs) -> Result<()> {}}- if !args.keep_data {- let persons = seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;- println!("Cleaned up {persons} persons");- }-- if let Some(stack) = stack {- if args.keep_stack {+ if let (Some(before), Some(topics), false) =+ (&publish_expected, &publish_topics, args.keep_data)+ {+ println!(+ "Waiting for the publish outbox to drain, then verifying the tombstones on Kafka..."+ );+ let (drained_in, outbox_violations) =+ publish::wait_outbox_drained(pool, outbox_table, args.team_id, publish::DRAIN_DEADLINE)+ .await?;+ println!(" Outbox drained in {:.1}s", drained_in.as_secs_f64());+ if let Some(stack) = stack.as_mut() {+ stack.check_alive()?;+ }+ // Rows parked before the first pass were reported there.+ let reported: HashSet<String> = violations.iter().map(|v| v.key.clone()).collect();+ let mut late: Vec<_> = outbox_violations+ .into_iter()+ .filter(|v| !reported.contains(&v.key))+ .collect();+ let after = publish::expected_mappings(pool, &args.pg_target_table, args.team_id).await?;+ late.extend(publish::verify_tombstoned_in_postgres(before, &after));+ let published =+ publish::read_published_mappings(&args.kafka_hosts, &topics.distinct_ids, args.team_id)+ .await?;+ late.extend(published.conflicts);+ late.extend(publish::verify_published_mappings(&after, &published.rows));+ if late.is_empty() {println!(- "Stack left running (logs at {}); services die with this process",- stack.log_dir.display()+ " Every one of {} mappings tombstoned on Kafka at the version Postgres holds",+ before.len());- // Hold the stack (and its kill-on-drop children) until the user- // interrupts, since child processes die with the harness.- tokio::signal::ctrl_c().await?;- stack.down().await?;} else {- stack.down().await?;+ println!(" {} publish violations after the delete leg:", late.len());+ for violation in late.iter().take(20) {+ println!(+ " person {} {}: expected {} actual {}",+ violation.person_id, violation.key, violation.expected, violation.actual+ );+ }}+ violations.extend(late);}- if !violations.is_empty() {- bail!("{} consistency violations detected", violations.len());- }- // The invariant is "acked implies visible", which zero acks satisfy- // vacuously — a stack that failed every write must not pass the gate.- if collector.writes.snapshot().successes == 0 {- bail!("no writes were acked; the gate asserted nothing");+ if !args.keep_data {+ let persons = seed::cleanup_team(pool, &args.pg_target_table, args.team_id).await?;+ println!("Cleaned up {persons} persons");+ if args.publish {+ sqlx::query(&format!("DELETE FROM {outbox_table} WHERE team_id = $1"))+ .bind(args.team_id as i32)+ .execute(pool)+ .await+ .context("cleaning the publish outbox")?;+ }}- println!("Gate passed: every acked write visible in strong reads and Postgres");- Ok(())++ Ok(GateRun {+ violations,+ acked_writes: collector.writes.snapshot().successes,+ })}/// Delete `person_ids` through the lifecycle saga and hold the answers@@ -982,6 +1211,8 @@ mod tests {"2s","--writer-pause-duration","1s",+ "--publisher-crash-after",+ "4s",]);let rendered: Vec<(u64, String)> = chaos_timeline(&args).iter()@@ -990,6 +1221,7 @@ mod tests {let expected: Vec<(u64, String)> = [(2, "writer pause (lag injection)"),(3, "writer resume"),+ (4, "publisher crash-restart"),(5, "graceful shutdown"),(7, "zombie stop (SIGSTOP + lease revoke)"),(10, "kill (fast lease revoke)"),diff --git a/rust/personhog-test-harness/src/stack/kafka.rs b/rust/personhog-test-harness/src/stack/kafka.rsindex 803ebe895359..38cf5a1bdf97 100644--- a/rust/personhog-test-harness/src/stack/kafka.rs+++ b/rust/personhog-test-harness/src/stack/kafka.rs@@ -1,10 +1,15 @@-use std::time::Duration;+use std::collections::HashMap;+use std::time::{Duration, Instant};use anyhow::{bail, Context, Result};use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};use rdkafka::client::DefaultClientContext;use rdkafka::config::ClientConfig;+use rdkafka::consumer::{BaseConsumer, Consumer};+use rdkafka::error::KafkaError;+use rdkafka::message::Message;use rdkafka::types::RDKafkaErrorCode;+use rdkafka::{Offset, TopicPartitionList};fn admin_client(kafka_hosts: &str) -> Result<AdminClient<DefaultClientContext>> {ClientConfig::new()@@ -13,10 +18,10 @@ fn admin_client(kafka_hosts: &str) -> Result<AdminClient<DefaultClientContext>>.context("creating kafka admin client")}-/// Create the changelog topic with exactly `partitions` partitions. The-/// partition count must match `total_partitions` in etcd — a mismatch is a-/// silent mis-shard — so an existing topic with a different count is an-/// error rather than something to adopt.+/// Create a per-run topic with exactly `partitions` partitions. For the+/// changelog the count must match `total_partitions` in etcd — a mismatch+/// is a silent mis-shard — so an existing topic with a different count is+/// an error rather than something to adopt.pub async fn create_topic(kafka_hosts: &str, topic: &str, partitions: u32) -> Result<()> {let admin = admin_client(kafka_hosts)?;let options = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));@@ -25,7 +30,7 @@ pub async fn create_topic(kafka_hosts: &str, topic: &str, partitions: u32) -> Relet results = admin.create_topics([&new_topic], &options).await- .context("creating changelog topic")?;+ .context("creating topic")?;for result in results {match result {@@ -40,7 +45,7 @@ pub async fn create_topic(kafka_hosts: &str, topic: &str, partitions: u32) -> Re}}- tracing::info!(topic, partitions, "created changelog topic");+ tracing::info!(topic, partitions, "created topic");Ok(())}@@ -51,7 +56,7 @@ pub async fn delete_topic(kafka_hosts: &str, topic: &str) -> Result<()> {let results = admin.delete_topics(&[topic], &options).await- .context("deleting changelog topic")?;+ .context("deleting topic")?;for result in results {match result {@@ -60,6 +65,108 @@ pub async fn delete_topic(kafka_hosts: &str, topic: &str) -> Result<()> {}}- tracing::info!(topic, "deleted changelog topic");+ tracing::info!(topic, "deleted topic");Ok(())}++pub struct KafkaRecord {+ pub key: Option<Vec<u8>>,+ pub payload: Vec<u8>,+}++/// Every record on `topic`, from the beginning of each partition up to the+/// high watermark captured when the read starts, so a producer still+/// writing cannot make the read run on. Nothing is committed, so no+/// consumer group state is left behind. The deadline only bounds a+/// partition that stops delivering.+pub async fn read_to_end(+ kafka_hosts: &str,+ topic: &str,+ deadline: Duration,+) -> Result<Vec<KafkaRecord>> {+ let kafka_hosts = kafka_hosts.to_string();+ let topic = topic.to_string();+ tokio::task::spawn_blocking(move || read_to_end_blocking(&kafka_hosts, &topic, deadline))+ .await+ .context("kafka read task panicked")?+}++fn read_to_end_blocking(+ kafka_hosts: &str,+ topic: &str,+ deadline: Duration,+) -> Result<Vec<KafkaRecord>> {+ let consumer: BaseConsumer = ClientConfig::new()+ .set("bootstrap.servers", kafka_hosts)+ .set("group.id", "personhog-test-harness-reader")+ .set("enable.auto.commit", "false")+ .set("enable.partition.eof", "true")+ .set("auto.offset.reset", "earliest")+ .create()+ .context("creating kafka reader")?;++ let metadata = consumer+ .fetch_metadata(Some(topic), Duration::from_secs(10))+ .context("fetching topic metadata")?;+ let partitions: Vec<i32> = metadata+ .topics()+ .iter()+ .find(|t| t.name() == topic)+ .map(|t| t.partitions().iter().map(|p| p.id()).collect())+ .with_context(|| format!("topic {topic} has no metadata"))?;++ let mut remaining: HashMap<i32, i64> = HashMap::new();+ let mut assignment = TopicPartitionList::new();+ for partition in partitions {+ let (low, high) = consumer+ .fetch_watermarks(topic, partition, Duration::from_secs(10))+ .with_context(|| format!("fetching watermarks of {topic}/{partition}"))?;+ if high > low {+ remaining.insert(partition, high);+ assignment.add_partition_offset(topic, partition, Offset::Beginning)?;+ }+ }+ if remaining.is_empty() {+ return Ok(Vec::new());+ }+ consumer+ .assign(&assignment)+ .context("assigning partitions")?;++ let start = Instant::now();+ let mut records = Vec::new();+ while !remaining.is_empty() {+ if start.elapsed() > deadline {+ bail!(+ "reading {topic} did not reach the high watermark within {deadline:?}; \+ partitions left: {:?}",+ remaining+ );+ }+ match consumer.poll(Duration::from_millis(200)) {+ None => {}+ Some(Err(KafkaError::PartitionEOF(partition))) => {+ remaining.remove(&partition);+ }+ Some(Err(e)) => bail!("reading {topic}: {e}"),+ Some(Ok(message)) => {+ let partition = message.partition();+ let Some(high) = remaining.get(&partition).copied() else {+ continue;+ };+ if message.offset() >= high {+ remaining.remove(&partition);+ continue;+ }+ records.push(KafkaRecord {+ key: message.key().map(<[u8]>::to_vec),+ payload: message.payload().unwrap_or_default().to_vec(),+ });+ if message.offset() + 1 >= high {+ remaining.remove(&partition);+ }+ }+ }+ }+ Ok(records)+}diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rsindex 1f9804060b36..32d54670e524 100644--- a/rust/personhog-test-harness/src/stack/mod.rs+++ b/rust/personhog-test-harness/src/stack/mod.rs@@ -8,7 +8,7 @@ use personhog_coordination::store::PersonhogStore;use personhog_coordination::types::HandoffPhase;mod etcd;-mod kafka;+pub(crate) mod kafka;mod process;use process::ServiceProcess;@@ -33,7 +33,12 @@ const IDENTITY_METRICS_PORT: u16 = 24152;const WRITER_METRICS_PORT: u16 = 24153;const ROUTER_METRICS_BASE_PORT: u16 = 24154;const LEADER_METRICS_BASE_PORT: u16 = 24160;+/// Above the leader range, which grows with every scale-up.+const PUBLISHER_METRICS_BASE_PORT: u16 = 24200;const MAX_ROUTERS: u32 = 4;+/// Partitions of the two per-run publish topics. More than one, so the+/// keyed merge events spread the way they do in production.+const PUBLISH_TOPIC_PARTITIONS: u32 = 4;const ETCD_PREFIX: &str = "/personhog-test-harness/";const READY_DEADLINE: Duration = Duration::from_secs(90);@@ -67,6 +72,21 @@ pub struct StackConfig {/// router for its initial-properties writes. Only needed when the run/// creates persons through the identity path.pub spawn_identity: bool,+ /// Also spawn `personhog-publisher` replicas that drain the outbox the+ /// identity service writes, to two per-run topics. Needs+ /// `spawn_identity`: nothing else writes the outbox.+ pub publish: Option<PublishConfig>,+}++pub struct PublishConfig {+ pub publishers: u32,+ pub rows_per_pass: i64,+}++#[derive(Clone)]+pub struct PublishTopics {+ pub distinct_ids: String,+ pub merge_events: String,}/// A locally-spawned personhog stack: replica, writer, N leaders, and M@@ -103,6 +123,7 @@ pub struct Stack {/// Set when the stack spawned a personhog-identity service: the traffic/// router's URL, which proxies identity RPCs to it.pub identity_url: Option<String>,+ publish_topics: Option<PublishTopics>,pub log_dir: PathBuf,}@@ -139,6 +160,9 @@ impl Stack {if config.routers == 0 || config.routers > MAX_ROUTERS {bail!("--routers must be between 1 and {MAX_ROUTERS}");}+ if config.publish.is_some() && !config.spawn_identity {+ bail!("publishing needs the identity service: nothing else writes the outbox");+ }let run_id = chrono::Utc::now().format("%Y%m%d_%H%M%S").to_string();let topic = format!("personhog_test_harness_{run_id}");@@ -155,6 +179,9 @@ impl Stack {if config.spawn_identity {binaries.push("personhog-identity");}+ if config.publish.is_some() {+ binaries.push("personhog-publisher");+ }for bin in &binaries {let path = config.bin_dir.join(bin);if !path.exists() {@@ -178,6 +205,28 @@ impl Stack {let store = etcd::connect(&config.etcd_endpoints, ETCD_PREFIX).await?;etcd::reset(&store, config.partitions).await?;kafka::create_topic(&config.kafka_hosts, &topic, config.partitions).await?;+ let publish_topics = match &config.publish {+ Some(_) => {+ let topics = PublishTopics {+ distinct_ids: format!("{topic}_distinct_ids"),+ merge_events: format!("{topic}_merge_events"),+ };+ kafka::create_topic(+ &config.kafka_hosts,+ &topics.distinct_ids,+ PUBLISH_TOPIC_PARTITIONS,+ )+ .await?;+ kafka::create_topic(+ &config.kafka_hosts,+ &topics.merge_events,+ PUBLISH_TOPIC_PARTITIONS,+ )+ .await?;+ Some(topics)+ }+ None => None,+ };let mut infra = Vec::new();@@ -305,9 +354,59 @@ impl Stack {// interval fits a short run.("LIFECYCLE_SWEEPER_ENABLED", "true".to_string()),("LIFECYCLE_SWEEP_INTERVAL_SECS", "3".to_string()),+ (+ "LIFECYCLE_OUTBOX_ENABLED",+ config.publish.is_some().to_string(),+ ),],&log_dir,)?);+ if let (Some(publish), Some(topics)) = (&config.publish, &publish_topics) {+ for i in 0..publish.publishers {+ infra.push(ServiceProcess::spawn(+ &format!("publisher-{i}"),+ &config.bin_dir.join("personhog-publisher"),+ &[+ ("PRIMARY_DATABASE_URL", config.persons_db_url.clone()),+ ("PERSON_TABLE", config.pg_target_table.clone()),+ (+ "PERSON_DISTINCT_ID_TABLE",+ companions.person_distinct_id.to_string(),+ ),+ (+ "FF_HASH_KEY_OVERRIDE_TABLE",+ companions.ff_hash_key_override.to_string(),+ ),+ ("LIFECYCLE_OP_TABLE", companions.lifecycle_op.to_string()),+ (+ "LIFECYCLE_OP_PERSON_TABLE",+ companions.lifecycle_op_person.to_string(),+ ),+ (+ "PERSON_PUBLISH_OUTBOX_TABLE",+ companions.person_publish_outbox.to_string(),+ ),+ ("KAFKA_HOSTS", config.kafka_hosts.clone()),+ ("PERSON_DISTINCT_ID_TOPIC", topics.distinct_ids.clone()),+ ("PERSON_MERGE_EVENTS_ENABLED", "true".to_string()),+ ("PERSON_MERGE_EVENTS_TOPIC", topics.merge_events.clone()),+ ("PERSON_MERGE_EVENTS_TEAM_ALLOWLIST", "*".to_string()),+ (+ "LIFECYCLE_PUBLISH_MAX_ROWS_PER_PASS",+ publish.rows_per_pass.to_string(),+ ),+ // A short idle poll, so the drain after traffic+ // is bounded by the row budget, not the poll.+ ("LIFECYCLE_PUBLISH_INTERVAL_MS", "50".to_string()),+ (+ "METRICS_PORT",+ (PUBLISHER_METRICS_BASE_PORT + i as u16).to_string(),+ ),+ ],+ &log_dir,+ )?);+ }+ }Some(router_url.clone())} else {None@@ -325,6 +424,7 @@ impl Stack {topic,router_url,identity_url,+ publish_topics,log_dir,};@@ -591,6 +691,27 @@ impl Stack {Ok(())}+ pub fn publish_topics(&self) -> Option<&PublishTopics> {+ self.publish_topics.as_ref()+ }++ /// Crash-restart the first publisher: SIGKILL + respawn. Its in-flight+ /// claim rolls back, so the rows stay pending for the other replica or+ /// the respawn, and whatever it had already produced republishes.+ pub async fn crash_restart_publisher(&mut self) -> Result<()> {+ self.infra_mut("publisher-0")?.respawn().await?;+ tracing::info!("crash-restarted publisher");+ Ok(())+ }++ /// Crash-restart the identity service: SIGKILL + respawn. In-flight+ /// RPCs fail unacked; a saga mid-flight is re-driven by the sweeper.+ pub async fn crash_restart_identity(&mut self) -> Result<()> {+ self.infra_mut("identity")?.respawn().await?;+ tracing::info!("crash-restarted identity");+ Ok(())+ }+/// Wait (up to `deadline`) for a handoff to appear in flight, then/// SIGKILL its target pod mid-handoff. Best effort: fast handoffs can/// complete between polls, in which case nothing is killed.@@ -815,8 +936,23 @@ impl Stack {.map(|proc| proc.terminate(SHUTDOWN_GRACE));futures::future::join_all(terminations).await;- kafka::delete_topic(&self.config.kafka_hosts, &self.topic).await?;- Ok(())+ // Every topic is attempted even when one delete fails, so a failed+ // teardown leaves at most that one topic behind.+ let mut topics = vec![self.topic.as_str()];+ if let Some(publish) = &self.publish_topics {+ topics.push(publish.distinct_ids.as_str());+ topics.push(publish.merge_events.as_str());+ }+ let mut first_error = None;+ for topic in topics {+ if let Err(e) = kafka::delete_topic(&self.config.kafka_hosts, topic).await {+ first_error.get_or_insert(e);+ }+ }+ match first_error {+ Some(e) => Err(e),+ None => Ok(()),+ }}}