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): e2e test harness for ci (#70797)

Zach Brown091d681d2c1d
diff --git a/.agents/skills/extending-personhog-test-harness/SKILL.md b/.agents/skills/extending-personhog-test-harness/SKILL.md
new file mode 100644
index 000000000000..f86070b7b934
--- /dev/null
+++ b/.agents/skills/extending-personhog-test-harness/SKILL.md
@@ -0,0 +1,87 @@
+---
+name: extending-personhog-test-harness
+description: >
+ When and how to add scenarios, chaos events, and invariants to the personhog
+ e2e test harness (rust/personhog-test-harness). Use after fixing a bug or
+ regression in the personhog leader path (leader, router, writer, replica,
+ coordination protocol) so the fix gets a permanent regression scenario; when
+ adding a new failure mode to test (crashes, drains, zombies, lag, failover);
+ or when a new correctness property needs asserting during runs. Trigger
+ terms: personhog gate, chaos scenario, test harness, leader path regression,
+ handoff bug, eviction, writer lag, acked write.
+---
+
+# Extending the personhog test harness
+
+The harness (`rust/personhog-test-harness/`, see its README for usage) spawns a
+real personhog stack and asserts one invariant three ways: **every acked write
+is visible afterwards** — live via read-your-write probers, at end-of-run via
+strong reads, and durably via Postgres at the acked version. It has caught real
+bugs (eviction data loss, unordered lifecycle shutdown, coordinator failover
+stalls) precisely because chaos scenarios run against those assertions.
+
+## When to add a scenario
+
+Add one whenever you fix a personhog bug whose _trigger_ the harness can
+reproduce — a crash, drain, restart, lag, election, or eviction condition. The
+fix's PR should show the scenario red before the fix and green after; that run
+becomes the permanent regression test. Also add one when introducing a new
+failure mode (a new process to disrupt, a new timing window) or a new
+correctness property (a new journal check).
+
+Don't add scenarios for behavior already covered by an existing flag
+combination — compose existing flags instead — and don't add unit-testable
+logic here: the harness is for whole-stack behavior only.
+
+## Where things live
+
+- `src/cli.rs` — every scenario is driven by `GateArgs` flags.
+- `src/scenarios/gate.rs` — `ChaosEvent` enum, `chaos_timeline()` (offset-sorted
+ events, paired stop/resume events), the dispatch loop, and verification
+ ordering (probers → regressions → strong reads → Postgres quiesce).
+- `src/stack/mod.rs` — stack primitives: spawn/kill/restart leaders (SIGKILL,
+ SIGTERM drain, SIGSTOP/SIGCONT zombie), writer crash/pause, coordinator
+ kill, etcd lease revocation, per-service env. New disruptions are new
+ methods here.
+- `src/state.rs` — the acked-write journal and its verifiers. New invariants go
+ here, and their decision tables get unit tests: a false-negative verifier
+ looks identical to a healthy stack, so e2e runs cannot reveal it.
+- `README.md` — every scenario gets a runnable example; scenarios that stay red
+ because of a known unfixed defect go in the "Known defects" section with
+ their observable signature and fix direction.
+
+## Adding a chaos scenario
+
+1. Add the stack primitive if the disruption is new (prefer process signals
+ and etcd operations; never disrupt the shared docker containers — they
+ also serve the dev stack).
+2. Add the `GateArgs` flag, the `ChaosEvent` variant, and its
+ `chaos_timeline()` entry. Timed events take an offset; paired disruptions
+ (pause/resume) schedule both entries. State-triggered events (like
+ `--kill-handoff-target`) poll etcd after their triggering event instead.
+3. Guard invalid combinations in `gate.rs` with an early `bail!` (for example,
+ coordinator kill requires two routers).
+4. Rehearse locally until deterministic — three consecutive green runs is the
+ bar (see the README for build and docker prerequisites). If timing makes a
+ scenario a lottery, make it deterministic (the coordinator election is
+ forced at bring-up for exactly this reason) rather than accepting flakes.
+5. Only failed-but-unacked requests are tolerable during chaos; the invariant
+ machinery needs no changes for a new disruption unless you're adding a new
+ _property_, in which case journal it in `state.rs` with unit tests.
+6. Add the scenario to the `personhog-gate` CI job in
+ `.github/workflows/ci-rust.yml` once rehearsed — extend an existing
+ composite run if compatible (keep runs to roughly three disruption kinds so
+ failures stay diagnosable), or add a step. Expected-red scenarios
+ (documenting a known defect) stay out of CI until the defect is fixed.
+
+## Validating a fix with the harness
+
+Run the harness binary against binaries built from the fix branch:
+
+```bash
+cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer
+personhog-test-harness gate <scenario flags> --bin-dir <fix-worktree>/rust/target/debug
+```
+
+Show the same command red on the base branch and green on the fix in the PR's
+testing section.
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index b5e70775aad1..242f995e09c0 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -472,6 +472,146 @@ jobs:
org-slug: posthog-inc
token: ${{ secrets.TRUNK_API_TOKEN }}
+ # Spawns a real personhog stack (replica, writer, leaders, leader-mode
+ # routers) against dockerized Postgres/Kafka/etcd and asserts that every
+ # write acked by the leader path is visible afterwards — in strong reads
+ # and in Postgres at the acked version — including under chaos: leader
+ # kill (lease-revoked and TTL-expiry), scale-up, graceful drain, zombie
+ # (SIGSTOP/SIGCONT), writer crash and lag, same-identity restart,
+ # coordinator failover, and a mid-handoff target kill. Not a required
+ # check while it soaks.
+ personhog-gate:
+ name: PersonHog e2e gate
+ needs: [changes, affected]
+ # Gated on the affected computation: a determinator package-rule
+ # marks the harness affected whenever a personhog service it spawns
+ # changes, so unrelated rust PRs skip the job entirely.
+ if: needs.changes.outputs.rust == 'true' && contains(needs.affected.outputs.affected_crates, 'personhog-test-harness')
+ runs-on: depot-ubuntu-24.04-4
+ timeout-minutes: 25
+ permissions:
+ contents: read
+ env:
+ DOCKERHUB_USERNAME: ${{ vars.DOCKERHUB_USER }}
+ DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ defaults:
+ run:
+ working-directory: rust
+
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ clean: false
+
+ - name: Log in to Docker Hub
+ if: ${{ env.DOCKERHUB_USERNAME != '' && env.DOCKERHUB_TOKEN != '' }}
+ uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
+ with:
+ username: ${{ vars.DOCKERHUB_USER }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ - name: Start Postgres, Kafka, and etcd
+ env:
+ COMPOSE_FILE: ../docker-compose.dev.yml:../docker-compose.profiles.yml
+ COMPOSE_PROFILES: etcd
+ WAIT_FOR_DOCKER_LAUNCH_RETRIES: 3
+ WAIT_FOR_DOCKER_LAUNCH_RETRY_DELAY: 10
+ run: |
+ ../bin/ci-wait-for-docker launch --down db kafka etcd
+ ../bin/ci-wait-for-docker wait --only db kafka etcd
+
+ echo "127.0.0.1 db kafka" | sudo tee -a /etc/hosts
+
+ # please keep the tag version here in sync with rust-version in rust/*/Cargo.toml
+ - name: Install rust
+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9
+ with:
+ toolchain: 1.91.1
+
+ - name: Install protoc
+ uses: ./.github/actions/setup-protoc
+
+ - name: Set sccache WebDAV key prefix (Cargo.lock hash)
+ run: echo "SCCACHE_WEBDAV_KEY_PREFIX=cargo-${{ hashFiles('rust/Cargo.lock') }}" >> "$GITHUB_ENV"
+
+ - name: Install sccache
+ uses: ./.github/actions/setup-sccache
+
+ - name: Install sqlx-cli
+ uses: ./.github/actions/setup-sqlx-cli
+
+ - name: Create and migrate the persons database
+ env:
+ DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog_persons'
+ run: |
+ sqlx database create
+ sqlx migrate run --source persons_migrations/
+
+ - name: Build the personhog stack and harness
+ run: cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-test-harness
+
+ # Unit tests for the harness's own verification logic — a
+ # false-negative verifier would pass gates that lost data.
+ - name: Test the harness verification logic
+ run: cargo test -p personhog-test-harness
+
+ - name: Run the e2e gate
+ env:
+ RUST_BACKTRACE: 1
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 2 --partitions 4 --persons 100 --concurrency 10 --duration 10s
+
+ - name: Run the e2e gate under chaos (kill + scale-up)
+ env:
+ RUST_BACKTRACE: 1
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 15s \
+ --kill-after 5s --scale-up-after 8s
+
+ - name: Run the e2e gate under chaos (drain + zombie + writer lag)
+ env:
+ RUST_BACKTRACE: 1
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 18s \
+ --shutdown-after 3s --zombie-after 8s --zombie-duration 6s \
+ --writer-pause-after 4s --writer-pause-duration 6s
+
+ - name: Run the e2e gate under chaos (TTL-expiry kill + restarts)
+ env:
+ RUST_BACKTRACE: 1
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 18s \
+ --leader-lease-ttl 5 --kill-after 4s --kill-fast false \
+ --writer-crash-after 9s --restart-after 12s
+
+ - name: Run the e2e gate under chaos (coordinator failover + mid-handoff kill)
+ env:
+ RUST_BACKTRACE: 1
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --routers 2 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
+ --duration 18s --router-kill-after 4s --shutdown-after 8s --kill-handoff-target
+
+ - name: Dump service logs on failure
+ if: failure()
+ run: |
+ docker ps -a || true
+ docker logs --tail=200 rust-kafka-1 || true
+ docker logs --tail=200 rust-etcd-1 || true
+
+ - name: Upload harness logs on failure
+ if: failure()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: personhog-test-harness-logs
+ path: rust/target/debug/harness-logs/
+ if-no-files-found: ignore
+
linting:
name: Lint Rust services (depot-ubuntu-22.04-4)
needs: changes
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a45f09806e1b..9423a0140034 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7592,6 +7592,30 @@ dependencies = [
"stateright",
]
+[[package]]
+name = "personhog-test-harness"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "assignment-coordination",
+ "chrono",
+ "clap",
+ "futures",
+ "hdrhistogram",
+ "humantime",
+ "personhog-coordination",
+ "personhog-proto",
+ "rand 0.8.5",
+ "rdkafka",
+ "serde_json",
+ "sqlx",
+ "tokio",
+ "tonic 0.12.3",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
[[package]]
name = "personhog-writer"
version = "0.1.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 76ebad38123e..e40ddbe59648 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -58,6 +58,7 @@ members = [
"personhog-replica",
"personhog-router",
"personhog-stateright",
+ "personhog-test-harness",
"affected-services",
"property-vals-rs",
]
diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.toml
index 764df49c7799..36bd08c173f1 100644
--- a/rust/affected-services/determinator-rules.toml
+++ b/rust/affected-services/determinator-rules.toml
@@ -89,3 +89,17 @@ globs = [
"bin/migrate-*",
]
mark-changed = []
+
+# The e2e test harness exercises the personhog services as spawned
+# binaries — a runtime dependency the cargo graph cannot see (compile-time
+# deps like personhog-proto flow through the graph already). Mark the
+# harness affected whenever a service it spawns changes so the CI gate
+# runs against those changes.
+[[package-rule]]
+on-affected = [
+ "personhog-replica",
+ "personhog-router",
+ "personhog-leader",
+ "personhog-writer",
+]
+mark-changed = ["personhog-test-harness"]
diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rs
index f0b6e12dec73..a2008bc69963 100644
--- a/rust/affected-services/tests/integration.rs
+++ b/rust/affected-services/tests/integration.rs
@@ -111,7 +111,8 @@ fn every_deployable_binary_has_an_image_entry() {
"stl_dump",
"run", // hogvm dev/diff CLI, not a service
"hermes",
- "personhog-stateright", // model-checker explorer CLI, not a service
+ "personhog-stateright", // model-checker explorer CLI, not a service
+ "personhog-test-harness", // e2e load/correctness harness CLI, not a service
]
.into();
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 2a0b284502e5..1226c7939c9f 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -256,9 +256,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let shared_table = coordination_routing_table.table_handle();
let leader_port = config.leader_port;
+ // Pods may register with an explicit `host:port` name (local
+ // multi-leader setups, where a single fleet-wide port cannot hold);
+ // those resolve as-is. Bare pod names resolve via DNS on the
+ // fleet-wide leader port.
let leader_backend = Arc::new(LeaderBackend::new(
shared_table,
- Arc::new(move |pod_name: &str| Some(format!("http://{}:{}", pod_name, leader_port))),
+ Arc::new(move |pod_name: &str| {
+ if pod_name.contains(':') {
+ Some(format!("http://{pod_name}"))
+ } else {
+ Some(format!("http://{pod_name}:{leader_port}"))
+ }
+ }),
LeaderBackendConfig {
num_partitions,
timeout: config.backend_timeout(),
diff --git a/rust/personhog-test-harness/Cargo.toml b/rust/personhog-test-harness/Cargo.toml
new file mode 100644
index 000000000000..47bd91692495
--- /dev/null
+++ b/rust/personhog-test-harness/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "personhog-test-harness"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+personhog-proto = { path = "../personhog-proto" }
+personhog-coordination = { path = "../personhog-coordination" }
+assignment-coordination = { path = "../common/assignment-coordination" }
+
+anyhow = { workspace = true }
+chrono = { workspace = true }
+clap = { workspace = true, features = ["derive"] }
+futures = { workspace = true }
+hdrhistogram = { workspace = true }
+humantime = { workspace = true }
+rand = { workspace = true }
+rdkafka = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+tonic = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true }
+uuid = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
new file mode 100644
index 000000000000..57419c5cfc87
--- /dev/null
+++ b/rust/personhog-test-harness/README.md
@@ -0,0 +1,187 @@
+# personhog-test-harness
+
+Load, consistency, and e2e correctness harness for the personhog leader path.
+Revived from the original personhog-cannon draft (#55581) and extended with stack orchestration, Postgres seeding, and an acked-write journal so it can gate CI, not just generate load.
+
+The core invariant it checks: **every write acked by the leader path is visible afterwards** — in strong reads once coordination has converged (post-chaos handoffs re-driven; an already-settled run waits zero time, and failing to converge within 90s fails the gate), and in Postgres (at or above the highest acked version) once the writer drains.
+Every acked update is journaled under a unique property key, so the final state must contain all of them regardless of how concurrent writers interleaved.
+Version assignment is asserted throughout: the leader assigns each version of a person to at most one acked write, so a duplicated acked version (two writes served from the same base state), or a strong read observing a version below the highest ack, is a violation.
+Read-your-write recency is asserted live: `--probers` (default 2) workers run write-then-strong-read cycles alongside the blast traffic, so a staleness window during a chaos event trips a probe even if it heals before the end-of-run verification.
+
+## Requirements
+
+The docker-compose dev dependencies must be running: Postgres (`posthog_persons`), Kafka, and etcd (`COMPOSE_PROFILES=etcd`).
+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
+```
+
+## `gate` — the e2e correctness gate
+
+Brings 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.
+Exits non-zero on any violation.
+
+```bash
+target/debug/personhog-test-harness gate --duration 10s --persons 100 --concurrency 10
+
+# More leaders/partitions
+target/debug/personhog-test-harness gate --leaders 3 --partitions 8 --duration 30s
+
+# Against an already-running stack instead of spawning one. The dev stack's
+# writer targets personhog_person_tmp, so tell the verifier to read it there.
+target/debug/personhog-test-harness gate --external-router-url http://127.0.0.1:50054 \
+ --pg-target-table personhog_person_tmp
+```
+
+The spawned stack is isolated from the dev stack: its own port range (51xxx), its own etcd prefix (`/personhog-test-harness/`), and a per-run changelog topic (`personhog_test_harness_<run_id>`, deleted on teardown).
+Persons are seeded directly in Postgres for a reserved harness team id (SQL is the interim seeding mechanism until the create RPC's future is settled; `src/seed.rs` is the swap seam).
+Service logs land in `<bin-dir>/harness-logs/<run_id>/`.
+
+Multiple local leaders work because each registers with a `host:port` pod name, which the router's address resolver dials as-is (bare pod names still resolve via DNS on the fleet-wide leader port).
+
+### Chaos disruptions
+
+Disruptions fire mid-traffic, scheduled relative to the start of the traffic phase (spawned stack only).
+The invariant is unchanged: failed writes were never acked, but everything acked through the disruption must still be visible afterwards.
+
+```bash
+# Crash the busiest leader 5s in (SIGKILL + etcd lease revoke for instant detection)
+target/debug/personhog-test-harness gate --leaders 3 --duration 15s --kill-after 5s
+
+# Let the coordinator discover the crash via lease TTL expiry instead.
+# --leader-lease-ttl shortens the lease (prod default 30s) so the dead
+# window fits in a short run; expect failures on the victim's partitions
+# for the full TTL — the coordinator is blind until the lease expires.
+target/debug/personhog-test-harness gate --leaders 3 --duration 20s \
+ --leader-lease-ttl 5 --kill-after 4s --kill-fast false
+
+# Graceful shutdown: SIGTERM, drain, partitions hand off while traffic flows
+target/debug/personhog-test-harness gate --leaders 3 --duration 15s --shutdown-after 5s
+
+# Scale out mid-traffic, then crash the busiest leader
+target/debug/personhog-test-harness gate --leaders 2 --duration 20s --scale-up-after 5s --kill-after 12s
+
+# Zombie: SIGSTOP + lease revoke so ownership moves, then SIGCONT the old
+# owner — it wakes believing it still owns its partitions
+target/debug/personhog-test-harness gate --leaders 3 --duration 20s --zombie-after 4s --zombie-duration 8s
+
+# Crash-restart the busiest leader under the same pod name (StatefulSet
+# restart): it must re-register and converge on the partitions etcd says it owns
+target/debug/personhog-test-harness gate --leaders 3 --duration 15s --restart-after 5s
+
+# Writer crash-restart (at-least-once redelivery under the version guard)
+# and writer pause/resume (controlled lag injection)
+target/debug/personhog-test-harness gate --duration 15s --writer-crash-after 5s
+target/debug/personhog-test-harness gate --duration 15s --writer-pause-after 3s --writer-pause-duration 8s
+
+# Kill the coordinator: bring-up guarantees the first router holds the
+# election, traffic targets the last; the kill revokes the election lease so
+# failover is immediate and a later handoff runs under the new coordinator
+target/debug/personhog-test-harness gate --leaders 3 --routers 2 --duration 20s \
+ --router-kill-after 5s --shutdown-after 9s
+
+# Compound: kill the target pod of an in-flight handoff (best-effort timing —
+# fires on the first handoff observed after the shutdown/scale-up)
+target/debug/personhog-test-harness gate --leaders 3 --duration 20s \
+ --shutdown-after 5s --kill-handoff-target
+```
+
+### Known defects these scenarios reproduce
+
+Four real leader-path bugs surface under specific gate configurations.
+They are documented here so red or noisy runs read as signal, not harness flakiness.
+
+**Cache eviction under writer lag loses acked writes — the gate goes RED.**
+`--cache-capacity` sets the leader cache size in entries; below `--persons` it forces eviction of dirty entries whose writes the writer has not yet flushed.
+The next operation reloads the stale Postgres row, later merges build on the stale base, and acked writes disappear — exactly what the journal catches:
+
+```bash
+# Expect thousands of violations until the eviction hazard is fixed
+target/debug/personhog-test-harness gate --persons 50 --cache-capacity 10 --duration 10s
+```
+
+Fix direction: pin dirty entries until the writer's committed offset passes their produce offset (see the TODO in `personhog-leader/src/cache/persons.rs`).
+
+**Graceful shutdown black-holes the leader's partitions — elevated Failed count, gate stays green.**
+The leader's lifecycle manager signals every component at SIGTERM simultaneously, so the gRPC server and Kafka producer finish shutting down (~160ms) long before the coordination drain hands partitions off (~2s: Draining status → 1s coordinator rebalance debounce → freeze → stash → fence → release).
+For most of that window the pod is still the registered owner with a dead server: writes get UNAVAILABLE, the router retries against the same owner (the stash only engages once it observes Freezing), and callers fail.
+
+```bash
+# Expect ~1% failed writes. All are unacked, so the invariant holds and the
+# gate passes — the signature is the Failed column, not violations.
+target/debug/personhog-test-harness gate --leaders 3 --duration 15s --shutdown-after 5s
+```
+
+Fix direction: ordered shutdown — drain the coordination component before stopping the gRPC server and producer (the lifecycle crate currently has no phase/ordering primitive).
+Once fixed, this run's Failed count should drop to ~0, matching the zombie scenario's.
+
+**A crashed coordinator blocks all handoffs for 10–20s — currently masked in the gate.**
+The coordinator election is a lease-backed CAS (15s TTL, 5s keepalives, 5s campaign retry); a crash of the router holding it leaves the key in place until the lease expires, and no handoff can start until a survivor wins.
+Leader crashes are usually unaffected (their own 30s registration lease gates discovery anyway), but a leader *drain* during the window stalls — which today, combined with the unordered-shutdown defect above, black-holes the draining pod's partitions for the whole gap (observed: 731 failed writes in ~10s at harness scale; one served strong read also returned NotFound for a person with acked writes, unreproduced and unexplained).
+The gate's coordinator-kill scenario deliberately revokes the election lease to stay deterministic, so it does NOT exercise this window; the slow-failover variant is worth adding once the shutdown ordering is fixed and traffic survives the wait.
+Fix direction: release the election on graceful exit reliably (the best-effort revoke can be dropped by the surrounding `select!` before it runs), and/or tune the election lease and retry intervals against the drain grace budget.
+
+**A drain overlapping a pod death wedges convergence for the drained pod's full lifecycle timeout — the gate waits it out.**
+The rebalance a drain triggers can race a concurrent pod death and create handoffs targeting the dead pod (self-healing: stale-handoff cleanup deletes them within a tick), but the re-drive rebalance still counts the *draining* pod as an assignment target — nothing marks it as leaving — and hands partitions back to it.
+Its gRPC server is already dead (the unordered-shutdown defect above) and its coordination component gets only a 5s grace, so those handoffs stall in Draining with no DrainedAck; rebalancing is globally deferred while any handoff is in flight, so nothing can converge until the pod's 30s lifecycle timeout force-exits it, deregistration fires, and cleanup plus a fresh rebalance finally move everything to survivors (observed: ~36s end to end, with the affected partitions black-holed throughout).
+
+```bash
+# Nondeterministic: wedges only when the mid-drain rebalance picks the
+# draining pod as a target. The signature is a large "settled in Ns" line
+# and an elevated Failed count.
+target/debug/personhog-test-harness gate --routers 2 --leaders 3 --duration 18s \
+ --router-kill-after 4s --shutdown-after 8s --kill-handoff-target
+```
+
+Verification waits for convergence (bounded at 90s) before asserting strong reads, so the gate stays green through the wedge; red here means convergence itself failed.
+Fix direction: the ordered-shutdown fix removes both halves (the server survives the drain, and coordination lives to write DrainedAck, collapsing "settled in" to near-zero — at which point the convergence deadline can tighten to re-gate on recovery time).
+Independently worth fixing: draining pods should be excluded as rebalance targets, and one stuck handoff should not defer all rebalancing.
+
+## `seed` / `cleanup` — manage traffic targets
+
+```bash
+# Create targets; prints a copy-pasteable --person-ids list
+target/debug/personhog-test-harness seed --team-id 900001 --count 100
+
+# Remove everything the harness wrote for a team
+target/debug/personhog-test-harness cleanup --team-id 900001
+```
+
+## `blast` — throughput with read-back verification
+
+Concurrent property updates against random targets, then a strong read-back verifying every acked write.
+Defaults to the dev stack's leader-mode router (`http://127.0.0.1:50054`).
+
+```bash
+target/debug/personhog-test-harness blast \
+ --team-id 900001 --person-ids 42,43,44 \
+ --concurrency 50 --duration 30s
+```
+
+## `consistency` — write-then-read validation
+
+Each worker writes a unique property and immediately reads it back with STRONG consistency.
+
+```bash
+target/debug/personhog-test-harness consistency \
+ --team-id 900001 --person-ids 42,43 \
+ --concurrency 5 --iterations 100
+```
+
+## Output
+
+```text
+=== personhog-test-harness gate results ===
+ Duration: 6.06s | Team: 900001 | Persons: 20
+
+ Operation Total Success Failed p50 p95 p99 RPS
+ writes 970 970 0 23.3ms 45.4ms 56.4ms 160.1
+ reads 20 20 0 753us 1.2ms 1.3ms 3.3
+
+ Consistency violations: 0
+```
+
+Violations are printed per person/key with expected vs actual; `__version` rows mean Postgres settled at a different version than the last ack, `__row` rows mean the person never reached Postgres at all.
+
+Set `RUST_LOG=personhog_test_harness=debug` for per-request logging.
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
new file mode 100644
index 000000000000..dbdec1872006
--- /dev/null
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -0,0 +1,253 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use clap::{Args, Parser, Subcommand};
+
+pub const DEFAULT_PERSONS_DB_URL: &str =
+ "postgres://posthog:posthog@localhost:5432/posthog_persons";
+
+/// The dev-stack leader-mode router (bin/mprocs.yaml `personhog-router-leader`).
+pub const DEV_STACK_ROUTER_URL: &str = "http://127.0.0.1:50054";
+
+#[derive(Parser)]
+#[command(
+ name = "personhog-test-harness",
+ about = "Load, consistency, and e2e correctness harness for the personhog leader path"
+)]
+pub struct Cli {
+ #[command(subcommand)]
+ pub command: Command,
+}
+
+#[derive(Subcommand)]
+pub enum Command {
+ /// Seed persons directly into Postgres for use as traffic targets.
+ Seed(SeedArgs),
+ /// Delete all harness data for a team from Postgres.
+ Cleanup(CleanupArgs),
+ /// High-throughput concurrent property updates with read-back verification.
+ Blast(BlastArgs),
+ /// Write-then-strong-read consistency validation.
+ Consistency(ConsistencyArgs),
+ /// Full e2e gate: stack up, seed, traffic, quiesce, verify, cleanup.
+ Gate(Box<GateArgs>),
+}
+
+#[derive(Args, Clone)]
+pub struct SeedArgs {
+ #[arg(long)]
+ pub team_id: i64,
+
+ /// Number of persons to create.
+ #[arg(long, default_value_t = 100)]
+ pub count: u32,
+
+ #[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
+ pub persons_db_url: String,
+}
+
+#[derive(Args, Clone)]
+pub struct CleanupArgs {
+ #[arg(long)]
+ pub team_id: i64,
+
+ #[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
+ pub persons_db_url: String,
+}
+
+#[derive(Args, Clone)]
+pub struct BlastArgs {
+ #[arg(long, default_value = DEV_STACK_ROUTER_URL)]
+ pub router_url: String,
+
+ #[arg(long)]
+ pub team_id: i64,
+
+ /// Person IDs to target (comma-separated). Use `seed` to create targets.
+ #[arg(long, value_delimiter = ',', required = true)]
+ pub person_ids: Vec<i64>,
+
+ #[arg(long, default_value_t = 10)]
+ pub concurrency: usize,
+
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub duration: Duration,
+
+ /// Prefix for generated property keys.
+ #[arg(long, default_value = "harness_")]
+ pub property_prefix: String,
+
+ /// Read back each person with STRONG consistency after the blast and
+ /// verify that every acked write is present.
+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
+ pub verify: bool,
+}
+
+#[derive(Args, Clone)]
+pub struct ConsistencyArgs {
+ #[arg(long, default_value = DEV_STACK_ROUTER_URL)]
+ pub router_url: String,
+
+ #[arg(long)]
+ pub team_id: i64,
+
+ /// Person IDs to target (comma-separated). Use `seed` to create targets.
+ #[arg(long, value_delimiter = ',', required = true)]
+ pub person_ids: Vec<i64>,
+
+ #[arg(long, default_value_t = 5)]
+ pub concurrency: usize,
+
+ /// Write-then-read cycles per worker.
+ #[arg(long, default_value_t = 100)]
+ pub iterations: u64,
+
+ /// Delay between write and read-back.
+ #[arg(long, default_value = "0ms", value_parser = humantime::parse_duration)]
+ pub read_delay: Duration,
+}
+
+#[derive(Args, Clone)]
+pub struct GateArgs {
+ /// Target an already-running stack at this router URL instead of
+ /// spawning one. When unset, the harness spawns its own isolated stack
+ /// (replica, leaders, leader-mode router, writer) against the
+ /// docker-compose Kafka/etcd/Postgres.
+ #[arg(long)]
+ pub external_router_url: Option<String>,
+
+ #[arg(long, default_value_t = 900_001)]
+ pub team_id: i64,
+
+ /// Number of persons to seed.
+ #[arg(long, default_value_t = 100)]
+ pub persons: u32,
+
+ /// Number of leader pods to spawn (ignored with --external-router-url).
+ #[arg(long, default_value_t = 2)]
+ pub leaders: u32,
+
+ /// Number of leader-mode routers to spawn (each is a coordinator
+ /// candidate). Traffic targets the last one, so a coordinator kill —
+ /// which targets the first — leaves the traffic path intact.
+ #[arg(long, default_value_t = 1)]
+ pub routers: u32,
+
+ /// Number of partitions (ignored with --external-router-url).
+ #[arg(long, default_value_t = 4)]
+ pub partitions: u32,
+
+ #[arg(long, default_value = "10s", value_parser = humantime::parse_duration)]
+ pub duration: Duration,
+
+ #[arg(long, default_value_t = 10)]
+ pub concurrency: usize,
+
+ /// Read-your-write probers running alongside the blast traffic: each
+ /// repeatedly writes a unique key and immediately strong-reads it back,
+ /// asserting recency through chaos windows (handoffs, failovers) that
+ /// the end-of-run verification cannot see. 0 disables.
+ #[arg(long, default_value_t = 2)]
+ pub probers: usize,
+
+ #[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
+ pub persons_db_url: String,
+
+ /// The table the writer under test upserts into. Must match the
+ /// writer's PG_TARGET_TABLE: spawned stacks run in posthog_person mode;
+ /// the dev stack's writer defaults to personhog_person_tmp, so pass
+ /// that with --external-router-url against dev.
+ #[arg(long, default_value = "posthog_person")]
+ pub pg_target_table: String,
+
+ #[arg(long, default_value = "localhost:9092")]
+ pub kafka_hosts: String,
+
+ #[arg(long, default_value = "http://localhost:2379")]
+ pub etcd_endpoints: String,
+
+ /// Kill (SIGKILL) the busiest leader this long into the traffic phase.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub kill_after: Option<Duration>,
+
+ /// With --kill-after: also revoke the pod's etcd lease so the
+ /// coordinator reacts immediately instead of waiting out the lease TTL.
+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
+ pub kill_fast: bool,
+
+ /// Gracefully shut down (SIGTERM + drain) the busiest leader this long
+ /// into the traffic phase.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub shutdown_after: Option<Duration>,
+
+ /// Spawn an additional leader this long into the traffic phase.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub scale_up_after: Option<Duration>,
+
+ /// Crash-restart (SIGKILL + respawn, same pod name) the busiest leader
+ /// this long into the traffic phase.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub restart_after: Option<Duration>,
+
+ /// Zombie the busiest leader this long into the traffic phase (SIGSTOP
+ /// plus lease revoke), so ownership moves while the process still holds
+ /// its old cache and producer.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub zombie_after: Option<Duration>,
+
+ /// How long the zombie stays SIGSTOPped before SIGCONT wakes it.
+ #[arg(long, default_value = "8s", value_parser = humantime::parse_duration)]
+ pub zombie_duration: Duration,
+
+ /// Crash-restart the writer this long into the traffic phase
+ /// (validates at-least-once redelivery under the version guard).
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub writer_crash_after: Option<Duration>,
+
+ /// SIGSTOP the writer this long into the traffic phase — controlled
+ /// writer-lag injection.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub writer_pause_after: Option<Duration>,
+
+ /// How long the writer stays paused before SIGCONT.
+ #[arg(long, default_value = "10s", value_parser = humantime::parse_duration)]
+ pub writer_pause_duration: Duration,
+
+ /// SIGKILL the first router (the presumed coordinator) this long into
+ /// the traffic phase. Requires --routers >= 2.
+ #[arg(long, value_parser = humantime::parse_duration)]
+ pub router_kill_after: Option<Duration>,
+
+ /// After the first handoff-creating event (--shutdown-after or
+ /// --scale-up-after) fires, watch for the resulting handoff and SIGKILL
+ /// its target pod mid-handoff. Best effort: a handoff that completes
+ /// between polls is not killed.
+ #[arg(long, default_value_t = false)]
+ pub kill_handoff_target: bool,
+
+ /// Leader cache capacity in entries. Set below --persons to put the
+ /// cache under eviction pressure.
+ #[arg(long, default_value_t = 100_000)]
+ pub cache_capacity: usize,
+
+ /// etcd lease TTL for spawned leaders, in seconds. The production
+ /// default is 30; lower it (5s works) so a TTL-expiry kill
+ /// (--kill-fast false) doesn't need a 30s+ outage window mid-run.
+ /// The heartbeat interval scales to a third of this.
+ #[arg(long, default_value_t = 30)]
+ pub leader_lease_ttl: i64,
+
+ /// 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)]
+ pub keep_stack: bool,
+
+ /// Leave seeded persons in Postgres after the gate finishes.
+ #[arg(long, default_value_t = false)]
+ pub keep_data: bool,
+
+ /// Directory containing the service binaries. Defaults to the
+ /// workspace target directory for this build profile.
+ #[arg(long)]
+ pub bin_dir: Option<PathBuf>,
+}
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
new file mode 100644
index 000000000000..cdbb4f2af19d
--- /dev/null
+++ b/rust/personhog-test-harness/src/client.rs
@@ -0,0 +1,113 @@
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use personhog_proto::personhog::{
+ service::v1::person_hog_service_client::PersonHogServiceClient,
+ types::v1::{
+ ConsistencyLevel, GetPersonRequest, Person, ReadOptions, UpdatePersonPropertiesRequest,
+ UpdatePersonPropertiesResponse,
+ },
+};
+use tonic::metadata::MetadataValue;
+use tonic::transport::Channel;
+use tonic::Request;
+
+/// Routing headers the leader-mode router requires on leader-bound calls.
+/// `UpdatePersonProperties` always routes to a leader; `GetPerson` routes to
+/// a leader only when `x-read-consistency: strong` is present.
+const TEAM_ID_HEADER: &str = "x-team-id";
+const PERSON_ID_HEADER: &str = "x-person-id";
+const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
+
+#[derive(Clone)]
+pub struct HarnessClient {
+ inner: PersonHogServiceClient<Channel>,
+}
+
+impl HarnessClient {
+ pub async fn connect(url: &str) -> Result<Self> {
+ let channel = Channel::from_shared(url.to_string())
+ .context("invalid router URL")?
+ .timeout(Duration::from_secs(10))
+ .connect_timeout(Duration::from_secs(5))
+ .tcp_nodelay(true)
+ .connect_lazy();
+
+ Ok(Self {
+ inner: PersonHogServiceClient::new(channel),
+ })
+ }
+
+ pub async fn get_person(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ consistency: ConsistencyLevel,
+ ) -> Result<Option<Person>> {
+ let mut request = Request::new(GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: Some(ReadOptions {
+ consistency: consistency.into(),
+ ..Default::default()
+ }),
+ });
+ if consistency == ConsistencyLevel::Strong {
+ stamp_routing_headers(&mut request, team_id, person_id)?;
+ request.metadata_mut().insert(
+ READ_CONSISTENCY_HEADER,
+ MetadataValue::from_static("strong"),
+ );
+ }
+
+ let resp = self
+ .inner
+ .clone()
+ .get_person(request)
+ .await
+ .context("GetPerson failed")?;
+
+ Ok(resp.into_inner().person)
+ }
+
+ pub async fn update_properties(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ set_properties: serde_json::Value,
+ set_once_properties: serde_json::Value,
+ unset_properties: Vec<String>,
+ ) -> Result<UpdatePersonPropertiesResponse> {
+ let mut request = Request::new(UpdatePersonPropertiesRequest {
+ team_id,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&set_properties)?,
+ set_once_properties: serde_json::to_vec(&set_once_properties)?,
+ unset_properties,
+ });
+ stamp_routing_headers(&mut request, team_id, person_id)?;
+
+ let resp = self
+ .inner
+ .clone()
+ .update_person_properties(request)
+ .await
+ .context("UpdatePersonProperties failed")?;
+
+ Ok(resp.into_inner())
+ }
+}
+
+fn stamp_routing_headers<T>(request: &mut Request<T>, team_id: i64, person_id: i64) -> Result<()> {
+ let metadata = request.metadata_mut();
+ metadata.insert(
+ TEAM_ID_HEADER,
+ MetadataValue::try_from(team_id.to_string()).context("invalid team id header")?,
+ );
+ metadata.insert(
+ PERSON_ID_HEADER,
+ MetadataValue::try_from(person_id.to_string()).context("invalid person id header")?,
+ );
+ Ok(())
+}
diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rs
new file mode 100644
index 000000000000..9d4c3890abe4
--- /dev/null
+++ b/rust/personhog-test-harness/src/main.rs
@@ -0,0 +1,33 @@
+use anyhow::Result;
+use clap::Parser;
+use tracing_subscriber::EnvFilter;
+
+mod cli;
+mod client;
+mod report;
+mod scenarios;
+mod seed;
+mod stack;
+mod state;
+mod stats;
+
+use cli::{Cli, Command};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| EnvFilter::new("personhog_test_harness=info,warn")),
+ )
+ .init();
+
+ let cli = Cli::parse();
+ match cli.command {
+ Command::Seed(args) => scenarios::seed_cmd::run(args).await,
+ Command::Cleanup(args) => scenarios::seed_cmd::run_cleanup(args).await,
+ Command::Blast(args) => scenarios::blast::run(args).await,
+ Command::Consistency(args) => scenarios::consistency::run(args).await,
+ Command::Gate(args) => scenarios::gate::run(*args).await,
+ }
+}
diff --git a/rust/personhog-test-harness/src/report.rs b/rust/personhog-test-harness/src/report.rs
new file mode 100644
index 000000000000..3ca6e92f2964
--- /dev/null
+++ b/rust/personhog-test-harness/src/report.rs
@@ -0,0 +1,82 @@
+use crate::stats::{StatsCollector, StatsSnapshot};
+
+fn format_us(us: u64) -> String {
+ if us < 1_000 {
+ format!("{us}us")
+ } else if us < 1_000_000 {
+ format!("{:.1}ms", us as f64 / 1_000.0)
+ } else {
+ format!("{:.2}s", us as f64 / 1_000_000.0)
+ }
+}
+
+fn print_stats_row(name: &str, snap: &StatsSnapshot) {
+ println!(
+ " {:<10} {:>8} {:>8} {:>7} {:>8} {:>8} {:>8} {:>9.1}",
+ name,
+ snap.total,
+ snap.successes,
+ snap.failures,
+ format_us(snap.p50_us),
+ format_us(snap.p95_us),
+ format_us(snap.p99_us),
+ snap.throughput_rps,
+ );
+}
+
+pub fn print_report(
+ title: &str,
+ collector: &StatsCollector,
+ team_id: i64,
+ num_persons: usize,
+ violations: &[ConsistencyViolation],
+) {
+ let write_snap = collector.writes.snapshot();
+ let read_snap = collector.reads.snapshot();
+ let elapsed = write_snap.elapsed.max(read_snap.elapsed);
+
+ println!();
+ println!("=== personhog-test-harness {title} results ===");
+ println!(
+ " Duration: {:.2}s | Team: {} | Persons: {}",
+ elapsed.as_secs_f64(),
+ team_id,
+ num_persons
+ );
+ println!();
+ println!(
+ " {:<10} {:>8} {:>8} {:>7} {:>8} {:>8} {:>8} {:>9}",
+ "Operation", "Total", "Success", "Failed", "p50", "p95", "p99", "RPS"
+ );
+ if write_snap.total > 0 {
+ print_stats_row("writes", &write_snap);
+ }
+ if read_snap.total > 0 {
+ print_stats_row("reads", &read_snap);
+ }
+ println!();
+
+ if violations.is_empty() {
+ println!(" Consistency violations: 0");
+ } else {
+ println!(" Consistency violations: {}", violations.len());
+ println!();
+ for v in violations.iter().take(20) {
+ println!(
+ " person_id={} key={:?} expected={} actual={}",
+ v.person_id, v.key, v.expected, v.actual,
+ );
+ }
+ if violations.len() > 20 {
+ println!(" ... and {} more", violations.len() - 20);
+ }
+ }
+ println!();
+}
+
+pub struct ConsistencyViolation {
+ pub person_id: i64,
+ pub key: String,
+ pub expected: serde_json::Value,
+ pub actual: serde_json::Value,
+}
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
new file mode 100644
index 000000000000..d42a96c4dc49
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -0,0 +1,187 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Result};
+use personhog_proto::personhog::types::v1::ConsistencyLevel;
+use rand::{Rng, SeedableRng};
+
+use crate::cli::BlastArgs;
+use crate::client::HarnessClient;
+use crate::report::{print_report, ConsistencyViolation};
+use crate::state::PersonState;
+use crate::stats::StatsCollector;
+
+pub async fn run(args: BlastArgs) -> Result<()> {
+ let client = HarnessClient::connect(&args.router_url).await?;
+ let person_ids = Arc::new(args.person_ids.clone());
+
+ println!(
+ "Blasting {} persons for {} with concurrency {}...",
+ person_ids.len(),
+ humantime::format_duration(args.duration),
+ args.concurrency
+ );
+
+ let collector = Arc::new(StatsCollector::new());
+ let state = PersonState::new();
+ run_traffic(
+ &client,
+ args.team_id,
+ person_ids.clone(),
+ args.duration,
+ args.concurrency,
+ &args.property_prefix,
+ &collector,
+ &state,
+ )
+ .await?;
+
+ let mut violations = state.take_anomalies().await;
+ if args.verify {
+ println!("Verifying reads with STRONG consistency...");
+ violations.extend(verify_strong(&client, &collector, &state, args.team_id).await?);
+ }
+
+ print_report(
+ "blast",
+ &collector,
+ args.team_id,
+ person_ids.len(),
+ &violations,
+ );
+
+ if !violations.is_empty() {
+ bail!("{} consistency violations detected", violations.len());
+ }
+ Ok(())
+}
+
+/// Drive concurrent property updates against random targets until the
+/// duration elapses, journaling every acked write into `state`.
+#[allow(clippy::too_many_arguments)]
+pub async fn run_traffic(
+ client: &HarnessClient,
+ team_id: i64,
+ person_ids: Arc<Vec<i64>>,
+ duration: Duration,
+ concurrency: usize,
+ property_prefix: &str,
+ collector: &Arc<StatsCollector>,
+ state: &PersonState,
+) -> Result<()> {
+ let deadline = Instant::now() + duration;
+
+ let mut handles = Vec::new();
+ for worker_id in 0..concurrency {
+ let client = client.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let person_ids = person_ids.clone();
+ let prefix = property_prefix.to_string();
+
+ handles.push(tokio::spawn(async move {
+ let mut counter: u64 = 0;
+ let mut rng = rand::rngs::StdRng::from_entropy();
+
+ while Instant::now() < deadline {
+ let person_id = person_ids[rng.gen_range(0..person_ids.len())];
+ counter += 1;
+
+ let key = format!("{prefix}{worker_id}_{counter}");
+ let value = uuid::Uuid::new_v4().to_string();
+ let props = serde_json::json!({ &key: &value });
+
+ let start = Instant::now();
+ match client
+ .update_properties(team_id, person_id, props, serde_json::json!({}), vec![])
+ .await
+ {
+ Ok(resp) => {
+ collector.writes.record_success(start.elapsed());
+ let mut written = HashMap::new();
+ written.insert(key, serde_json::Value::String(value));
+ match resp.person {
+ Some(person) => {
+ state.record_write(person_id, person.version, written).await
+ }
+ None => state.record_ack_anomaly(person_id, written).await,
+ }
+ }
+ Err(e) => {
+ collector.writes.record_failure();
+ // `{:#}` prints the full anyhow chain — the outer
+ // context alone hides the gRPC status underneath.
+ tracing::warn!(person_id, error = format!("{e:#}"), "write failed");
+ }
+ }
+ }
+ }));
+ }
+
+ for handle in handles {
+ handle.await?;
+ }
+ Ok(())
+}
+
+/// Read every journaled person back with STRONG consistency and check that
+/// all acked writes are visible. A person that cannot be read is a
+/// violation, not a skip: NotFound for a person with acked writes means the
+/// person is gone, and a read error (retried once, since verification can
+/// race a settling handoff) means visibility cannot be asserted at all.
+pub async fn verify_strong(
+ client: &HarnessClient,
+ collector: &StatsCollector,
+ state: &PersonState,
+ team_id: i64,
+) -> Result<Vec<ConsistencyViolation>> {
+ let person_ids = state.person_ids().await;
+ let mut all_violations = Vec::new();
+
+ for person_id in person_ids {
+ let start = Instant::now();
+ let mut result = client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await;
+ if result.is_err() {
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ result = client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await;
+ }
+
+ match result {
+ Ok(Some(person)) => {
+ collector.reads.record_success(start.elapsed());
+ let props: serde_json::Value = if person.properties.is_empty() {
+ serde_json::json!({})
+ } else {
+ serde_json::from_slice(&person.properties)?
+ };
+ let mut violations = state.verify(person_id, &props, person.version).await;
+ all_violations.append(&mut violations);
+ }
+ Ok(None) => {
+ collector.reads.record_failure();
+ all_violations.push(ConsistencyViolation {
+ person_id,
+ key: "__missing_person".to_string(),
+ expected: serde_json::json!("person with acked writes exists"),
+ actual: serde_json::Value::Null,
+ });
+ }
+ Err(e) => {
+ collector.reads.record_failure();
+ all_violations.push(ConsistencyViolation {
+ person_id,
+ key: "__strong_read_failed".to_string(),
+ expected: serde_json::json!("readable"),
+ actual: serde_json::json!(e.to_string()),
+ });
+ }
+ }
+ }
+
+ Ok(all_violations)
+}
diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rs
new file mode 100644
index 000000000000..1cf9ea9fbee7
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs
@@ -0,0 +1,286 @@
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Context, Result};
+use personhog_proto::personhog::types::v1::ConsistencyLevel;
+
+use crate::cli::ConsistencyArgs;
+use crate::client::HarnessClient;
+use crate::report::{print_report, ConsistencyViolation};
+use crate::state::PersonState;
+use crate::stats::StatsCollector;
+
+pub async fn run(args: ConsistencyArgs) -> Result<()> {
+ let client = HarnessClient::connect(&args.router_url).await?;
+ let person_ids = Arc::new(args.person_ids.clone());
+
+ println!(
+ "Running consistency test: {} persons, {} workers, {} iterations each",
+ person_ids.len(),
+ args.concurrency,
+ args.iterations
+ );
+
+ let collector = Arc::new(StatsCollector::new());
+ let violations = Arc::new(tokio::sync::Mutex::new(Vec::<ConsistencyViolation>::new()));
+ let violation_count = Arc::new(AtomicU64::new(0));
+
+ let mut handles = Vec::new();
+ for worker_id in 0..args.concurrency {
+ let client = client.clone();
+ let collector = collector.clone();
+ let violations = violations.clone();
+ let violation_count = violation_count.clone();
+ let person_ids = person_ids.clone();
+ let team_id = args.team_id;
+ let iterations = args.iterations;
+ let read_delay = args.read_delay;
+
+ handles.push(tokio::spawn(async move {
+ for i in 0..iterations {
+ let person_id = person_ids[(worker_id + i as usize) % person_ids.len()];
+ let marker = uuid::Uuid::new_v4().to_string();
+ let key = format!("harness_consistency_{marker}");
+
+ let write_start = Instant::now();
+ let write_result = client
+ .update_properties(
+ team_id,
+ person_id,
+ serde_json::json!({ &key: &marker }),
+ serde_json::json!({}),
+ vec![],
+ )
+ .await;
+
+ match write_result {
+ Ok(resp) => {
+ collector.writes.record_success(write_start.elapsed());
+ if resp.person.is_none() {
+ // The response contract is that updates return
+ // the updated person; a bare ack is a violation,
+ // not a skip.
+ violation_count.fetch_add(1, Ordering::Relaxed);
+ let mut v = violations.lock().await;
+ if v.len() < 100 {
+ v.push(ConsistencyViolation {
+ person_id,
+ key: "__ack_missing_person".to_string(),
+ expected: serde_json::json!(
+ "update response carries the person"
+ ),
+ actual: serde_json::Value::Null,
+ });
+ }
+ continue;
+ }
+ }
+ Err(e) => {
+ collector.writes.record_failure();
+ tracing::warn!(person_id, error = %e, "consistency write failed");
+ continue;
+ }
+ }
+
+ if !read_delay.is_zero() {
+ tokio::time::sleep(read_delay).await;
+ }
+
+ let read_start = Instant::now();
+ match client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await
+ {
+ Ok(Some(person)) => {
+ collector.reads.record_success(read_start.elapsed());
+ let props: serde_json::Value = if person.properties.is_empty() {
+ serde_json::json!({})
+ } else {
+ match serde_json::from_slice(&person.properties) {
+ Ok(v) => v,
+ Err(e) => {
+ tracing::warn!(
+ person_id,
+ error = %e,
+ "failed to parse properties"
+ );
+ continue;
+ }
+ }
+ };
+
+ let actual = props.get(&key);
+ let expected = serde_json::Value::String(marker.clone());
+ if actual != Some(&expected) {
+ violation_count.fetch_add(1, Ordering::Relaxed);
+ let mut v = violations.lock().await;
+ if v.len() < 100 {
+ v.push(ConsistencyViolation {
+ person_id,
+ key: key.clone(),
+ expected,
+ actual: actual.cloned().unwrap_or(serde_json::Value::Null),
+ });
+ }
+ }
+ }
+ Ok(None) => {
+ collector.reads.record_failure();
+ tracing::warn!(person_id, "person not found during read-back");
+ }
+ Err(e) => {
+ collector.reads.record_failure();
+ tracing::warn!(person_id, error = %e, "consistency read failed");
+ }
+ }
+ }
+ }));
+ }
+
+ for handle in handles {
+ handle.await?;
+ }
+
+ let final_violations = violations.lock().await;
+ print_report(
+ "consistency",
+ &collector,
+ args.team_id,
+ person_ids.len(),
+ &final_violations,
+ );
+
+ let total_violations = violation_count.load(Ordering::Relaxed);
+ if total_violations > 0 {
+ bail!("{total_violations} consistency violations detected");
+ }
+ Ok(())
+}
+
+/// Read-your-write probers for the gate: each prober repeatedly writes a
+/// unique key and immediately strong-reads it back until the deadline.
+/// They run alongside the blast traffic, so recency is asserted *during*
+/// chaos windows — a transient staleness window that has healed by the
+/// end of the run is invisible to the end-of-run verification but trips a
+/// prober on the very next read.
+///
+/// Probed writes are journaled like any other ack, so the end-of-run
+/// checks cover their durability too. The mid-run assertion checks only
+/// the prober's own key: concurrent blast acks race the journal, so
+/// comparing a live read against the full journal would flag phantom
+/// violations. A failed read is likewise not a recency violation — reads
+/// legitimately fail while a killed owner's partitions are in limbo, and
+/// end-of-run verification owns readability.
+pub async fn run_probers(
+ client: &HarnessClient,
+ team_id: i64,
+ person_ids: Arc<Vec<i64>>,
+ probers: usize,
+ duration: Duration,
+ collector: &Arc<StatsCollector>,
+ state: &PersonState,
+) -> Result<Vec<ConsistencyViolation>> {
+ let deadline = Instant::now() + duration;
+
+ let mut handles = Vec::new();
+ for worker_id in 0..probers {
+ let client = client.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let person_ids = person_ids.clone();
+
+ handles.push(tokio::spawn(async move {
+ let mut violations = Vec::new();
+ let mut iteration: usize = 0;
+
+ while Instant::now() < deadline {
+ let person_id = person_ids[(worker_id + iteration) % person_ids.len()];
+ iteration += 1;
+ let marker = uuid::Uuid::new_v4().to_string();
+ let key = format!("harness_probe_{worker_id}_{iteration}");
+
+ let write_start = Instant::now();
+ let response = match client
+ .update_properties(
+ team_id,
+ person_id,
+ serde_json::json!({ &key: &marker }),
+ serde_json::json!({}),
+ vec![],
+ )
+ .await
+ {
+ Ok(response) => {
+ collector.writes.record_success(write_start.elapsed());
+ response
+ }
+ Err(e) => {
+ collector.writes.record_failure();
+ tracing::warn!(person_id, error = %e, "probe write failed");
+ continue;
+ }
+ };
+ let mut written = HashMap::new();
+ written.insert(key.clone(), serde_json::Value::String(marker.clone()));
+ match response.person {
+ Some(person) => {
+ state.record_write(person_id, person.version, written).await;
+ }
+ None => {
+ // Already flagged as a violation by the journal; the
+ // keys still get end-of-run verification.
+ state.record_ack_anomaly(person_id, written).await;
+ continue;
+ }
+ }
+
+ let read_start = Instant::now();
+ match client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await
+ {
+ Ok(Some(person)) => {
+ collector.reads.record_success(read_start.elapsed());
+ let props: serde_json::Value = serde_json::from_slice(&person.properties)
+ .unwrap_or_else(|_| serde_json::json!({}));
+ let expected = serde_json::Value::String(marker);
+ let actual = props.get(&key);
+ if actual != Some(&expected) {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key,
+ expected,
+ actual: actual.cloned().unwrap_or(serde_json::Value::Null),
+ });
+ }
+ }
+ Ok(None) => {
+ // A served read that cannot see a person with an
+ // acked write is a violation, not an availability
+ // blip.
+ collector.reads.record_failure();
+ violations.push(ConsistencyViolation {
+ person_id,
+ key,
+ expected: serde_json::Value::String(marker),
+ actual: serde_json::Value::Null,
+ });
+ }
+ Err(e) => {
+ collector.reads.record_failure();
+ tracing::warn!(person_id, error = %e, "probe read failed");
+ }
+ }
+ }
+ violations
+ }));
+ }
+
+ let mut all_violations = Vec::new();
+ for handle in handles {
+ all_violations.extend(handle.await.context("prober task panicked")?);
+ }
+ Ok(all_violations)
+}
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
new file mode 100644
index 000000000000..9dbf32e3e7fc
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -0,0 +1,498 @@
+use std::collections::HashMap;
+use std::fmt;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Context, Result};
+use sqlx::postgres::PgPool;
+use sqlx::Row;
+
+use crate::cli::GateArgs;
+use crate::client::HarnessClient;
+use crate::report::{print_report, ConsistencyViolation};
+use crate::scenarios::{blast, consistency};
+use crate::seed;
+use crate::stack::{Stack, StackConfig};
+use crate::state::{verify_properties, ExpectedPerson, PersonState};
+use crate::stats::StatsCollector;
+
+/// How long to wait for the writer to drain acked writes into Postgres
+/// before declaring them lost.
+const QUIESCE_DEADLINE: Duration = Duration::from_secs(60);
+
+/// A chaos disruption scheduled relative to the start of the traffic phase.
+enum ChaosEvent {
+ Kill { fast: bool },
+ Shutdown,
+ ScaleUp,
+ Restart,
+ ZombieStop,
+ ZombieResume,
+ WriterCrash,
+ WriterPause,
+ WriterResume,
+ RouterKill,
+}
+
+impl fmt::Display for ChaosEvent {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ChaosEvent::Kill { fast: true } => write!(f, "kill (fast lease revoke)"),
+ ChaosEvent::Kill { fast: false } => write!(f, "kill (lease TTL expiry)"),
+ ChaosEvent::Shutdown => write!(f, "graceful shutdown"),
+ ChaosEvent::ScaleUp => write!(f, "scale up"),
+ ChaosEvent::Restart => write!(f, "leader crash-restart"),
+ ChaosEvent::ZombieStop => write!(f, "zombie stop (SIGSTOP + lease revoke)"),
+ ChaosEvent::ZombieResume => write!(f, "zombie resume (SIGCONT)"),
+ ChaosEvent::WriterCrash => write!(f, "writer crash-restart"),
+ ChaosEvent::WriterPause => write!(f, "writer pause (lag injection)"),
+ ChaosEvent::WriterResume => write!(f, "writer resume"),
+ ChaosEvent::RouterKill => write!(f, "coordinator router kill"),
+ }
+ }
+}
+
+fn chaos_timeline(args: &GateArgs) -> Vec<(Duration, ChaosEvent)> {
+ let mut events = Vec::new();
+ if let Some(after) = args.kill_after {
+ events.push((
+ after,
+ ChaosEvent::Kill {
+ fast: args.kill_fast,
+ },
+ ));
+ }
+ if let Some(after) = args.shutdown_after {
+ events.push((after, ChaosEvent::Shutdown));
+ }
+ if let Some(after) = args.scale_up_after {
+ events.push((after, ChaosEvent::ScaleUp));
+ }
+ if let Some(after) = args.restart_after {
+ events.push((after, ChaosEvent::Restart));
+ }
+ if let Some(after) = args.zombie_after {
+ events.push((after, ChaosEvent::ZombieStop));
+ events.push((after + args.zombie_duration, ChaosEvent::ZombieResume));
+ }
+ if let Some(after) = args.writer_crash_after {
+ events.push((after, ChaosEvent::WriterCrash));
+ }
+ if let Some(after) = args.writer_pause_after {
+ events.push((after, ChaosEvent::WriterPause));
+ events.push((after + args.writer_pause_duration, ChaosEvent::WriterResume));
+ }
+ if let Some(after) = args.router_kill_after {
+ events.push((after, ChaosEvent::RouterKill));
+ }
+ events.sort_by_key(|(after, _)| *after);
+ events
+}
+
+/// The workspace target directory for the profile this harness was built
+/// with, derived from the crate's location at compile time. The runtime
+/// executable path is deliberately not consulted — its output is
+/// attacker-influenceable — and the harness only ever runs sibling
+/// binaries produced by the same cargo build; `--bin-dir` overrides for
+/// anything else.
+fn default_bin_dir() -> PathBuf {
+ let profile = if cfg!(debug_assertions) {
+ "debug"
+ } else {
+ "release"
+ };
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../target")
+ .join(profile)
+}
+
+/// The full e2e correctness gate: bring up an isolated stack (or target a
+/// running one), seed persons, drive update traffic through the router —
+/// optionally disrupting the stack mid-traffic — then assert every acked
+/// write is visible via strong reads AND lands in Postgres with the acked
+/// version. Exits non-zero on any violation, so it can gate CI.
+pub async fn run(args: GateArgs) -> Result<()> {
+ seed::validate_table_name(&args.pg_target_table)?;
+ let chaos = chaos_timeline(&args);
+ if args.external_router_url.is_some() && (!chaos.is_empty() || args.kill_handoff_target) {
+ bail!("chaos flags require a spawned stack; they cannot target --external-router-url");
+ }
+ if args.router_kill_after.is_some() && args.routers < 2 {
+ bail!("--router-kill-after requires --routers >= 2 (traffic targets the last router)");
+ }
+ if args.kill_handoff_target && args.shutdown_after.is_none() && args.scale_up_after.is_none() {
+ bail!("--kill-handoff-target needs a handoff-creating event (--shutdown-after or --scale-up-after)");
+ }
+
+ let mut stack = match &args.external_router_url {
+ Some(_) => None,
+ None => {
+ let bin_dir = args.bin_dir.clone().unwrap_or_else(default_bin_dir);
+ Some(
+ Stack::up(StackConfig {
+ bin_dir,
+ leaders: args.leaders,
+ routers: args.routers,
+ partitions: args.partitions,
+ kafka_hosts: args.kafka_hosts.clone(),
+ etcd_endpoints: args.etcd_endpoints.clone(),
+ persons_db_url: args.persons_db_url.clone(),
+ writer_flush_interval_ms: 1000,
+ pg_target_table: args.pg_target_table.clone(),
+ cache_memory_capacity: args.cache_capacity,
+ leader_lease_ttl: args.leader_lease_ttl,
+ })
+ .await?,
+ )
+ }
+ };
+
+ 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 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.
+ seed::cleanup_team(&pool, args.team_id).await?;
+ let person_ids = Arc::new(seed::seed_persons(&pool, args.team_id, args.persons).await?);
+ println!(
+ "Seeded {} persons for team {}",
+ person_ids.len(),
+ args.team_id
+ );
+
+ println!(
+ "Driving traffic for {} with concurrency {}...",
+ humantime::format_duration(args.duration),
+ args.concurrency
+ );
+ let collector = Arc::new(StatsCollector::new());
+ let state = PersonState::new();
+ let traffic = {
+ let client = client.clone();
+ let person_ids = person_ids.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let (team_id, duration, concurrency) = (args.team_id, args.duration, args.concurrency);
+ tokio::spawn(async move {
+ blast::run_traffic(
+ &client,
+ team_id,
+ person_ids,
+ duration,
+ concurrency,
+ "harness_gate_",
+ &collector,
+ &state,
+ )
+ .await
+ })
+ };
+
+ // Read-your-write probers run for the same window as the traffic, so
+ // recency is asserted through whatever chaos fires below.
+ let probers = {
+ let client = client.clone();
+ let person_ids = person_ids.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let (team_id, duration, prober_count) = (args.team_id, args.duration, args.probers);
+ tokio::spawn(async move {
+ consistency::run_probers(
+ &client,
+ team_id,
+ person_ids,
+ prober_count,
+ duration,
+ &collector,
+ &state,
+ )
+ .await
+ })
+ };
+
+ // Fire scheduled disruptions while traffic flows. Failures aren't
+ // journaled, so the invariant is untouched: whatever the leader acked
+ // through the disruption must still be visible afterwards.
+ let traffic_start = Instant::now();
+ let mut handoff_kill_armed = args.kill_handoff_target;
+ for (after, event) in chaos {
+ let stack = stack.as_mut().expect("chaos requires a spawned stack");
+ tokio::time::sleep_until((traffic_start + after).into()).await;
+ let creates_handoff = matches!(event, ChaosEvent::Shutdown | ChaosEvent::ScaleUp);
+ let pod = match event {
+ ChaosEvent::Kill { fast } => Some(stack.kill_leader(fast).await?),
+ ChaosEvent::Shutdown => Some(stack.shutdown_leader().await?),
+ ChaosEvent::ScaleUp => Some(stack.spawn_leader()?),
+ ChaosEvent::Restart => Some(stack.restart_leader().await?),
+ ChaosEvent::ZombieStop => Some(stack.stop_zombie().await?),
+ ChaosEvent::ZombieResume => Some(stack.resume_zombie()?),
+ ChaosEvent::WriterCrash => {
+ stack.crash_restart_writer().await?;
+ None
+ }
+ ChaosEvent::WriterPause => {
+ stack.pause_writer()?;
+ None
+ }
+ ChaosEvent::WriterResume => {
+ stack.resume_writer()?;
+ None
+ }
+ ChaosEvent::RouterKill => Some(stack.kill_coordinator_router().await?),
+ };
+ println!(
+ "Chaos at {:.1}s: {event} → pod {} | {}",
+ traffic_start.elapsed().as_secs_f64(),
+ pod.as_deref().unwrap_or("-"),
+ stack.coordination_report().await,
+ );
+
+ // Immediately after the first handoff-creating event, optionally
+ // hunt the resulting handoff and kill its target mid-flight.
+ if handoff_kill_armed && creates_handoff {
+ handoff_kill_armed = false;
+ match stack.kill_handoff_target(Duration::from_secs(15)).await? {
+ Some(victim) => println!(
+ "Chaos at {:.1}s: killed handoff target → pod {victim} | {}",
+ traffic_start.elapsed().as_secs_f64(),
+ stack.coordination_report().await,
+ ),
+ None => println!("No in-flight handoff observed; handoff-target kill skipped"),
+ }
+ }
+ }
+
+ traffic.await.context("traffic task panicked")??;
+ let prober_violations = probers.await.context("prober task panicked")??;
+
+ // Verification asserts data visibility on a converged topology, not
+ // recovery speed: chaos legitimately leaves handoffs to re-drive, and
+ // the protocol's convergence is bounded (worst known case ~40s via the
+ // drained pod's lifecycle timeout). An already-settled run waits zero
+ // time; a run that cannot converge fails here with the stuck state.
+ if let Some(stack) = stack.as_mut() {
+ let settled = stack
+ .wait_converged(Duration::from_secs(90))
+ .await
+ .context("coordination must converge before verification")?;
+ println!(
+ "Post-traffic coordination settled in {:.1}s: {}",
+ settled.as_secs_f64(),
+ stack.coordination_report().await
+ );
+ }
+
+ println!("Verifying strong reads...");
+ let mut violations = prober_violations;
+ violations.extend(state.take_anomalies().await);
+ violations.extend(blast::verify_strong(&client, &collector, &state, args.team_id).await?);
+
+ println!("Waiting for the writer to drain, then verifying Postgres...");
+ let journal = state.snapshot().await;
+ violations.extend(verify_postgres(&pool, &args.pg_target_table, args.team_id, &journal).await?);
+
+ print_report(
+ "gate",
+ &collector,
+ args.team_id,
+ person_ids.len(),
+ &violations,
+ );
+
+ if !args.keep_data {
+ let persons = seed::cleanup_team(&pool, args.team_id).await?;
+ if args.pg_target_table != "posthog_person" {
+ seed::cleanup_target_table(&pool, &args.pg_target_table, args.team_id).await?;
+ }
+ println!("Cleaned up {persons} persons");
+ }
+
+ if let Some(stack) = stack {
+ 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?;
+ } else {
+ stack.down().await?;
+ }
+ }
+
+ 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");
+ }
+ println!("Gate passed: every acked write visible in strong reads and Postgres");
+ Ok(())
+}
+
+/// Poll Postgres until every journaled person row contains all acked
+/// property writes at the acked version, or the quiesce deadline passes.
+/// Returns the outstanding violations (empty = converged).
+async fn verify_postgres(
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+ journal: &HashMap<i64, ExpectedPerson>,
+) -> Result<Vec<ConsistencyViolation>> {
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ let person_ids: Vec<i64> = journal.keys().copied().collect();
+ if person_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let query = format!(
+ "SELECT id, properties::text AS properties, version \
+ FROM {table} WHERE team_id = $1 AND id = ANY($2)"
+ );
+ let deadline = Instant::now() + QUIESCE_DEADLINE;
+ loop {
+ let rows = sqlx::query(&query)
+ .bind(team)
+ .bind(&person_ids)
+ .fetch_all(pool)
+ .await
+ .context("reading persons from Postgres")?;
+
+ let mut by_id: HashMap<i64, (serde_json::Value, i64)> = HashMap::new();
+ for row in rows {
+ let id: i64 = row.get("id");
+ let properties: Option<String> = row.get("properties");
+ let version: Option<i64> = row.get("version");
+ let props = properties
+ .as_deref()
+ .map(serde_json::from_str)
+ .transpose()
+ .context("parsing properties JSON")?
+ .unwrap_or_else(|| serde_json::json!({}));
+ by_id.insert(id, (props, version.unwrap_or(0)));
+ }
+
+ let mut violations = Vec::new();
+ for (person_id, expected) in journal {
+ match by_id.get(person_id) {
+ Some((props, version)) => {
+ violations.extend(verify_properties(
+ *person_id,
+ &expected.written_properties,
+ props,
+ ));
+ // The highest acked version is a floor, not an exact
+ // target: a write that produced its record but lost the
+ // response (a drain, a client timeout) is unacked yet
+ // still applied, legitimately leaving the row above the
+ // floor. Below it, an acked write never reached
+ // Postgres.
+ if *version < expected.last_version {
+ violations.push(ConsistencyViolation {
+ person_id: *person_id,
+ key: "__version".to_string(),
+ expected: serde_json::json!(format!(">= {}", expected.last_version)),
+ actual: serde_json::json!(version),
+ });
+ }
+ }
+ None => {
+ violations.push(ConsistencyViolation {
+ person_id: *person_id,
+ key: "__row".to_string(),
+ expected: serde_json::json!("present"),
+ actual: serde_json::Value::Null,
+ });
+ }
+ }
+ }
+
+ if violations.is_empty() {
+ return Ok(violations);
+ }
+ if Instant::now() > deadline {
+ tracing::error!(
+ outstanding = violations.len(),
+ "Postgres did not converge within {QUIESCE_DEADLINE:?}"
+ );
+ return Ok(violations);
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use clap::Parser;
+
+ use super::*;
+ use crate::cli::{Cli, Command};
+
+ fn gate_args(extra: &[&str]) -> GateArgs {
+ let mut argv = vec!["personhog-test-harness", "gate"];
+ argv.extend_from_slice(extra);
+ match Cli::try_parse_from(argv)
+ .expect("gate args must parse")
+ .command
+ {
+ Command::Gate(args) => *args,
+ _ => unreachable!("gate subcommand parses to Gate"),
+ }
+ }
+
+ #[test]
+ fn chaos_timeline_is_empty_without_flags() {
+ assert!(chaos_timeline(&gate_args(&[])).is_empty());
+ }
+
+ /// Events must fire in offset order regardless of flag order, and the
+ /// paired disruptions (zombie, writer pause) must schedule their
+ /// resume at start + duration — a mis-built timeline silently runs a
+ /// different scenario than the flags describe.
+ #[test]
+ fn chaos_timeline_sorts_events_and_pairs_stop_with_resume() {
+ let args = gate_args(&[
+ "--kill-after",
+ "10s",
+ "--shutdown-after",
+ "5s",
+ "--zombie-after",
+ "7s",
+ "--zombie-duration",
+ "3s",
+ "--writer-pause-after",
+ "2s",
+ "--writer-pause-duration",
+ "1s",
+ ]);
+ let rendered: Vec<(u64, String)> = chaos_timeline(&args)
+ .iter()
+ .map(|(after, event)| (after.as_secs(), event.to_string()))
+ .collect();
+ let expected: Vec<(u64, String)> = [
+ (2, "writer pause (lag injection)"),
+ (3, "writer resume"),
+ (5, "graceful shutdown"),
+ (7, "zombie stop (SIGSTOP + lease revoke)"),
+ (10, "kill (fast lease revoke)"),
+ (10, "zombie resume (SIGCONT)"),
+ ]
+ .into_iter()
+ .map(|(after, event)| (after, event.to_string()))
+ .collect();
+ assert_eq!(rendered, expected);
+ }
+}
diff --git a/rust/personhog-test-harness/src/scenarios/mod.rs b/rust/personhog-test-harness/src/scenarios/mod.rs
new file mode 100644
index 000000000000..cf036e04a2e0
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/mod.rs
@@ -0,0 +1,4 @@
+pub mod blast;
+pub mod consistency;
+pub mod gate;
+pub mod seed_cmd;
diff --git a/rust/personhog-test-harness/src/scenarios/seed_cmd.rs b/rust/personhog-test-harness/src/scenarios/seed_cmd.rs
new file mode 100644
index 000000000000..32a8c9e9aed7
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/seed_cmd.rs
@@ -0,0 +1,32 @@
+use anyhow::{Context, Result};
+use sqlx::postgres::PgPool;
+
+use crate::cli::{CleanupArgs, SeedArgs};
+use crate::seed;
+
+pub async fn run(args: SeedArgs) -> Result<()> {
+ let pool = PgPool::connect(&args.persons_db_url)
+ .await
+ .context("connecting to persons DB")?;
+
+ let ids = seed::seed_persons(&pool, args.team_id, args.count).await?;
+
+ println!("Seeded {} persons for team {}", ids.len(), args.team_id);
+ println!();
+ println!(
+ " --team-id {} --person-ids {}",
+ args.team_id,
+ ids.iter().map(i64::to_string).collect::<Vec<_>>().join(",")
+ );
+ Ok(())
+}
+
+pub async fn run_cleanup(args: CleanupArgs) -> Result<()> {
+ let pool = PgPool::connect(&args.persons_db_url)
+ .await
+ .context("connecting to persons DB")?;
+
+ let persons = seed::cleanup_team(&pool, args.team_id).await?;
+ println!("Deleted {persons} persons for team {}", args.team_id);
+ Ok(())
+}
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
new file mode 100644
index 000000000000..3dd0f5f6df1e
--- /dev/null
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -0,0 +1,114 @@
+use anyhow::{bail, Context, Result};
+use sqlx::postgres::PgPool;
+
+/// Seed `count` persons for `team_id` directly in Postgres and return their
+/// ids. Ids come from the production sequence so they are unique against
+/// real data and spread across leader partitions exactly like organic ids.
+///
+/// There is no team to seed: the persons database has no team table and no
+/// foreign key on `team_id` — a team exists here only as an integer value
+/// on rows, so the first insert brings the harness team into existence and
+/// a team-wide delete removes every trace of it.
+///
+/// This writes SQL instead of calling CreatePerson because the create RPC's
+/// future is still being settled; this function is the seam where the RPC
+/// swaps in.
+pub async fn seed_persons(pool: &PgPool, team_id: i64, count: u32) -> Result<Vec<i64>> {
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+
+ let ids: Vec<i64> =
+ sqlx::query_scalar("SELECT nextval('posthog_person_id_seq') FROM generate_series(1, $1)")
+ .bind(count as i32)
+ .fetch_all(pool)
+ .await
+ .context("allocating person ids")?;
+
+ let teams: Vec<i32> = vec![team; ids.len()];
+ let uuids: Vec<String> = ids
+ .iter()
+ .map(|_| uuid::Uuid::new_v4().to_string())
+ .collect();
+
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_person (
+ id, team_id, uuid, properties, properties_last_updated_at,
+ properties_last_operation, created_at, version, is_identified
+ )
+ SELECT id, team_id, uuid::uuid, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, now(), 0, false
+ FROM UNNEST($1::bigint[], $2::int[], $3::text[]) AS u(id, team_id, uuid)
+ "#,
+ )
+ .bind(&ids)
+ .bind(&teams)
+ .bind(&uuids)
+ .execute(pool)
+ .await
+ .context("inserting seed persons")?;
+
+ Ok(ids)
+}
+
+/// Delete a team's rows from a writer target table other than
+/// posthog_person (e.g. the dev stack's personhog_person_tmp validation
+/// table). The table name comes from the operator's CLI, but sanity-check
+/// it anyway since it is interpolated into SQL.
+pub async fn cleanup_target_table(pool: &PgPool, table: &str, team_id: i64) -> Result<u64> {
+ validate_table_name(table)?;
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ let deleted = sqlx::query(&format!("DELETE FROM {table} WHERE team_id = $1"))
+ .bind(team)
+ .execute(pool)
+ .await
+ .with_context(|| format!("cleaning up {table}"))?
+ .rows_affected();
+ Ok(deleted)
+}
+
+pub fn validate_table_name(table: &str) -> Result<()> {
+ if table.is_empty() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ bail!("invalid table name: {table}");
+ }
+ Ok(())
+}
+
+/// Delete all persons for `team_id`. The harness owns its team ids
+/// outright, so a team-wide delete is the whole cleanup. Nothing writes
+/// distinct-id rows today (traffic is id-keyed), so nothing cleans them —
+/// that changes together when seeding grows a mechanism that writes them.
+pub async fn cleanup_team(pool: &PgPool, team_id: i64) -> Result<u64> {
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+
+ let persons = sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")
+ .bind(team)
+ .execute(pool)
+ .await
+ .context("deleting persons")?
+ .rows_affected();
+
+ Ok(persons)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::validate_table_name;
+
+ #[test]
+ fn validate_table_name_gates_what_reaches_sql_interpolation() {
+ for ok in ["posthog_person", "personhog_person_tmp", "t1"] {
+ assert!(validate_table_name(ok).is_ok(), "{ok} should be valid");
+ }
+ for bad in [
+ "",
+ "posthog_person; DROP TABLE posthog_person",
+ "table-name",
+ "table name",
+ "table\"quoted",
+ ] {
+ assert!(
+ validate_table_name(bad).is_err(),
+ "{bad:?} should be rejected"
+ );
+ }
+ }
+}
diff --git a/rust/personhog-test-harness/src/stack/etcd.rs b/rust/personhog-test-harness/src/stack/etcd.rs
new file mode 100644
index 000000000000..fbfdb4a10319
--- /dev/null
+++ b/rust/personhog-test-harness/src/stack/etcd.rs
@@ -0,0 +1,157 @@
+use anyhow::{bail, Context, Result};
+use assignment_coordination::store::{EtcdStore, StoreConfig};
+use personhog_coordination::store::PersonhogStore;
+
+pub async fn connect(endpoints: &str, prefix: &str) -> Result<PersonhogStore> {
+ let config = StoreConfig {
+ endpoints: endpoints.split(',').map(str::to_string).collect(),
+ prefix: prefix.to_string(),
+ };
+ let store = EtcdStore::connect(config)
+ .await
+ .context("connecting to etcd")?;
+ Ok(PersonhogStore::new(store))
+}
+
+/// Wipe all coordination state under the harness prefix and set the
+/// partition count, giving each run a clean slate.
+pub async fn reset(store: &PersonhogStore, partitions: u32) -> Result<()> {
+ store.delete_all().await.context("clearing etcd prefix")?;
+ store
+ .set_total_partitions(partitions)
+ .await
+ .context("setting total_partitions")?;
+ Ok(())
+}
+
+/// Revoke the etcd lease attached to a pod's registration. Deleting the key
+/// through the lease makes the coordinator detect the pod's death
+/// immediately instead of waiting out the lease TTL — the "fast" half of a
+/// kill.
+pub async fn revoke_pod_lease(store: &PersonhogStore, pod_name: &str) -> Result<()> {
+ revoke_registration_lease(store, &format!("pods/{pod_name}")).await
+}
+
+/// Revoke the lease attached to a router's registration, so the coordinator
+/// stops counting the dead router toward freeze-ack quorums immediately.
+pub async fn revoke_router_lease(store: &PersonhogStore, router_name: &str) -> Result<()> {
+ revoke_registration_lease(store, &format!("routers/{router_name}")).await
+}
+
+/// If `holder` currently holds the coordinator election, revoke the
+/// election lease so a surviving router can win immediately. Without this
+/// a killed coordinator blocks the election for the full lease TTL (15s by
+/// default), during which no handoffs can be created at all.
+pub async fn revoke_coordinator_lease_if_held_by(
+ store: &PersonhogStore,
+ holder: &str,
+) -> Result<bool> {
+ let Some(leader) = store
+ .get_leader()
+ .await
+ .context("reading coordinator election key")?
+ else {
+ return Ok(false);
+ };
+ if leader.holder != holder {
+ return Ok(false);
+ }
+
+ store
+ .inner()
+ .client()
+ .clone()
+ .lease_revoke(leader.lease_id)
+ .await
+ .context("revoking coordinator election lease")?;
+ tracing::info!(
+ holder,
+ lease_id = leader.lease_id,
+ "revoked coordinator election lease"
+ );
+ Ok(true)
+}
+
+/// Wait until `holder` owns the coordinator election. Used at bring-up so
+/// chaos that targets "the coordinator" is deterministic instead of
+/// depending on which router won the initial campaign.
+pub async fn wait_for_leader(
+ store: &PersonhogStore,
+ holder: &str,
+ deadline: std::time::Duration,
+) -> Result<()> {
+ let start = std::time::Instant::now();
+ loop {
+ if let Some(leader) = store.get_leader().await.unwrap_or(None) {
+ if leader.holder == holder {
+ return Ok(());
+ }
+ }
+ if start.elapsed() > deadline {
+ bail!("{holder} did not acquire coordinator leadership within {deadline:?}");
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+}
+
+async fn revoke_registration_lease(store: &PersonhogStore, key_suffix: &str) -> Result<()> {
+ let prefix = store.inner().prefix();
+ let key = format!("{prefix}{key_suffix}");
+
+ let resp = store
+ .inner()
+ .client()
+ .clone()
+ .get(key.clone(), None)
+ .await
+ .context("reading registration key from etcd")?;
+
+ let kv = resp
+ .kvs()
+ .first()
+ .with_context(|| format!("{key} not registered in etcd"))?;
+
+ let lease_id = kv.lease();
+ if lease_id == 0 {
+ bail!("{key} has no lease attached");
+ }
+
+ store
+ .inner()
+ .client()
+ .clone()
+ .lease_revoke(lease_id)
+ .await
+ .context("revoking registration lease")?;
+
+ tracing::info!(key, lease_id, "revoked etcd lease");
+ Ok(())
+}
+
+/// One readiness probe: the coordinator has assigned every partition and
+/// initial handoffs have completed — N registered pods, all partitions
+/// Active, no in-flight handoffs. Returns `None` when ready, or a progress
+/// report while waiting.
+pub async fn check_ready(
+ store: &PersonhogStore,
+ partitions: u32,
+ leaders: u32,
+) -> Result<Option<String>> {
+ let pods = store.list_pods().await.unwrap_or_default();
+ let assignments = store.list_assignments().await.unwrap_or_default();
+ let handoffs = store.list_handoffs().await.unwrap_or_default();
+
+ let assigned = assignments.len() as u32;
+ if pods.len() as u32 >= leaders && assigned == partitions && handoffs.is_empty() {
+ return Ok(None);
+ }
+
+ Ok(Some(format!(
+ "pods {}/{}, partitions {}/{}, handoffs in flight {}",
+ pods.len(),
+ leaders,
+ assigned,
+ partitions,
+ handoffs.len()
+ )))
+}
diff --git a/rust/personhog-test-harness/src/stack/kafka.rs b/rust/personhog-test-harness/src/stack/kafka.rs
new file mode 100644
index 000000000000..803ebe895359
--- /dev/null
+++ b/rust/personhog-test-harness/src/stack/kafka.rs
@@ -0,0 +1,65 @@
+use std::time::Duration;
+
+use anyhow::{bail, Context, Result};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::config::ClientConfig;
+use rdkafka::types::RDKafkaErrorCode;
+
+fn admin_client(kafka_hosts: &str) -> Result<AdminClient<DefaultClientContext>> {
+ ClientConfig::new()
+ .set("bootstrap.servers", kafka_hosts)
+ .create()
+ .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.
+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)));
+
+ let new_topic = NewTopic::new(topic, partitions as i32, TopicReplication::Fixed(1));
+ let results = admin
+ .create_topics([&new_topic], &options)
+ .await
+ .context("creating changelog topic")?;
+
+ for result in results {
+ match result {
+ Ok(_) => {}
+ Err((name, RDKafkaErrorCode::TopicAlreadyExists)) => {
+ bail!(
+ "topic {name} already exists — a previous run may not have torn down; \
+ delete it or pass a different --topic"
+ );
+ }
+ Err((name, code)) => bail!("failed to create topic {name}: {code}"),
+ }
+ }
+
+ tracing::info!(topic, partitions, "created changelog topic");
+ Ok(())
+}
+
+pub async fn delete_topic(kafka_hosts: &str, topic: &str) -> Result<()> {
+ let admin = admin_client(kafka_hosts)?;
+ let options = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+
+ let results = admin
+ .delete_topics(&[topic], &options)
+ .await
+ .context("deleting changelog topic")?;
+
+ for result in results {
+ match result {
+ Ok(_) | Err((_, RDKafkaErrorCode::UnknownTopicOrPartition)) => {}
+ Err((name, code)) => bail!("failed to delete topic {name}: {code}"),
+ }
+ }
+
+ tracing::info!(topic, "deleted changelog topic");
+ Ok(())
+}
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
new file mode 100644
index 000000000000..48cddbd35b91
--- /dev/null
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -0,0 +1,621 @@
+use std::collections::{HashMap, HashSet};
+use std::fs;
+use std::path::PathBuf;
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Context, Result};
+use personhog_coordination::store::PersonhogStore;
+use personhog_coordination::types::HandoffPhase;
+
+mod etcd;
+mod kafka;
+mod process;
+
+use process::ServiceProcess;
+
+/// Ports sit in their own range so a harness stack can run alongside the
+/// dev stack (gRPC 50051-50054, metrics 9100-9105) without collisions.
+/// Routers occupy base..base+3 and leaders start at base+6, which caps the
+/// router count at 4.
+const REPLICA_GRPC_PORT: u16 = 51051;
+const ROUTER_GRPC_BASE_PORT: u16 = 51054;
+const LEADER_GRPC_BASE_PORT: u16 = 51060;
+const REPLICA_METRICS_PORT: u16 = 51151;
+const WRITER_METRICS_PORT: u16 = 51153;
+const ROUTER_METRICS_BASE_PORT: u16 = 51154;
+const LEADER_METRICS_BASE_PORT: u16 = 51160;
+const MAX_ROUTERS: u32 = 4;
+
+const ETCD_PREFIX: &str = "/personhog-test-harness/";
+const READY_DEADLINE: Duration = Duration::from_secs(90);
+const SHUTDOWN_GRACE: Duration = Duration::from_secs(5);
+
+pub struct StackConfig {
+ /// Directory containing the service binaries (the cargo target dir).
+ pub bin_dir: PathBuf,
+ pub leaders: u32,
+ pub routers: u32,
+ pub partitions: u32,
+ pub kafka_hosts: String,
+ pub etcd_endpoints: String,
+ pub persons_db_url: String,
+ /// Writer flush cadence. Short by default so gate quiesce is quick.
+ pub writer_flush_interval_ms: u64,
+ /// The table the writer upserts into.
+ pub pg_target_table: String,
+ /// Leader in-memory cache capacity (entries). Lower it below the seeded
+ /// person count to put the cache under eviction pressure.
+ pub cache_memory_capacity: usize,
+ /// etcd lease TTL for leaders, in seconds. Bounds how long a crashed
+ /// (unrevoked) leader stays the registered owner.
+ pub leader_lease_ttl: i64,
+}
+
+/// A locally-spawned personhog stack: replica, writer, N leaders, and M
+/// leader-mode routers (each hosting a coordinator candidate), all pointed
+/// at the docker-compose Kafka/etcd/Postgres but isolated from the dev
+/// stack via their own ports, etcd prefix, and per-run changelog topic.
+pub struct Stack {
+ config: StackConfig,
+ infra: Vec<ServiceProcess>,
+ /// Live routers, keyed by registration name. The first spawned almost
+ /// always wins the coordinator election, so traffic targets the LAST
+ /// router and chaos kills the first.
+ routers: Vec<(String, ServiceProcess)>,
+ /// Live leaders, keyed by the pod name they registered with.
+ leaders: Vec<(String, ServiceProcess)>,
+ /// A SIGSTOPped zombie leader, waiting for its SIGCONT.
+ paused: Vec<(String, ServiceProcess)>,
+ /// Processes removed by chaos (killed, draining, or resumed zombies);
+ /// their exit is expected, so they are excluded from liveness checks.
+ retired: Vec<ServiceProcess>,
+ next_leader_index: u32,
+ store: PersonhogStore,
+ topic: String,
+ pub router_url: String,
+ pub log_dir: PathBuf,
+}
+
+impl Stack {
+ pub async fn up(config: StackConfig) -> Result<Self> {
+ if config.routers == 0 || config.routers > MAX_ROUTERS {
+ bail!("--routers must be between 1 and {MAX_ROUTERS}");
+ }
+
+ let run_id = chrono::Utc::now().format("%Y%m%d_%H%M%S").to_string();
+ let topic = format!("personhog_test_harness_{run_id}");
+ let log_dir = config.bin_dir.join("harness-logs").join(&run_id);
+ fs::create_dir_all(&log_dir)
+ .with_context(|| format!("creating log dir {}", log_dir.display()))?;
+
+ let binaries = [
+ "personhog-replica",
+ "personhog-router",
+ "personhog-leader",
+ "personhog-writer",
+ ];
+ for bin in binaries {
+ let path = config.bin_dir.join(bin);
+ if !path.exists() {
+ bail!(
+ "{} not found — build the stack first:\n cargo build -p personhog-replica \
+ -p personhog-router -p personhog-leader -p personhog-writer",
+ path.display()
+ );
+ }
+ }
+
+ tracing::info!(
+ leaders = config.leaders,
+ routers = config.routers,
+ partitions = config.partitions,
+ topic,
+ log_dir = %log_dir.display(),
+ "bringing up 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 mut infra = Vec::new();
+
+ infra.push(ServiceProcess::spawn(
+ "replica",
+ &config.bin_dir.join("personhog-replica"),
+ &[
+ ("GRPC_ADDRESS", format!("127.0.0.1:{REPLICA_GRPC_PORT}")),
+ ("PRIMARY_DATABASE_URL", config.persons_db_url.clone()),
+ ("METRICS_PORT", REPLICA_METRICS_PORT.to_string()),
+ ],
+ &log_dir,
+ )?);
+
+ infra.push(ServiceProcess::spawn(
+ "writer",
+ &config.bin_dir.join("personhog-writer"),
+ &[
+ ("DATABASE_URL", config.persons_db_url.clone()),
+ ("KAFKA_HOSTS", config.kafka_hosts.clone()),
+ ("KAFKA_TOPIC", topic.clone()),
+ (
+ "KAFKA_CONSUMER_GROUP",
+ "personhog-test-harness-writer".to_string(),
+ ),
+ ("PG_TARGET_TABLE", config.pg_target_table.clone()),
+ (
+ "FLUSH_INTERVAL_MS",
+ config.writer_flush_interval_ms.to_string(),
+ ),
+ ("METRICS_PORT", WRITER_METRICS_PORT.to_string()),
+ ],
+ &log_dir,
+ )?);
+
+ // The first router must win the coordinator election so chaos that
+ // targets "the coordinator" is deterministic: spawn it alone, wait
+ // for it to acquire leadership, then bring up the rest.
+ let mut routers = Vec::new();
+ for i in 0..config.routers {
+ if i == 1 {
+ etcd::wait_for_leader(&store, "harness-router-0", Duration::from_secs(15)).await?;
+ }
+ let name = format!("harness-router-{i}");
+ let proc = ServiceProcess::spawn(
+ &name,
+ &config.bin_dir.join("personhog-router"),
+ &[
+ ("ROUTER_MODE", "leader".to_string()),
+ (
+ "GRPC_ADDRESS",
+ format!("127.0.0.1:{}", ROUTER_GRPC_BASE_PORT + i as u16),
+ ),
+ (
+ "REPLICA_URL",
+ format!("http://127.0.0.1:{REPLICA_GRPC_PORT}"),
+ ),
+ ("ETCD_ENDPOINTS", config.etcd_endpoints.clone()),
+ ("ETCD_PREFIX", ETCD_PREFIX.to_string()),
+ ("BACKEND_TIMEOUT_MS", "5000".to_string()),
+ ("POD_NAME", name.clone()),
+ (
+ "METRICS_PORT",
+ (ROUTER_METRICS_BASE_PORT + i as u16).to_string(),
+ ),
+ ],
+ &log_dir,
+ )?;
+ routers.push((name, proc));
+ }
+
+ // Traffic targets the last router: the first spawned usually wins
+ // the coordinator election, so a coordinator kill (which targets
+ // the first) leaves the traffic path intact.
+ let traffic_router_port = ROUTER_GRPC_BASE_PORT + (config.routers - 1) as u16;
+ let router_url = format!("http://127.0.0.1:{traffic_router_port}");
+
+ let mut stack = Self {
+ config,
+ infra,
+ routers,
+ leaders: Vec::new(),
+ paused: Vec::new(),
+ retired: Vec::new(),
+ next_leader_index: 0,
+ store,
+ topic,
+ router_url,
+ log_dir,
+ };
+
+ for _ in 0..stack.config.leaders {
+ stack.spawn_leader()?;
+ }
+
+ let (partitions, leaders) = (stack.config.partitions, stack.config.leaders);
+ stack
+ .wait_ready(partitions, leaders)
+ .await
+ .inspect_err(|_| stack.dump_recent_logs())?;
+
+ Ok(stack)
+ }
+
+ /// Spawn one more leader. The pod registers with an explicit host:port
+ /// name, which the router's resolver dials as-is.
+ pub fn spawn_leader(&mut self) -> Result<String> {
+ let index = self.next_leader_index;
+ self.next_leader_index += 1;
+
+ let grpc_port = LEADER_GRPC_BASE_PORT + index as u16;
+ let pod_name = format!("127.0.0.1:{grpc_port}");
+ // Heartbeats must land well inside the lease window or a healthy
+ // pod's lease expires between renewals.
+ let heartbeat_secs = (self.config.leader_lease_ttl / 3).max(1);
+ let proc = ServiceProcess::spawn(
+ &format!("leader-{index}"),
+ &self.config.bin_dir.join("personhog-leader"),
+ &[
+ ("GRPC_ADDRESS", pod_name.clone()),
+ ("POD_NAME", pod_name.clone()),
+ ("LEASE_TTL", self.config.leader_lease_ttl.to_string()),
+ ("HEARTBEAT_INTERVAL_SECS", heartbeat_secs.to_string()),
+ (
+ "CACHE_MEMORY_CAPACITY",
+ self.config.cache_memory_capacity.to_string(),
+ ),
+ ("ETCD_ENDPOINTS", self.config.etcd_endpoints.clone()),
+ ("ETCD_PREFIX", ETCD_PREFIX.to_string()),
+ ("KAFKA_HOSTS", self.config.kafka_hosts.clone()),
+ ("KAFKA_PERSON_STATE_TOPIC", self.topic.clone()),
+ // Must match the spawned writer's consumer group or the
+ // leader's committed-offset queries (warming ranges, dirty
+ // index pruning) silently see no progress at all.
+ (
+ "WRITER_CONSUMER_GROUP",
+ "personhog-test-harness-writer".to_string(),
+ ),
+ ("FALLBACK_DATABASE_URL", self.config.persons_db_url.clone()),
+ (
+ "METRICS_PORT",
+ (LEADER_METRICS_BASE_PORT + index as u16).to_string(),
+ ),
+ ],
+ &self.log_dir,
+ )?;
+
+ self.leaders.push((pod_name.clone(), proc));
+ Ok(pod_name)
+ }
+
+ /// SIGKILL the leader owning the most partitions (a crash, maximum
+ /// blast radius). With `fast`, also revoke its etcd lease so the
+ /// coordinator reacts immediately instead of waiting out the lease TTL.
+ pub async fn kill_leader(&mut self, fast: bool) -> Result<String> {
+ let victim = self.busiest_leader().await?;
+ let (pod_name, mut proc) = self.remove_leader(&victim)?;
+
+ proc.kill_now().await;
+ tracing::info!(pod = %pod_name, fast, "killed leader");
+ if fast {
+ etcd::revoke_pod_lease(&self.store, &pod_name).await?;
+ }
+ self.retired.push(proc);
+ Ok(pod_name)
+ }
+
+ /// SIGTERM the busiest leader and let it drain: it transitions to
+ /// Draining, the coordinator hands its partitions off, and the process
+ /// exits on its own while traffic continues.
+ pub async fn shutdown_leader(&mut self) -> Result<String> {
+ let victim = self.busiest_leader().await?;
+ let (pod_name, proc) = self.remove_leader(&victim)?;
+
+ proc.sigterm();
+ tracing::info!(pod = %pod_name, "requested graceful shutdown");
+ self.retired.push(proc);
+ Ok(pod_name)
+ }
+
+ /// Crash-restart the busiest leader under the same identity: SIGKILL,
+ /// then immediately respawn with the same pod name and ports, the way a
+ /// StatefulSet brings a crashed pod back. The restarted process
+ /// re-registers and must converge on the partitions etcd still says it
+ /// owns.
+ pub async fn restart_leader(&mut self) -> Result<String> {
+ let victim = self.busiest_leader().await?;
+ let position = self
+ .leaders
+ .iter()
+ .position(|(name, _)| *name == victim)
+ .context("victim leader not tracked")?;
+
+ self.leaders[position].1.respawn().await?;
+ tracing::info!(pod = %victim, "crash-restarted leader");
+ Ok(victim)
+ }
+
+ /// Turn the busiest leader into a zombie: SIGSTOP it (unreachable but
+ /// not dead) and revoke its lease so ownership moves while the process
+ /// still holds its old cache and producer. `resume_zombie` wakes it.
+ pub async fn stop_zombie(&mut self) -> Result<String> {
+ let victim = self.busiest_leader().await?;
+ let (pod_name, proc) = self.remove_leader(&victim)?;
+
+ proc.sigstop();
+ tracing::info!(pod = %pod_name, "SIGSTOPped leader (zombie)");
+ etcd::revoke_pod_lease(&self.store, &pod_name).await?;
+ self.paused.push((pod_name.clone(), proc));
+ Ok(pod_name)
+ }
+
+ /// SIGCONT the paused zombie. It wakes believing it still owns its
+ /// partitions; whatever it does next (self-fence, exit, re-register)
+ /// must not corrupt state that has moved to the new owner.
+ pub fn resume_zombie(&mut self) -> Result<String> {
+ let (pod_name, proc) = self
+ .paused
+ .pop()
+ .context("no paused zombie leader to resume")?;
+ proc.sigcont();
+ tracing::info!(pod = %pod_name, "SIGCONTed zombie leader");
+ self.retired.push(proc);
+ Ok(pod_name)
+ }
+
+ /// SIGKILL the first-spawned router — the coordinator, since bring-up
+ /// waits for it to win the election — and revoke both its registration
+ /// lease (so freeze quorums stop counting it) and its election lease
+ /// (so a surviving router takes over immediately instead of waiting
+ /// out the 15s election TTL). Handoffs created after this run under
+ /// the new coordinator.
+ pub async fn kill_coordinator_router(&mut self) -> Result<String> {
+ if self.routers.len() < 2 {
+ bail!("coordinator kill requires at least 2 routers");
+ }
+ let (name, mut proc) = self.routers.remove(0);
+ proc.kill_now().await;
+ etcd::revoke_router_lease(&self.store, &name).await?;
+ let held_election = etcd::revoke_coordinator_lease_if_held_by(&self.store, &name).await?;
+ tracing::info!(router = %name, held_election, "killed coordinator router");
+ self.retired.push(proc);
+ Ok(name)
+ }
+
+ /// Crash-restart the writer: SIGKILL + respawn in the same consumer
+ /// group. Uncommitted records are redelivered; the version-guarded
+ /// upsert must keep the replay idempotent.
+ pub async fn crash_restart_writer(&mut self) -> Result<()> {
+ self.infra_mut("writer")?.respawn().await?;
+ tracing::info!("crash-restarted writer");
+ Ok(())
+ }
+
+ /// SIGSTOP the writer — controlled writer-lag injection.
+ pub fn pause_writer(&mut self) -> Result<()> {
+ self.infra_mut("writer")?.sigstop();
+ tracing::info!("paused writer (lag injection)");
+ Ok(())
+ }
+
+ /// SIGCONT the writer.
+ pub fn resume_writer(&mut self) -> Result<()> {
+ self.infra_mut("writer")?.sigcont();
+ tracing::info!("resumed writer");
+ 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.
+ pub async fn kill_handoff_target(&mut self, deadline: Duration) -> Result<Option<String>> {
+ let start = Instant::now();
+ while start.elapsed() < deadline {
+ let handoffs = self.store.list_handoffs().await.unwrap_or_default();
+ let target = handoffs
+ .iter()
+ .find(|h| h.phase != HandoffPhase::Complete)
+ .map(|h| h.new_owner.clone());
+
+ if let Some(victim) = target {
+ // The target may not be a tracked live leader (e.g. it was
+ // already killed); skip and keep watching if so.
+ if let Ok((pod_name, mut proc)) = self.remove_leader(&victim) {
+ proc.kill_now().await;
+ tracing::info!(pod = %pod_name, "killed handoff target mid-handoff");
+ etcd::revoke_pod_lease(&self.store, &pod_name).await?;
+ self.retired.push(proc);
+ return Ok(Some(pod_name));
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ tracing::warn!("no in-flight handoff observed within {deadline:?}; nothing killed");
+ Ok(None)
+ }
+
+ fn remove_leader(&mut self, pod_name: &str) -> Result<(String, ServiceProcess)> {
+ let position = self
+ .leaders
+ .iter()
+ .position(|(name, _)| name == pod_name)
+ .with_context(|| format!("leader {pod_name} not tracked as live"))?;
+ Ok(self.leaders.remove(position))
+ }
+
+ fn infra_mut(&mut self, name: &str) -> Result<&mut ServiceProcess> {
+ self.infra
+ .iter_mut()
+ .find(|proc| proc.name() == name)
+ .with_context(|| format!("{name} not tracked in stack"))
+ }
+
+ /// The live leader owning the most partitions; falls back to the first
+ /// live leader when assignments are empty.
+ async fn busiest_leader(&self) -> Result<String> {
+ if self.leaders.is_empty() {
+ bail!("no live leaders to target");
+ }
+
+ let assignments = self.store.list_assignments().await.unwrap_or_default();
+ let mut counts: HashMap<&str, usize> = HashMap::new();
+ for assignment in &assignments {
+ *counts.entry(assignment.owner.as_str()).or_default() += 1;
+ }
+
+ let busiest = self
+ .leaders
+ .iter()
+ .map(|(name, _)| name)
+ .max_by_key(|name| (counts.get(name.as_str()).copied().unwrap_or(0), *name));
+ Ok(busiest.expect("leaders is non-empty").clone())
+ }
+
+ /// Wait until coordination has converged after chaos: no handoffs in
+ /// flight and every partition assigned to a leader whose process is
+ /// actually running. Owners are checked against the stack's live
+ /// process list rather than etcd registrations — a draining pod stays
+ /// registered (with a dead gRPC server) until its lifecycle timeout,
+ /// and a briefly-empty handoff list mid-re-drive would otherwise read
+ /// as converged. Returns how long convergence took; an already-settled
+ /// stack returns immediately. Timing out fails the run: a protocol
+ /// that cannot converge is itself a violation, independent of any
+ /// data-visibility check.
+ pub async fn wait_converged(&mut self, deadline: Duration) -> Result<Duration> {
+ let start = Instant::now();
+ let mut last_report = String::new();
+
+ loop {
+ self.check_alive()?;
+
+ let assignments = self.store.list_assignments().await.unwrap_or_default();
+ let handoffs = self.store.list_handoffs().await.unwrap_or_default();
+ let live: HashSet<&str> = self.leaders.iter().map(|(name, _)| name.as_str()).collect();
+ let dead_owned = assignments
+ .iter()
+ .filter(|a| !live.contains(a.owner.as_str()))
+ .count();
+
+ if handoffs.is_empty()
+ && assignments.len() as u32 == self.config.partitions
+ && dead_owned == 0
+ {
+ return Ok(start.elapsed());
+ }
+
+ let report = format!(
+ "partitions assigned {}/{} ({} on dead pods), handoffs in flight {}",
+ assignments.len(),
+ self.config.partitions,
+ dead_owned,
+ handoffs.len()
+ );
+ if report != last_report {
+ tracing::info!("waiting for coordination to converge: {report}");
+ last_report = report;
+ }
+ if start.elapsed() > deadline {
+ bail!("coordination did not converge within {deadline:?}: {last_report}");
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ }
+
+ /// One-line snapshot of coordination state, for chaos event logging.
+ pub async fn coordination_report(&self) -> String {
+ let pods = self.store.list_pods().await.unwrap_or_default();
+ let assignments = self.store.list_assignments().await.unwrap_or_default();
+ let handoffs = self.store.list_handoffs().await.unwrap_or_default();
+ format!(
+ "pods {}, partitions assigned {}/{}, handoffs in flight {}",
+ pods.len(),
+ assignments.len(),
+ self.config.partitions,
+ handoffs.len()
+ )
+ }
+
+ async fn wait_ready(&mut self, partitions: u32, leaders: u32) -> Result<()> {
+ let start = Instant::now();
+ let mut last_report = String::new();
+
+ loop {
+ // Child liveness is checked every probe so a crash-looping
+ // service fails the bring-up immediately instead of timing out.
+ self.check_alive()?;
+
+ match etcd::check_ready(&self.store, partitions, leaders).await? {
+ None => break,
+ Some(report) => {
+ if report != last_report {
+ tracing::info!("waiting for coordination: {report}");
+ last_report = report;
+ }
+ if start.elapsed() > READY_DEADLINE {
+ bail!("coordination not ready after {READY_DEADLINE:?}: {last_report}");
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+
+ for i in 0..self.routers.len() {
+ let addr = format!("127.0.0.1:{}", ROUTER_GRPC_BASE_PORT + i as u16);
+ wait_tcp(&addr, Duration::from_secs(10)).await?;
+ }
+ tracing::info!(
+ router = %self.router_url,
+ elapsed_ms = start.elapsed().as_millis() as u64,
+ "stack ready"
+ );
+ Ok(())
+ }
+
+ /// Fail if any spawned service has exited (retired and paused
+ /// processes excluded — their state is chaos-induced).
+ pub fn check_alive(&mut self) -> Result<()> {
+ let procs = self
+ .infra
+ .iter_mut()
+ .chain(self.routers.iter_mut().map(|(_, proc)| proc))
+ .chain(self.leaders.iter_mut().map(|(_, proc)| proc));
+ for proc in procs {
+ if let Some(status) = proc.exited() {
+ let tail = proc.log_tail(30);
+ bail!(
+ "service {} exited ({status}); last log lines:\n{tail}",
+ proc.name()
+ );
+ }
+ }
+ Ok(())
+ }
+
+ fn dump_recent_logs(&self) {
+ let procs = self
+ .infra
+ .iter()
+ .chain(self.routers.iter().map(|(_, proc)| proc))
+ .chain(self.leaders.iter().map(|(_, proc)| proc));
+ for proc in procs {
+ tracing::error!(
+ service = %proc.name(),
+ log = %proc.log_path().display(),
+ "--- last log lines ---\n{}",
+ proc.log_tail(15)
+ );
+ }
+ }
+
+ pub async fn down(self) -> Result<()> {
+ tracing::info!("tearing down stack");
+ // Teardown discards all run state (topic deleted below, etcd prefix
+ // wiped on the next bring-up), so services stop concurrently with a
+ // short grace rather than draining through handoffs.
+ let terminations = self
+ .infra
+ .into_iter()
+ .chain(self.routers.into_iter().map(|(_, proc)| proc))
+ .chain(self.leaders.into_iter().map(|(_, proc)| proc))
+ .chain(self.paused.into_iter().map(|(_, proc)| proc))
+ .chain(self.retired)
+ .map(|proc| proc.terminate(SHUTDOWN_GRACE));
+ futures::future::join_all(terminations).await;
+
+ kafka::delete_topic(&self.config.kafka_hosts, &self.topic).await?;
+ Ok(())
+ }
+}
+
+async fn wait_tcp(addr: &str, deadline: Duration) -> Result<()> {
+ let start = Instant::now();
+ loop {
+ if tokio::net::TcpStream::connect(addr).await.is_ok() {
+ return Ok(());
+ }
+ if start.elapsed() > deadline {
+ bail!("{addr} not accepting connections after {deadline:?}");
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
diff --git a/rust/personhog-test-harness/src/stack/process.rs b/rust/personhog-test-harness/src/stack/process.rs
new file mode 100644
index 000000000000..b452ce3051d9
--- /dev/null
+++ b/rust/personhog-test-harness/src/stack/process.rs
@@ -0,0 +1,179 @@
+use std::path::{Path, PathBuf};
+use std::process::{Command as StdCommand, Stdio};
+use std::time::Duration;
+use std::{env, fs};
+
+use anyhow::{Context, Result};
+use tokio::process::{Child, Command};
+
+/// Everything needed to (re)spawn a service, retained so chaos events can
+/// restart a process under the same identity.
+struct ServiceSpec {
+ name: String,
+ binary: PathBuf,
+ envs: Vec<(String, String)>,
+ log_path: PathBuf,
+}
+
+impl ServiceSpec {
+ fn spawn(&self) -> Result<Child> {
+ // Append so a respawned service continues its predecessor's log.
+ let log_file = fs::File::options()
+ .create(true)
+ .append(true)
+ .open(&self.log_path)
+ .with_context(|| format!("opening log file {}", self.log_path.display()))?;
+ let stderr_file = log_file.try_clone().context("cloning log handle")?;
+
+ let mut command = Command::new(&self.binary);
+ command
+ .env_clear()
+ // PATH and HOME survive so the binaries can resolve tools and
+ // dotfiles (librdkafka, DNS, etc.) the way they do in dev.
+ .envs(env::vars().filter(|(k, _)| k == "PATH" || k == "HOME"))
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "info")
+ .stdout(Stdio::from(log_file))
+ .stderr(Stdio::from(stderr_file))
+ .kill_on_drop(true);
+ for (key, value) in &self.envs {
+ command.env(key, value);
+ }
+
+ let child = command
+ .spawn()
+ .with_context(|| format!("spawning {} from {}", self.name, self.binary.display()))?;
+
+ tracing::info!(
+ service = %self.name,
+ pid = child.id(),
+ log = %self.log_path.display(),
+ "spawned"
+ );
+ Ok(child)
+ }
+}
+
+/// A spawned service child process with its log file and respawnable spec.
+pub struct ServiceProcess {
+ spec: ServiceSpec,
+ child: Child,
+}
+
+impl ServiceProcess {
+ pub fn spawn(
+ name: &str,
+ binary: &Path,
+ envs: &[(&str, String)],
+ log_dir: &Path,
+ ) -> Result<Self> {
+ let spec = ServiceSpec {
+ name: name.to_string(),
+ binary: binary.to_path_buf(),
+ envs: envs
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.clone()))
+ .collect(),
+ log_path: log_dir.join(format!("{name}.log")),
+ };
+ let child = spec.spawn()?;
+ Ok(Self { spec, child })
+ }
+
+ pub fn name(&self) -> &str {
+ &self.spec.name
+ }
+
+ pub fn log_path(&self) -> &Path {
+ &self.spec.log_path
+ }
+
+ /// Whether the process has exited. Returns the exit description if so.
+ pub fn exited(&mut self) -> Option<String> {
+ match self.child.try_wait() {
+ Ok(Some(status)) => Some(status.to_string()),
+ Ok(None) => None,
+ Err(e) => Some(format!("unknown ({e})")),
+ }
+ }
+
+ /// Kill the current process (if still running) and start a fresh one
+ /// from the same spec — a crash-restart under the same identity.
+ pub async fn respawn(&mut self) -> Result<()> {
+ self.kill_now().await;
+ self.child = self.spec.spawn()?;
+ Ok(())
+ }
+
+ fn signal(&self, signal: &str) {
+ let Some(pid) = self.child.id() else {
+ return;
+ };
+ // tokio's Child only exposes SIGKILL; other signals go through
+ // kill(1) to avoid pulling in a signals dependency.
+ if let Err(e) = StdCommand::new("kill")
+ .args([signal, &pid.to_string()])
+ .status()
+ {
+ tracing::warn!(service = %self.spec.name, signal, error = %e, "failed to signal");
+ }
+ }
+
+ /// Send SIGTERM without waiting — the process drains and exits on its
+ /// own schedule (used by chaos graceful shutdowns, where traffic keeps
+ /// flowing while the leader hands its partitions off).
+ pub fn sigterm(&self) {
+ self.signal("-TERM");
+ }
+
+ /// SIGSTOP — freeze the process without killing it. To its peers it is
+ /// unreachable but not gone: connections hang, heartbeats stop, and the
+ /// process resumes exactly where it was on SIGCONT.
+ pub fn sigstop(&self) {
+ self.signal("-STOP");
+ }
+
+ /// SIGCONT — wake a stopped process.
+ pub fn sigcont(&self) {
+ self.signal("-CONT");
+ }
+
+ /// SIGKILL immediately — a crash, not a shutdown.
+ pub async fn kill_now(&mut self) {
+ if let Err(e) = self.child.kill().await {
+ tracing::warn!(service = %self.spec.name, error = %e, "failed to kill");
+ }
+ }
+
+ /// Ask the process to shut down gracefully (SIGTERM), then wait up to
+ /// `grace` before killing it outright.
+ pub async fn terminate(mut self, grace: Duration) -> Result<()> {
+ // A stopped process cannot handle SIGTERM; wake it first so
+ // teardown does not hang on a paused zombie.
+ self.sigcont();
+ self.sigterm();
+
+ match tokio::time::timeout(grace, self.child.wait()).await {
+ Ok(status) => {
+ tracing::info!(service = %self.spec.name, status = ?status.ok(), "exited");
+ }
+ Err(_) => {
+ tracing::warn!(service = %self.spec.name, "did not exit within grace period, killing");
+ if let Err(e) = self.child.kill().await {
+ tracing::warn!(service = %self.spec.name, error = %e, "failed to kill");
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// Return the last `lines` lines of the service's log, for error reports.
+ pub fn log_tail(&self, lines: usize) -> String {
+ let Ok(content) = fs::read_to_string(&self.spec.log_path) else {
+ return String::new();
+ };
+ let all: Vec<&str> = content.lines().collect();
+ let start = all.len().saturating_sub(lines);
+ all[start..].join("\n")
+ }
+}
diff --git a/rust/personhog-test-harness/src/state.rs b/rust/personhog-test-harness/src/state.rs
new file mode 100644
index 000000000000..022bfe0a1720
--- /dev/null
+++ b/rust/personhog-test-harness/src/state.rs
@@ -0,0 +1,306 @@
+use std::collections::{HashMap, HashSet};
+use std::mem;
+use std::sync::Arc;
+
+use tokio::sync::RwLock;
+
+use crate::report::ConsistencyViolation;
+
+/// Journal of acked writes. Every property write acked by the leader path is
+/// recorded here; verification asserts each one is visible afterwards. Keys
+/// are unique per write, so the final state must contain every acked key
+/// regardless of the interleaving of concurrent writers.
+#[derive(Clone)]
+pub struct PersonState {
+ inner: Arc<RwLock<Journal>>,
+}
+
+#[derive(Default)]
+struct Journal {
+ persons: HashMap<i64, ExpectedPerson>,
+ /// Acks that broke an invariant at journaling time. The leader
+ /// serializes writes per person and bumps the version on every change,
+ /// so each version of a person is assigned to at most one acked write;
+ /// a duplicate means two writes were served from the same base state
+ /// (a stale warm, a stale fallback, or a zombie leader). Arrival order
+ /// is deliberately not checked: concurrent writers' acks are recorded
+ /// in whatever order the responses land, so a lower version arriving
+ /// after a higher one is normal.
+ anomalies: Vec<ConsistencyViolation>,
+}
+
+pub struct ExpectedPerson {
+ /// Only tracks keys the harness wrote — other properties are ignored
+ /// during verification.
+ pub written_properties: HashMap<String, serde_json::Value>,
+ /// Highest version the leader acked for this person.
+ pub last_version: i64,
+ /// Every version the leader acked for this person, for duplicate
+ /// detection.
+ acked_versions: HashSet<i64>,
+}
+
+impl PersonState {
+ pub fn new() -> Self {
+ Self {
+ inner: Arc::new(RwLock::new(Journal::default())),
+ }
+ }
+
+ pub async fn record_write(
+ &self,
+ person_id: i64,
+ version: i64,
+ properties: HashMap<String, serde_json::Value>,
+ ) {
+ let mut journal = self.inner.write().await;
+ let entry = journal
+ .persons
+ .entry(person_id)
+ .or_insert_with(|| ExpectedPerson {
+ written_properties: HashMap::new(),
+ last_version: 0,
+ acked_versions: HashSet::new(),
+ });
+ let duplicate = !entry.acked_versions.insert(version);
+ entry.last_version = entry.last_version.max(version);
+ for (k, v) in properties {
+ entry.written_properties.insert(k, v);
+ }
+ if duplicate {
+ journal.anomalies.push(ConsistencyViolation {
+ person_id,
+ key: "__ack_version_duplicate".to_string(),
+ expected: serde_json::json!("each version acked at most once"),
+ actual: serde_json::json!(version),
+ });
+ }
+ }
+
+ /// Journal an ack whose response carried no person body. The write is
+ /// acked, so its keys must still be verified like any other — but the
+ /// response contract (updates return the updated person) broke, which
+ /// is itself flagged as a violation. With no version in the response,
+ /// the person's version high-water mark is left untouched.
+ pub async fn record_ack_anomaly(
+ &self,
+ person_id: i64,
+ properties: HashMap<String, serde_json::Value>,
+ ) {
+ let mut journal = self.inner.write().await;
+ journal.anomalies.push(ConsistencyViolation {
+ person_id,
+ key: "__ack_missing_person".to_string(),
+ expected: serde_json::json!("update response carries the person"),
+ actual: serde_json::Value::Null,
+ });
+ let entry = journal
+ .persons
+ .entry(person_id)
+ .or_insert_with(|| ExpectedPerson {
+ written_properties: HashMap::new(),
+ last_version: 0,
+ acked_versions: HashSet::new(),
+ });
+ for (k, v) in properties {
+ entry.written_properties.insert(k, v);
+ }
+ }
+
+ /// Duplicate-version and response anomalies observed while journaling.
+ pub async fn take_anomalies(&self) -> Vec<ConsistencyViolation> {
+ mem::take(&mut self.inner.write().await.anomalies)
+ }
+
+ /// Verify a strong read against the journal: every acked property must
+ /// be present, and the observed version must not sit below the highest
+ /// acked version.
+ pub async fn verify(
+ &self,
+ person_id: i64,
+ actual_properties: &serde_json::Value,
+ observed_version: i64,
+ ) -> Vec<ConsistencyViolation> {
+ let journal = self.inner.read().await;
+ let Some(expected) = journal.persons.get(&person_id) else {
+ return vec![];
+ };
+ let mut violations =
+ verify_properties(person_id, &expected.written_properties, actual_properties);
+ if observed_version < expected.last_version {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: "__strong_read_version".to_string(),
+ expected: serde_json::json!(format!(">= {}", expected.last_version)),
+ actual: serde_json::json!(observed_version),
+ });
+ }
+ violations
+ }
+
+ pub async fn person_ids(&self) -> Vec<i64> {
+ self.inner.read().await.persons.keys().copied().collect()
+ }
+
+ /// Drain the journal into a plain map for offline (Postgres) verification.
+ pub async fn snapshot(&self) -> HashMap<i64, ExpectedPerson> {
+ let mut journal = self.inner.write().await;
+ mem::take(&mut journal.persons)
+ }
+}
+
+/// A false positive here fails good runs; a false negative passes runs
+/// that lost data. The e2e gate exercises this on every run but can only
+/// reveal false positives — a verifier that misses violations looks
+/// identical to a healthy stack — so the decision table is unit-tested.
+pub fn verify_properties(
+ person_id: i64,
+ expected: &HashMap<String, serde_json::Value>,
+ actual_properties: &serde_json::Value,
+) -> Vec<ConsistencyViolation> {
+ let actual_map = actual_properties.as_object();
+ let mut violations = Vec::new();
+
+ for (key, expected_val) in expected {
+ let actual_val = actual_map.and_then(|m| m.get(key));
+ match actual_val {
+ Some(val) if val == expected_val => {}
+ Some(val) => {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: key.clone(),
+ expected: expected_val.clone(),
+ actual: val.clone(),
+ });
+ }
+ None => {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: key.clone(),
+ expected: expected_val.clone(),
+ actual: serde_json::Value::Null,
+ });
+ }
+ }
+ }
+
+ violations
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ fn violation_keys(mut violations: Vec<ConsistencyViolation>) -> Vec<String> {
+ violations.sort_by(|a, b| a.key.cmp(&b.key));
+ violations.into_iter().map(|v| v.key).collect()
+ }
+
+ fn props(entries: &[(&str, &str)]) -> HashMap<String, serde_json::Value> {
+ entries
+ .iter()
+ .map(|(k, v)| (k.to_string(), json!(v)))
+ .collect()
+ }
+
+ #[test]
+ fn verify_properties_flags_exactly_the_missing_and_mismatched_keys() {
+ let expected = props(&[("a", "1"), ("b", "2")]);
+ let cases: &[(serde_json::Value, &[&str])] = &[
+ // Everything acked is present; unrelated keys are ignored.
+ (json!({"a": "1", "b": "2", "other": true}), &[]),
+ // Present but wrong value.
+ (json!({"a": "1", "b": "wrong"}), &["b"]),
+ // Acked key absent entirely.
+ (json!({"a": "1"}), &["b"]),
+ // Non-object properties lose every acked key.
+ (json!(null), &["a", "b"]),
+ ];
+ for (actual, expected_keys) in cases {
+ let got = violation_keys(verify_properties(1, &expected, actual));
+ assert_eq!(got, *expected_keys, "actual={actual}");
+ }
+ }
+
+ #[tokio::test]
+ async fn journal_merges_keys_and_keeps_the_max_acked_version() {
+ let state = PersonState::new();
+ state.record_write(1, 1, props(&[("k1", "v1")])).await;
+ state.record_write(1, 2, props(&[("k2", "v2")])).await;
+
+ assert!(state.take_anomalies().await.is_empty());
+ let snapshot = state.snapshot().await;
+ let person = &snapshot[&1];
+ assert_eq!(person.last_version, 2);
+ assert_eq!(person.written_properties.len(), 2);
+ }
+
+ #[tokio::test]
+ async fn out_of_order_acks_are_benign_and_max_is_kept() {
+ let state = PersonState::new();
+ state.record_write(1, 5, props(&[("k1", "v1")])).await;
+ state.record_write(1, 3, props(&[("k2", "v2")])).await;
+
+ // Concurrent writers' acks land in arbitrary order; distinct
+ // versions arriving out of order are not an anomaly.
+ assert!(state.take_anomalies().await.is_empty());
+ let snapshot = state.snapshot().await;
+ let person = &snapshot[&1];
+ assert_eq!(person.last_version, 5);
+ assert!(person.written_properties.contains_key("k2"));
+ }
+
+ #[tokio::test]
+ async fn duplicate_acked_version_is_flagged_and_both_keys_journaled() {
+ let state = PersonState::new();
+ state.record_write(1, 5, props(&[("k1", "v1")])).await;
+ state.record_write(1, 5, props(&[("k2", "v2")])).await;
+
+ assert_eq!(
+ violation_keys(state.take_anomalies().await),
+ vec!["__ack_version_duplicate"]
+ );
+ // Drained on take, and both acked writes' keys stay journaled for
+ // end-of-run verification.
+ assert!(state.take_anomalies().await.is_empty());
+ let snapshot = state.snapshot().await;
+ let person = &snapshot[&1];
+ assert_eq!(person.last_version, 5);
+ assert!(person.written_properties.contains_key("k1"));
+ assert!(person.written_properties.contains_key("k2"));
+ }
+
+ #[tokio::test]
+ async fn ack_without_person_is_flagged_and_its_keys_still_journaled() {
+ let state = PersonState::new();
+ state.record_write(1, 5, props(&[("k1", "v1")])).await;
+ state.record_ack_anomaly(1, props(&[("k2", "v2")])).await;
+
+ assert_eq!(
+ violation_keys(state.take_anomalies().await),
+ vec!["__ack_missing_person"]
+ );
+ let snapshot = state.snapshot().await;
+ let person = &snapshot[&1];
+ assert_eq!(person.last_version, 5, "anomaly must not move the version");
+ assert!(person.written_properties.contains_key("k2"));
+ }
+
+ #[tokio::test]
+ async fn strong_read_below_max_acked_version_is_a_violation() {
+ let state = PersonState::new();
+ state.record_write(1, 5, props(&[("k", "v")])).await;
+ let actual = json!({"k": "v"});
+
+ assert!(state.verify(1, &actual, 5).await.is_empty());
+ assert!(state.verify(1, &actual, 6).await.is_empty());
+ assert_eq!(
+ violation_keys(state.verify(1, &actual, 4).await),
+ vec!["__strong_read_version"]
+ );
+ // Unjournaled persons have nothing to verify against.
+ assert!(state.verify(2, &actual, 0).await.is_empty());
+ }
+}
diff --git a/rust/personhog-test-harness/src/stats.rs b/rust/personhog-test-harness/src/stats.rs
new file mode 100644
index 000000000000..a69c07d92643
--- /dev/null
+++ b/rust/personhog-test-harness/src/stats.rs
@@ -0,0 +1,84 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use hdrhistogram::Histogram;
+
+pub struct LatencyRecorder {
+ histogram: Mutex<Histogram<u64>>,
+ successes: AtomicU64,
+ failures: AtomicU64,
+ start_time: Instant,
+}
+
+impl LatencyRecorder {
+ pub fn new() -> Self {
+ Self {
+ histogram: Mutex::new(Histogram::new_with_max(60_000_000, 3).unwrap()),
+ successes: AtomicU64::new(0),
+ failures: AtomicU64::new(0),
+ start_time: Instant::now(),
+ }
+ }
+
+ pub fn record_success(&self, latency: Duration) {
+ let us = latency.as_micros() as u64;
+ if let Ok(mut h) = self.histogram.lock() {
+ let _ = h.record(us.min(60_000_000));
+ }
+ self.successes.fetch_add(1, Ordering::Relaxed);
+ }
+
+ pub fn record_failure(&self) {
+ self.failures.fetch_add(1, Ordering::Relaxed);
+ }
+
+ pub fn snapshot(&self) -> StatsSnapshot {
+ let h = self.histogram.lock().unwrap();
+ let successes = self.successes.load(Ordering::Relaxed);
+ let failures = self.failures.load(Ordering::Relaxed);
+ let total = successes + failures;
+ let elapsed = self.start_time.elapsed();
+ let throughput_rps = if elapsed.as_secs_f64() > 0.0 {
+ total as f64 / elapsed.as_secs_f64()
+ } else {
+ 0.0
+ };
+
+ StatsSnapshot {
+ total,
+ successes,
+ failures,
+ p50_us: h.value_at_quantile(0.50),
+ p95_us: h.value_at_quantile(0.95),
+ p99_us: h.value_at_quantile(0.99),
+ elapsed,
+ throughput_rps,
+ }
+ }
+}
+
+pub struct StatsSnapshot {
+ pub total: u64,
+ pub successes: u64,
+ pub failures: u64,
+ pub p50_us: u64,
+ pub p95_us: u64,
+ pub p99_us: u64,
+ pub elapsed: Duration,
+ pub throughput_rps: f64,
+}
+
+pub struct StatsCollector {
+ pub writes: LatencyRecorder,
+ pub reads: LatencyRecorder,
+}
+
+impl StatsCollector {
+ pub fn new() -> Self {
+ Self {
+ writes: LatencyRecorder::new(),
+ reads: LatencyRecorder::new(),
+ }
+ }
+}