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): merge traffic in the test harness gate (#91011)

Nick Best3b7417676080
diff --git a/.agents/skills/extending-personhog-test-harness/SKILL.md b/.agents/skills/extending-personhog-test-harness/SKILL.md
index f86070b7b934..dd9434c93a49 100644
--- a/.agents/skills/extending-personhog-test-harness/SKILL.md
+++ b/.agents/skills/extending-personhog-test-harness/SKILL.md
@@ -43,6 +43,10 @@ logic here: the harness is for whole-stack behavior only.
SIGTERM drain, SIGSTOP/SIGCONT zombie), writer crash/pause, coordinator
kill, etcd lease revocation, per-service env. New disruptions are new
methods here.
+- `src/scenarios/merge.rs` — the merge lane (`--merge-concurrency`): MergePersons
+ calls with one or more sources (`--merge-sources`) against live persons while
+ the other lanes write to them. Merged sources hang off the survivor in the
+ journal tree and are retired from the shared `src/pool.rs` target pool.
- `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.
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 54f75728695a..bddfa290f25f 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -681,6 +681,26 @@ jobs:
--leaders 3 --partitions 8 --persons 100 \
--concurrency 10 --duration 15s --kill-after 5s --scale-up-after 8s
+ # The merge saga under load and chaos: MergePersons calls against
+ # live persons while blast writes race each source's fence and
+ # each target's fold, through a leader kill and a scale-up. Two
+ # sources per call exercise the fold's request order. The wide
+ # persons make the flip repoint a thousand mappings per source.
+ # The gate asserts the folded survivor document, the merge
+ # event's $set and $set_once, that each source is gone (not-found
+ # reads, a tombstone above every acked version, no mapping left
+ # behind), and that the delete leg answers not_found for merged
+ # sources.
+ - name: Run the e2e gate merging persons under chaos (kill + scale-up)
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --pg-target-table posthog_person \
+ --leaders 3 --partitions 8 --persons 200 \
+ --concurrency 10 --duration 15s --merge-concurrency 4 --merge-rate 5 \
+ --merge-sources 2 \
+ --merge-wide-persons 3 --merge-wide-distinct-ids 1000 --merge-wide-role source \
+ --kill-after 5s --scale-up-after 8s
+
# Regression gate for eviction under writer lag: the cache is
# sized far below the person count so dirty entries evict while
# the paused writer guarantees their PG rows are stale. Before
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 76622e805bf3..cc0635ac9aab 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -3,7 +3,7 @@
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 30s fails the gate), and in Postgres (at or above the highest acked version) once the writer drains.
+The core invariant it checks: **every write acked by the leader path is visible afterwards** — on the person it was written to, or on the survivor once a merge folded that person away — in strong reads once coordination has converged (post-chaos handoffs re-driven; an already-settled run waits zero time, and failing to converge within 30s 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.
@@ -62,6 +62,54 @@ target/debug/personhog-test-harness gate --create-via-identity \
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).
+### Merging persons under load
+
+`--merge-concurrency N` adds a merge lane: N workers repeatedly pick live persons and merge one or more sources into a target through `MergePersons` on the identity service, while the blast writers and probers keep writing to all of them.
+Every source is a distinct live person, so each source that settles as `merged` ran the durable saga end to end (fence, seal, fold, flip, release) with writes racing the source's fence and the target's fold.
+A source distinct id is reserved for one in-flight call and never reused once merged; targets are shared, so concurrent calls can contend for a person and settle as `skipped_conflict`.
+`--merge-sources K` puts K sources on each call (default 1, the shape ingestion sends); the leader folds sealed sources in request order, and the journal holds the survivor to that order.
+The lane implies `--create-via-identity` (merges need distinct ids) and merges identified sources by default (`--merge-identified-sources false` for `$identify` semantics, under which a survivor can never be a source again).
+
+The invariant extends to the fold rather than stopping at it:
+
+- The sources' acked writes are asserted on the survivor under the leader's fold rule (the survivor wins every key it has, the sources fill the rest in request order), and the folded version is claimed like any other ack.
+- The merge event's own writes are asserted in the acked survivor document and afterwards: its `$set` key must be present, its `$set_once` must fill a fresh key, lose to the same event's `$set` on a shared key, and leave the seed property every person holds untouched.
+- The journal is a tree: a merged source keeps its own keys and hangs off the survivor its ack named, and a live person's expected document is folded from that tree. So a source write whose ack lands after the merge was journaled still counts, even for a key an earlier fold already carried, and a survivor that merges on carries everything with it.
+- A merged source must be gone: a strong read right after the ack and at end of run must answer not-found, its Postgres row must be a tombstone whose death version sits above every version the leader acked for it, and no acked version may exceed the sealed version the saga recorded on its `lifecycle_op_person` row — an ack above the seal means a write got through the fence.
+- Two merges into one survivor are ordered by the folded version, not by ack arrival: the earlier fold fills a key and the later fold finds it present, which is what the journal expects.
+- A merge the crash window abandons mid-saga is re-driven by the identity sweeper (the spawned identity runs it on a 3s cadence), and the delete leg waits for those ops to settle before it asserts.
+- A call that loses every response (retried under the same op id) is settled after traffic from the saga's own `lifecycle_op` record: a completed merge is journaled late (safe, because folds are ordered by version), an aborted or never-started one leaves the source live, and one that never settles is a violation. Writes refused for a fenced or destroyed person are counted as lifecycle rejections, not failures.
+- The delete leg expects merged sources to answer `not_found` on the first attempt.
+
+Pathological merges — a person carrying thousands of distinct ids, every one of which the flip must repoint — get their own lane: `--merge-wide-persons N` creates N extra persons with `--merge-wide-distinct-ids K` extra mappings each (identity caps a create entry at 5000), and `--merge-wide-role source|target|both` decides which side they take.
+Workers prefer a wide pair while one is available, and calls involving a wide person report as a separate `merges_wide` row so their cost does not hide in the ordinary median.
+Merged sources are additionally checked for leftover mappings (`__merged_source_dids_left`): every distinct id of a destroyed person must point at the survivor.
+
+```bash
+# 5 wide sources with 2000 distinct ids each, merged into ordinary targets
+target/debug/personhog-test-harness gate --merge-concurrency 2 --merge-rate 2 \
+ --merge-wide-persons 5 --merge-wide-distinct-ids 2000 --merge-wide-role source \
+ --persons 100 --duration 15s
+```
+
+Each merged source retires one person, so size `--persons` for sources × rate × duration; the report says when the lane ran the pool dry.
+The `merges` row in the report is the baseline: one call is one saga, so its latency is the end-to-end merge cost and its RPS the merge throughput.
+
+```bash
+# Paced: 5 merges/s alongside the blast traffic
+target/debug/personhog-test-harness gate --merge-concurrency 4 --merge-rate 5 \
+ --persons 200 --concurrency 10 --duration 15s
+
+# Throughput ceiling: unpaced workers, pool sized for a 10s burn
+target/debug/personhog-test-harness gate --merge-concurrency 8 --persons 400 --duration 10s
+
+# Merges through a leader kill and a scale-up: fences, folds, and death
+# documents must survive the handoffs
+target/debug/personhog-test-harness gate --leaders 3 --partitions 8 \
+ --merge-concurrency 4 --merge-rate 5 --persons 200 --duration 15s \
+ --kill-after 5s --scale-up-after 8s
+```
+
### Chaos disruptions
Disruptions fire mid-traffic, scheduled relative to the start of the traffic phase (spawned stack only).
@@ -232,10 +280,15 @@ target/debug/personhog-test-harness consistency \
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
+ merges 80 80 0 80.6ms 197.0ms 697.3ms 5.0
+
+ Lifecycle rejections (counted in Total, not Failed): 17 writes refused for a fenced or destroyed person
+ Merge outcomes per source: merged=79 skipped_conflict=1
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.
+Merge runs add `__merged_source_alive` (a destroyed person still reads), `__merged_source_tombstone` / `__merged_source_death_version` (the source row is not a tombstone, or its death version does not sit above every acked write), `__merged_source_ack_above_seal` (the leader acked a source write above the sealed version the saga recorded — the fence failed open), `__merged_source_seal_record` (the saga left no deleted source row for a merged person), `__merged_twice` (one person destroyed by two merges), and `__merge_unsettled` (a merge that lost every response never reached a terminal step).
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
index ba94a0846762..fe55ed807c48 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -333,6 +333,52 @@ pub struct GateArgs {
#[arg(long)]
pub external_identity_url: Option<String>,
+ /// Merge workers that run next to the blast traffic and probers.
+ /// Each worker picks live persons and merges them through
+ /// MergePersons on the identity service while writes to them
+ /// continue. Merged sources leave the traffic pool. Implies
+ /// --create-via-identity, because merges need distinct ids. 0
+ /// disables.
+ #[arg(long, default_value_t = 0)]
+ pub merge_concurrency: usize,
+
+ /// Total merge calls per second across the merge workers. Unset
+ /// runs them flat out. Each merged source retires one person, so
+ /// size --persons for sources x rate x duration.
+ #[arg(long)]
+ pub merge_rate: Option<f64>,
+
+ /// Sources per merge call. Ingestion sends one. With more, the
+ /// leader folds the sources in request order, and the gate asserts
+ /// that order.
+ #[arg(long, default_value_t = 1)]
+ pub merge_sources: usize,
+
+ /// Extra persons, each created with --merge-wide-distinct-ids
+ /// distinct ids. The merge lane uses them per --merge-wide-role and
+ /// reports their calls on the `merges_wide` row. Requires
+ /// --merge-concurrency.
+ #[arg(long, default_value_t = 0)]
+ pub merge_wide_persons: u32,
+
+ /// Extra distinct ids per wide person. The identity service caps a
+ /// create entry at 5000.
+ #[arg(long, default_value_t = 1000)]
+ pub merge_wide_distinct_ids: u32,
+
+ /// Which side of a merge the wide persons take. `source` makes the
+ /// flip repoint every mapping. `target` makes the survivor grow.
+ /// `both` merges wide into wide.
+ #[arg(long, default_value = "source", value_parser = ["source", "target", "both"])]
+ pub merge_wide_role: String,
+
+ /// Merge identified sources, as $merge_dangerously does. A survivor
+ /// becomes identified. With this off, a survivor can never be a
+ /// source again, and the lane ends in skipped_already_identified
+ /// once every live person survived a merge.
+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
+ pub merge_identified_sources: bool,
+
/// Leave the spawned stack running after the gate finishes (for
/// poking at it manually). Ignored with --external-router-url.
#[arg(long, default_value_t = false)]
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
index 286dc45f8de4..aae7996a5e56 100644
--- a/rust/personhog-test-harness/src/client.rs
+++ b/rust/personhog-test-harness/src/client.rs
@@ -5,7 +5,8 @@ use personhog_common::client::RouterClient;
use personhog_proto::personhog::{
identity::v1::{
person_hog_identity_client::PersonHogIdentityClient, GetOrCreatePersonEntry,
- GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
+ GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest, MergePersonsRequest,
+ MergePersonsResponse, MergeSource,
},
lifecycle::v1::{
person_hog_lifecycle_client::PersonHogLifecycleClient, DeletePersonOutcome,
@@ -155,6 +156,46 @@ impl IdentityClient {
.context("GetOrCreatePersonsByDistinctIds failed")?;
Ok(resp.into_inner().results)
}
+
+ /// Merge `source_distinct_ids` into the person that
+ /// `target_distinct_id` resolves to. A retry with the same op id
+ /// returns the recorded outcome and does not merge again.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn merge_persons(
+ &self,
+ team_id: i64,
+ target_distinct_id: &str,
+ source_distinct_ids: &[String],
+ event_set: serde_json::Value,
+ event_set_once: serde_json::Value,
+ op_id: &uuid::Uuid,
+ allow_identified_sources: bool,
+ move_limit: i64,
+ ) -> Result<MergePersonsResponse> {
+ let resp = self
+ .inner
+ .clone()
+ .merge_persons(Request::new(MergePersonsRequest {
+ team_id,
+ target_distinct_id: target_distinct_id.to_string(),
+ sources: source_distinct_ids
+ .iter()
+ .map(|did| MergeSource {
+ source_distinct_id: did.clone(),
+ event_uuid: uuid::Uuid::new_v4().to_string(),
+ })
+ .collect(),
+ event_set: serde_json::to_vec(&event_set)?,
+ event_set_once: serde_json::to_vec(&event_set_once)?,
+ op_id: op_id.to_string(),
+ allow_identified_sources,
+ move_limit: Some(move_limit),
+ created_at: 0,
+ }))
+ .await
+ .context("MergePersons failed")?;
+ Ok(resp.into_inner())
+ }
}
/// Client for the lifecycle saga service, co-served on the identity
diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rs
index 3132c11b47b0..3198d1f66d04 100644
--- a/rust/personhog-test-harness/src/main.rs
+++ b/rust/personhog-test-harness/src/main.rs
@@ -4,6 +4,7 @@ use tracing_subscriber::EnvFilter;
mod cli;
mod client;
+mod pool;
mod report;
mod scenarios;
mod seed;
diff --git a/rust/personhog-test-harness/src/pool.rs b/rust/personhog-test-harness/src/pool.rs
new file mode 100644
index 000000000000..ac3c823d468a
--- /dev/null
+++ b/rust/personhog-test-harness/src/pool.rs
@@ -0,0 +1,83 @@
+use std::sync::RwLock;
+
+use rand::Rng;
+
+/// The live traffic targets. The merge lane removes a source after the
+/// merge ack, not before the call. The source keeps taking writes during
+/// the merge, so the writes race the fence and the fold. That race is
+/// the point of merging under load.
+pub struct TargetPool {
+ ids: RwLock<Vec<i64>>,
+}
+
+impl TargetPool {
+ pub fn new(ids: Vec<i64>) -> Self {
+ Self {
+ ids: RwLock::new(ids),
+ }
+ }
+
+ pub fn len(&self) -> usize {
+ self.ids.read().unwrap().len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ pub fn pick_random(&self, rng: &mut impl Rng) -> Option<i64> {
+ let ids = self.ids.read().unwrap();
+ if ids.is_empty() {
+ return None;
+ }
+ Some(ids[rng.gen_range(0..ids.len())])
+ }
+
+ /// The person at `n` modulo the live count. None when the pool is
+ /// empty.
+ pub fn pick_nth(&self, n: usize) -> Option<i64> {
+ let ids = self.ids.read().unwrap();
+ if ids.is_empty() {
+ return None;
+ }
+ Some(ids[n % ids.len()])
+ }
+
+ pub fn remove(&self, person_id: i64) -> bool {
+ let mut ids = self.ids.write().unwrap();
+ match ids.iter().position(|&id| id == person_id) {
+ Some(index) => {
+ ids.swap_remove(index);
+ true
+ }
+ None => false,
+ }
+ }
+
+ pub fn snapshot(&self) -> Vec<i64> {
+ self.ids.read().unwrap().clone()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn picks_only_live_persons_and_empties_cleanly() {
+ let pool = TargetPool::new(vec![1, 2, 3]);
+ let mut rng = rand::thread_rng();
+ assert!(pool.remove(2));
+ assert!(!pool.remove(2));
+ for _ in 0..100 {
+ let picked = pool.pick_random(&mut rng).unwrap();
+ assert!(picked == 1 || picked == 3);
+ }
+ assert_eq!(pool.pick_nth(1), Some(pool.snapshot()[1]));
+ assert!(pool.remove(1));
+ assert!(pool.remove(3));
+ assert!(pool.is_empty());
+ assert_eq!(pool.pick_random(&mut rng), None);
+ assert_eq!(pool.pick_nth(7), None);
+ }
+}
diff --git a/rust/personhog-test-harness/src/report.rs b/rust/personhog-test-harness/src/report.rs
index 3ca6e92f2964..6c32dc6d4150 100644
--- a/rust/personhog-test-harness/src/report.rs
+++ b/rust/personhog-test-harness/src/report.rs
@@ -54,7 +54,33 @@ pub fn print_report(
if read_snap.total > 0 {
print_stats_row("reads", &read_snap);
}
+ let merge_snap = collector.merges.snapshot();
+ if merge_snap.total > 0 {
+ print_stats_row("merges", &merge_snap);
+ }
+ let wide_snap = collector.wide_merges.snapshot();
+ if wide_snap.total > 0 {
+ print_stats_row("merges_wide", &wide_snap);
+ }
println!();
+ let rejected = write_snap.lifecycle_rejections + read_snap.lifecycle_rejections;
+ if rejected > 0 {
+ println!(
+ " Lifecycle rejections (counted in Total, not Failed): {rejected} writes refused \
+ for a fenced or destroyed person"
+ );
+ }
+ let outcomes = collector.merge_outcomes();
+ if !outcomes.is_empty() {
+ let rendered: Vec<String> = outcomes
+ .iter()
+ .map(|(outcome, count)| format!("{outcome}={count}"))
+ .collect();
+ println!(" Merge outcomes per source: {}", rendered.join(" "));
+ }
+ if rejected > 0 || !outcomes.is_empty() {
+ println!();
+ }
if violations.is_empty() {
println!(" Consistency violations: 0");
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
index 40d5fa9f96da..59948db333fd 100644
--- a/rust/personhog-test-harness/src/scenarios/blast.rs
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -12,6 +12,7 @@ use uuid::Uuid;
use crate::cli::BlastArgs;
use crate::client::HarnessClient;
+use crate::pool::TargetPool;
use crate::report::{print_report, ConsistencyViolation};
use crate::state::PersonState;
use crate::stats::StatsCollector;
@@ -20,7 +21,7 @@ use crate::traffic_metrics;
pub async fn run(args: BlastArgs) -> Result<()> {
let client =
HarnessClient::connect_with_channels(&args.router_url, args.router_channels).await?;
- let person_ids = Arc::new(args.person_ids.clone());
+ let person_ids = Arc::new(TargetPool::new(args.person_ids.clone()));
println!(
"Blasting {} persons for {} with concurrency {}...",
@@ -115,7 +116,7 @@ impl PropertyPlan {
pub async fn run_traffic(
client: &HarnessClient,
team_id: i64,
- person_ids: Arc<Vec<i64>>,
+ person_ids: Arc<TargetPool>,
duration: Duration,
concurrency: usize,
rate_per_sec: Option<f64>,
@@ -124,6 +125,9 @@ pub async fn run_traffic(
state: &PersonState,
stop: Arc<AtomicBool>,
) -> Result<()> {
+ if person_ids.is_empty() {
+ bail!("no traffic targets: the pool is empty");
+ }
let deadline = Instant::now() + duration;
let worker_tick = rate_per_sec.map(|rate| per_worker_tick(rate, concurrency));
@@ -148,7 +152,11 @@ pub async fn run_traffic(
if let Some(pacer) = pacer.as_mut() {
pacer.tick().await;
}
- let person_id = person_ids[rng.gen_range(0..person_ids.len())];
+ // The merge lane can empty the pool. Stop instead of
+ // spinning.
+ let Some(person_id) = person_ids.pick_random(&mut rng) else {
+ break;
+ };
let key = plan.key(worker_id, &mut rng);
let value = Uuid::new_v4().to_string();
@@ -180,6 +188,12 @@ pub async fn run_traffic(
}
}
Err(e) => {
+ if is_lifecycle_rejection(&e) {
+ // The write did not apply, so the key stays
+ // certain.
+ collector.writes.record_lifecycle_rejection();
+ continue;
+ }
collector.writes.record_failure();
traffic_metrics::record_write_failed(traffic_metrics::LANE_BLAST, &e);
state.record_write_uncertain(person_id, &key).await;
@@ -198,6 +212,26 @@ pub async fn run_traffic(
Ok(())
}
+/// True for the refusals a lifecycle op causes: FAILED_PRECONDITION
+/// with the leader's fenced header, or NOT_FOUND for a destroyed
+/// person. Both mean the write did not apply. Other FAILED_PRECONDITION
+/// causes, such as a handoff, stay failures.
+pub fn is_lifecycle_rejection(err: &anyhow::Error) -> bool {
+ let Some(status) = err.downcast_ref::<tonic::Status>() else {
+ return false;
+ };
+ match status.code() {
+ tonic::Code::NotFound => true,
+ tonic::Code::FailedPrecondition => status.metadata().contains_key("x-person-fenced"),
+ _ => false,
+ }
+}
+
+pub fn is_not_found(err: &anyhow::Error) -> bool {
+ err.downcast_ref::<tonic::Status>()
+ .is_some_and(|status| status.code() == tonic::Code::NotFound)
+}
+
/// The tick interval each of `concurrency` workers needs so their
/// combined rate hits `rate_per_sec`. Rates too low to represent tick at
/// most once per hour rather than dividing by zero.
@@ -211,6 +245,8 @@ pub fn per_worker_tick(rate_per_sec: f64, concurrency: usize) -> Duration {
/// 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.
+/// A merged source must not read as alive. Its writes are verified on
+/// the survivor.
pub async fn verify_strong(
client: &HarnessClient,
collector: &StatsCollector,
@@ -220,17 +256,36 @@ pub async fn verify_strong(
let person_ids = state.person_ids().await;
let mut all_violations = Vec::new();
- for person_id in person_ids {
+ for person_id in state.merged_source_ids().await {
let start = Instant::now();
- let mut result = client
- .get_person(team_id, person_id, ConsistencyLevel::Strong)
- .await;
- if result.is_err() {
- sleep(Duration::from_secs(2)).await;
- result = client
- .get_person(team_id, person_id, ConsistencyLevel::Strong)
- .await;
+ match strong_read_with_retry(client, team_id, person_id).await {
+ // NOT_FOUND is the expected answer for a merged source.
+ Err(e) if is_not_found(&e) => collector.reads.record_success(start.elapsed()),
+ Ok(Some(person)) if !person.is_deleted => {
+ collector.reads.record_success(start.elapsed());
+ all_violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_alive".to_string(),
+ expected: json!("not found after the merge"),
+ actual: json!({ "version": person.version }),
+ });
+ }
+ Ok(_) => collector.reads.record_success(start.elapsed()),
+ Err(e) => {
+ collector.reads.record_failure();
+ all_violations.push(ConsistencyViolation {
+ person_id,
+ key: "__strong_read_failed".to_string(),
+ expected: json!("readable"),
+ actual: json!(e.to_string()),
+ });
+ }
}
+ }
+
+ for person_id in person_ids {
+ let start = Instant::now();
+ let result = strong_read_with_retry(client, team_id, person_id).await;
match result {
Ok(Some(person)) => {
@@ -273,6 +328,23 @@ pub async fn verify_strong(
Ok(all_violations)
}
+async fn strong_read_with_retry(
+ client: &HarnessClient,
+ team_id: i64,
+ person_id: i64,
+) -> Result<Option<personhog_proto::personhog::types::v1::Person>> {
+ let mut result = client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await;
+ if result.as_ref().is_err_and(|e| !is_not_found(e)) {
+ sleep(Duration::from_secs(2)).await;
+ result = client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await;
+ }
+ result
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rs
index c43303d71bfc..950808144be8 100644
--- a/rust/personhog-test-harness/src/scenarios/consistency.rs
+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs
@@ -8,6 +8,7 @@ use personhog_proto::personhog::types::v1::ConsistencyLevel;
use crate::cli::ConsistencyArgs;
use crate::client::HarnessClient;
+use crate::pool::TargetPool;
use crate::report::{print_report, ConsistencyViolation};
use crate::state::PersonState;
use crate::stats::StatsCollector;
@@ -178,7 +179,7 @@ pub async fn run(args: ConsistencyArgs) -> Result<()> {
pub async fn run_probers(
client: &HarnessClient,
team_id: i64,
- person_ids: Arc<Vec<i64>>,
+ person_ids: Arc<TargetPool>,
probers: usize,
duration: Duration,
collector: &Arc<StatsCollector>,
@@ -200,7 +201,9 @@ pub async fn run_probers(
let mut iteration: usize = 0;
while Instant::now() < deadline && !stop.load(Ordering::Relaxed) {
- let person_id = person_ids[(worker_id + iteration) % person_ids.len()];
+ let Some(person_id) = person_ids.pick_nth(worker_id + iteration) else {
+ break;
+ };
iteration += 1;
let marker = uuid::Uuid::new_v4().to_string();
let key = format!("harness_probe_{worker_id}_{iteration}");
@@ -225,6 +228,10 @@ pub async fn run_probers(
response
}
Err(e) => {
+ if super::blast::is_lifecycle_rejection(&e) {
+ collector.writes.record_lifecycle_rejection();
+ continue;
+ }
collector.writes.record_failure();
traffic_metrics::record_write_failed(traffic_metrics::LANE_PROBER, &e);
tracing::warn!(person_id, error = %e, "probe write failed");
@@ -276,7 +283,13 @@ pub async fn run_probers(
Ok(None) => {
// A served read that cannot see a person with an
// acked write is a violation, not an availability
- // blip.
+ // blip. The exception is a merged person: its
+ // writes folded into the survivor, and end-of-run
+ // verification asserts them there.
+ if state.is_merge_pending_or_merged(person_id).await {
+ collector.reads.record_success(read_start.elapsed());
+ continue;
+ }
collector.reads.record_failure();
traffic_metrics::record_read_failed(
traffic_metrics::LANE_PROBER,
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 9120927421f3..e2dc94345cce 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -12,7 +12,9 @@ use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
use crate::cli::{GateArgs, DEFAULT_KEYS_PER_PERSON};
use crate::client::{HarnessClient, IdentityClient};
+use crate::pool::TargetPool;
use crate::report::print_report;
+use crate::scenarios::merge::{self, MergeLane, WideRole};
use crate::scenarios::{blast, consistency};
use crate::seed;
use crate::stack::{Stack, StackConfig};
@@ -20,6 +22,10 @@ use crate::state::PersonState;
use crate::stats::StatsCollector;
use crate::verify::verify_postgres;
+/// The property set on every person the identity service creates. The
+/// merge lane expects it on every survivor.
+pub const SEED_KEY: &str = "harness_seed";
+
/// A chaos disruption scheduled relative to the start of the traffic phase.
enum ChaosEvent {
Kill { fast: bool },
@@ -150,12 +156,29 @@ pub async fn run(args: GateArgs) -> Result<()> {
if args.external_router_url.is_some() && !args.leader_env.is_empty() {
bail!("--leader-env requires a spawned stack; it cannot target --external-router-url");
}
- if args.create_via_identity
+ // Merges need distinct ids. Only the identity create path provides
+ // them.
+ let create_via_identity = args.create_via_identity || args.merge_concurrency > 0;
+ if create_via_identity
&& args.external_router_url.is_some()
&& args.external_identity_url.is_none()
{
- bail!("--create-via-identity with --external-router-url needs --external-identity-url");
+ bail!("--create-via-identity (or --merge-concurrency) with --external-router-url needs --external-identity-url");
+ }
+ if args.merge_concurrency > 0 && args.persons < 2 {
+ bail!("--merge-concurrency needs at least 2 persons to pair");
+ }
+ if args.merge_rate.is_some_and(|rate| rate <= 0.0) {
+ bail!("--merge-rate must be positive; omit it to run the merge workers flat out");
+ }
+ if args.merge_sources == 0 {
+ bail!("--merge-sources must be at least 1");
}
+ if args.merge_wide_persons > 0 && args.merge_concurrency == 0 {
+ bail!("--merge-wide-persons needs --merge-concurrency");
+ }
+ let wide_role = WideRole::parse(&args.merge_wide_role)
+ .ok_or_else(|| anyhow::anyhow!("unknown --merge-wide-role {:?}", args.merge_wide_role))?;
// The spawned identity derives its whole table set (person, distinct id,
// hash-key overrides) from --pg-target-table, so any known table set
// works; Stack::up rejects person tables without a known companion set.
@@ -203,7 +226,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
extra_leader_env: args.leader_env.clone(),
recovery_pool_size: args.recovery_pool_size,
leader_lease_ttl: args.leader_lease_ttl,
- spawn_identity: args.create_via_identity,
+ spawn_identity: create_via_identity,
})
.await?,
)
@@ -236,28 +259,55 @@ pub async fn run(args: GateArgs) -> Result<()> {
// assertions target that stack, so an external identity service pointed
// elsewhere would only produce confusing failures.
let identity_url = match (&args.external_identity_url, &stack) {
- _ if !args.create_via_identity => None,
+ _ if !create_via_identity => None,
(_, Some(stack)) => stack.identity_url.clone(),
(Some(url), None) => Some(url.clone()),
(None, None) => unreachable!("validated above"),
};
+ let mut distinct_ids: HashMap<i64, String> = HashMap::new();
let person_ids = match &identity_url {
Some(url) => {
- let ids = create_persons_via_identity(url, args.team_id, args.persons, &state).await?;
+ let created =
+ create_persons_via_identity(url, args.team_id, args.persons, &state).await?;
println!(
"Created {} persons via identity for team {}",
- ids.len(),
+ created.len(),
args.team_id
);
- Arc::new(ids)
+ let ids = created.iter().map(|(id, _)| *id).collect();
+ distinct_ids.extend(created);
+ ids
}
None => {
let ids = seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.persons)
.await?;
println!("Seeded {} persons for team {}", ids.len(), args.team_id);
- Arc::new(ids)
+ ids
}
};
+ let mut person_ids = person_ids;
+ let mut wide_persons = Vec::new();
+ if let (Some(url), true) = (&identity_url, args.merge_wide_persons > 0) {
+ let created = create_wide_persons_via_identity(
+ url,
+ args.team_id,
+ args.merge_wide_persons,
+ args.merge_wide_distinct_ids,
+ &state,
+ )
+ .await?;
+ println!(
+ "Created {} wide persons with {} extra distinct ids each",
+ created.len(),
+ args.merge_wide_distinct_ids
+ );
+ wide_persons.extend(created.iter().map(|(id, _)| *id));
+ person_ids.extend(created.iter().map(|(id, _)| *id));
+ distinct_ids.extend(created);
+ }
+ let created_count = person_ids.len();
+ let person_ids = Arc::new(TargetPool::new(person_ids));
+ let distinct_ids = Arc::new(distinct_ids);
println!(
"Driving traffic for {} with concurrency {}...",
@@ -315,6 +365,58 @@ pub async fn run(args: GateArgs) -> Result<()> {
})
};
+ let merges = identity_url
+ .as_ref()
+ .filter(|_| args.merge_concurrency > 0)
+ .map(|url| {
+ let url = url.clone();
+ let router = client.clone();
+ let person_ids = person_ids.clone();
+ let distinct_ids = distinct_ids.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let lane = MergeLane {
+ team_id: args.team_id,
+ concurrency: args.merge_concurrency,
+ rate_per_sec: args.merge_rate,
+ sources_per_call: args.merge_sources,
+ allow_identified_sources: args.merge_identified_sources,
+ // A survivor collects the distinct ids of every merged
+ // source. This limit covers the whole pool, so no source
+ // trips the move guard.
+ move_limit: i64::from(args.persons)
+ + i64::from(args.merge_wide_persons)
+ * (i64::from(args.merge_wide_distinct_ids) + 1)
+ + 1,
+ wide_persons: wide_persons.clone(),
+ wide_role,
+ };
+ let duration = args.duration;
+ println!(
+ "Merging with {} workers{}, {} source(s) per call...",
+ args.merge_concurrency,
+ args.merge_rate
+ .map(|rate| format!(" at {rate} merges/s"))
+ .unwrap_or_default(),
+ args.merge_sources
+ );
+ tokio::spawn(async move {
+ let identity = IdentityClient::connect(&url).await?;
+ merge::run_merges(
+ &identity,
+ &router,
+ lane,
+ person_ids,
+ distinct_ids,
+ duration,
+ &collector,
+ &state,
+ Arc::new(AtomicBool::new(false)),
+ )
+ .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.
@@ -344,7 +446,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
.execute(&pool)
.await
.context("inserting fence op row")?;
- for &person_id in person_ids.iter().take(args.fence_count) {
+ for &person_id in person_ids.snapshot().iter().take(args.fence_count) {
sqlx::query(
"INSERT INTO lifecycle_op_person \
(op_id, team_id, person_id, person_uuid, role, status) \
@@ -357,7 +459,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
.await
.context("inserting fence mark")?;
}
- for &person_id in person_ids.iter().take(args.fence_count) {
+ for &person_id in person_ids.snapshot().iter().take(args.fence_count) {
match client
.fence_person(args.team_id, person_id, &fence_op)
.await
@@ -476,7 +578,13 @@ pub async fn run(args: GateArgs) -> Result<()> {
}
traffic.await.context("traffic task panicked")??;
- let prober_violations = probers.await.context("prober task panicked")??;
+ let mut prober_violations = probers.await.context("prober task panicked")??;
+ let mut unresolved_merges = Vec::new();
+ if let Some(merges) = merges {
+ let result = merges.await.context("merge task panicked")??;
+ prober_violations.extend(result.violations);
+ unresolved_merges = result.unresolved;
+ }
// Verification asserts data visibility on a converged topology, not
// recovery speed: chaos legitimately leaves handoffs to re-drive. The
@@ -503,33 +611,70 @@ pub async fn run(args: GateArgs) -> Result<()> {
);
}
- println!("Verifying strong reads...");
+ // Merges that lost every response settle from their op records
+ // first. The sweeper re-drives an abandoned op only after its 15s
+ // lease lapses, which is why the deadline is long.
let mut violations = prober_violations;
+ violations.extend(
+ merge::settle_unresolved(&pool, &state, unresolved_merges, Duration::from_secs(90)).await?,
+ );
+
+ println!("Verifying strong reads...");
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 merged_ids = state.merged_source_ids().await;
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,
+ let merged = state.snapshot_merged().await;
+ violations.extend(
+ verify_postgres(
+ &pool,
+ &args.pg_target_table,
+ args.team_id,
+ &journal,
+ &merged,
+ )
+ .await?,
);
+ print_report("gate", &collector, args.team_id, created_count, &violations);
+ let mut disputed: HashMap<i64, Vec<String>> = HashMap::new();
+ for violation in &violations {
+ let keys = disputed.entry(violation.person_id).or_default();
+ if !keys.contains(&violation.key) {
+ keys.push(violation.key.clone());
+ }
+ }
+ for (person_id, keys) in disputed {
+ println!("{}", state.describe(person_id, &keys).await);
+ }
+ if !merged_ids.is_empty() {
+ println!(
+ " Merged {} of {} persons; {} live at the end",
+ merged_ids.len(),
+ created_count,
+ person_ids.len()
+ );
+ println!();
+ }
+
// The delete leg of the identity path: persons created through
// get-or-create leave through the lifecycle saga, and both the
// outcomes and the saga's idempotence are gate assertions — every
// created person deletes exactly once, and a second attempt under a
- // fresh op id answers not_found for all of them.
+ // fresh op id answers not_found for all of them. A merged source is
+ // a tombstone already, so it answers not_found on the first attempt.
if let Some(url) = &identity_url {
if !args.keep_data {
println!("Deleting persons through the lifecycle saga...");
let lifecycle = crate::client::LifecycleClient::connect(url).await?;
- verify_lifecycle_delete(&lifecycle, args.team_id, &person_ids).await?;
+ let uncertain = state.merge_uncertain_ids().await;
+ let mut live: Vec<i64> = distinct_ids.keys().copied().collect();
+ live.retain(|id| !merged_ids.contains(id) && !uncertain.contains(id));
+ live.sort_unstable();
+ verify_lifecycle_delete(&lifecycle, args.team_id, &live, &merged_ids, &uncertain)
+ .await?;
println!("Lifecycle delete verified: all deleted, re-delete answers not_found");
}
}
@@ -570,40 +715,108 @@ pub async fn run(args: GateArgs) -> Result<()> {
/// to the gate's standard: every id deleted on the first attempt, every
/// id not_found on a second attempt under a fresh op id (deleting a
/// tombstone is a no-op, never an error, never a false success).
+/// `merged_ids` must answer not_found on the first attempt. A `deleted`
+/// there means the merge left a living row. `uncertain_ids` had a merge
+/// call that never answered, so either answer is accepted.
+///
+/// A `skipped_conflict` means another lifecycle op still holds the
+/// person, usually a merge that chaos interrupted. The delete is retried
+/// under fresh op ids until the sweeper settles that op. An op that
+/// never settles fails the gate, because nobody can merge or delete
+/// that person again.
async fn verify_lifecycle_delete(
lifecycle: &crate::client::LifecycleClient,
team_id: i64,
person_ids: &[i64],
+ merged_ids: &[i64],
+ uncertain_ids: &[i64],
) -> Result<()> {
use personhog_proto::personhog::lifecycle::v1::DeletePersonOutcome;
- for (attempt, expected) in [
- (1, DeletePersonOutcome::Deleted),
- (2, DeletePersonOutcome::NotFound),
- ] {
+ /// The sweeper claims an abandoned op only after its 15s lease
+ /// lapses, then re-drives it. Sized for a few of those in sequence.
+ const SETTLE_DEADLINE: Duration = Duration::from_secs(90);
+
+ let mut expected: HashMap<i64, Vec<DeletePersonOutcome>> = HashMap::new();
+ for &id in person_ids {
+ expected.insert(id, vec![DeletePersonOutcome::Deleted]);
+ }
+ for &id in merged_ids {
+ expected.insert(id, vec![DeletePersonOutcome::NotFound]);
+ }
+ for &id in uncertain_ids {
+ expected.insert(
+ id,
+ vec![DeletePersonOutcome::Deleted, DeletePersonOutcome::NotFound],
+ );
+ }
+ let mut pending: Vec<i64> = expected.keys().copied().collect();
+ pending.sort_unstable();
+ let deadline = Instant::now() + SETTLE_DEADLINE;
+ while !pending.is_empty() {
+ let mut conflicts = Vec::new();
// The lifecycle service caps batches at 250 person ids.
- for chunk in person_ids.chunks(200) {
+ for chunk in pending.chunks(200) {
let op_id = uuid::Uuid::new_v4();
- let outcomes = lifecycle
+ for (person_id, outcome) in lifecycle
.delete_persons(team_id, chunk.to_vec(), &op_id)
- .await?;
- for (person_id, outcome) in outcomes {
- if outcome != expected {
+ .await?
+ {
+ let accepted = &expected[&person_id];
+ if outcome == DeletePersonOutcome::SkippedConflict {
+ conflicts.push(person_id);
+ } else if !accepted.contains(&outcome) {
bail!(
- "lifecycle delete attempt {attempt}: person {person_id} answered \
- {outcome:?}, expected {expected:?}"
+ "lifecycle delete: person {person_id} answered {outcome:?}, \
+ expected one of {accepted:?}"
);
}
}
}
+ if conflicts.is_empty() {
+ break;
+ }
+ if Instant::now() > deadline {
+ bail!(
+ "lifecycle delete: {} persons still held by another lifecycle op after {:?}: {:?}",
+ conflicts.len(),
+ SETTLE_DEADLINE,
+ &conflicts[..conflicts.len().min(10)]
+ );
+ }
+ println!(
+ " {} persons held by an unsettled lifecycle op; waiting for the sweeper...",
+ conflicts.len()
+ );
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ pending = conflicts;
+ }
+
+ // A second attempt under a fresh op id must answer not_found for
+ // everything. Deleting a tombstone is a no-op, not an error.
+ let mut all: Vec<i64> = expected.keys().copied().collect();
+ all.sort_unstable();
+ for chunk in all.chunks(200) {
+ let op_id = uuid::Uuid::new_v4();
+ for (person_id, outcome) in lifecycle
+ .delete_persons(team_id, chunk.to_vec(), &op_id)
+ .await?
+ {
+ if outcome != DeletePersonOutcome::NotFound {
+ bail!(
+ "lifecycle re-delete: person {person_id} answered {outcome:?}, expected NotFound"
+ );
+ }
+ }
}
Ok(())
}
/// Create the traffic-target persons through the identity service's batch
-/// get-or-create, with one seed property per person. The create ack covers
-/// both planes (stub committed in Postgres, initial properties durable in
-/// the changelog), so each ack is journaled like any other write — the
+/// get-or-create, with one seed property per person, returning each
+/// person's id with its distinct id. The create ack covers both planes
+/// (stub committed in Postgres, initial properties durable in the
+/// changelog), so each ack is journaled like any other write. The
/// end-of-run strong reads and the Postgres check then hold create
/// visibility to the same invariant as update visibility.
async fn create_persons_via_identity(
@@ -611,7 +824,7 @@ async fn create_persons_via_identity(
team_id: i64,
count: u32,
state: &PersonState,
-) -> Result<Vec<i64>> {
+) -> Result<Vec<(i64, String)>> {
/// The identity service caps batches at 250 entries by default.
const CREATE_BATCH_SIZE: u32 = 250;
@@ -629,7 +842,7 @@ async fn create_persons_via_identity(
extra_distinct_ids: vec![],
event_name: "$set".to_string(),
set_properties: serde_json::to_vec(
- &serde_json::json!({ "harness_seed": distinct_id }),
+ &serde_json::json!({ SEED_KEY: distinct_id }),
)
.expect("seed properties serialize"),
set_once_properties: Vec::new(),
@@ -651,24 +864,73 @@ async fn create_persons_via_identity(
.with_context(|| format!("no person for distinct id {}", result.distinct_id))?;
if !result.created {
bail!(
- "distinct id {} already existed — the harness team must start clean",
+ "distinct id {} already existed; the harness team must start clean",
result.distinct_id
);
}
- let seed_properties = HashMap::from([(
- "harness_seed".to_string(),
- serde_json::json!(result.distinct_id),
- )]);
+ let seed_properties =
+ HashMap::from([(SEED_KEY.to_string(), serde_json::json!(result.distinct_id))]);
state
.record_write(person.id, person.version, seed_properties)
.await;
- person_ids.push(person.id);
+ person_ids.push((person.id, result.distinct_id));
}
start = end;
}
Ok(person_ids)
}
+/// Create persons with `extra_distinct_ids` extra distinct ids each, so
+/// a merge makes the flip repoint many mappings.
+async fn create_wide_persons_via_identity(
+ identity_url: &str,
+ team_id: i64,
+ count: u32,
+ extra_distinct_ids: u32,
+ state: &PersonState,
+) -> Result<Vec<(i64, String)>> {
+ let client = IdentityClient::connect(identity_url).await?;
+ let mut persons = Vec::with_capacity(count as usize);
+ for i in 0..count {
+ let distinct_id = format!("harness-gate-{team_id}-wide{i}");
+ let entry = GetOrCreatePersonEntry {
+ team_id,
+ distinct_id: distinct_id.clone(),
+ extra_distinct_ids: (0..extra_distinct_ids)
+ .map(|j| format!("{distinct_id}-{j}"))
+ .collect(),
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({ SEED_KEY: distinct_id }))
+ .expect("seed properties serialize"),
+ set_once_properties: Vec::new(),
+ created_at: 0,
+ is_identified: false,
+ };
+ let mut results = client.get_or_create_persons(vec![entry]).await?;
+ let result = results
+ .pop()
+ .context("identity returned no result for a wide person")?;
+ if let Some(error) = &result.error {
+ bail!("identity create failed for wide person {distinct_id}: {error}");
+ }
+ let person = result
+ .person
+ .with_context(|| format!("no person for wide distinct id {distinct_id}"))?;
+ if !result.created {
+ bail!("distinct id {distinct_id} already existed; the harness team must start clean");
+ }
+ state
+ .record_write(
+ person.id,
+ person.version,
+ HashMap::from([(SEED_KEY.to_string(), serde_json::json!(result.distinct_id))]),
+ )
+ .await;
+ persons.push((person.id, result.distinct_id));
+ }
+ Ok(persons)
+}
+
#[cfg(test)]
mod tests {
use clap::Parser;
diff --git a/rust/personhog-test-harness/src/scenarios/merge.rs b/rust/personhog-test-harness/src/scenarios/merge.rs
new file mode 100644
index 000000000000..b1db97613d6a
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/merge.rs
@@ -0,0 +1,700 @@
+//! The merge lane: MergePersons calls against live persons while the
+//! blast writers and probers keep writing to them.
+//!
+//! Each call names one target and one or more live sources. A source
+//! that settles as `merged` ran the durable saga end to end, with writes
+//! racing its fence and the target's fold. A source is reserved for one
+//! call at a time and is never reused after a merge, so the journal
+//! always knows which person died. Targets are shared, so two calls can
+//! contend for one person.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use anyhow::{Context, Result};
+use personhog_proto::personhog::identity::v1::MergeSourceOutcome;
+use personhog_proto::personhog::types::v1::ConsistencyLevel;
+use rand::{Rng, SeedableRng};
+use serde_json::json;
+use sqlx::postgres::PgPool;
+use sqlx::Row;
+use tokio::time::{interval, sleep, MissedTickBehavior};
+
+use crate::client::{HarnessClient, IdentityClient};
+use crate::pool::TargetPool;
+use crate::report::ConsistencyViolation;
+use crate::scenarios::blast::{is_not_found, per_worker_tick};
+use crate::scenarios::gate::SEED_KEY;
+use crate::state::{MergeAck, PersonState};
+use crate::stats::StatsCollector;
+
+/// Attempts per call, all under one op id. A retry with the same op id
+/// returns the recorded outcome and does not merge again.
+const MERGE_ATTEMPTS: u32 = 3;
+const MERGE_RETRY_BACKOFF: Duration = Duration::from_millis(500);
+
+/// The `$set_once` value sent for keys the survivor already holds. It
+/// must never land.
+const SET_ONCE_LOSER: &str = "harness_set_once_must_not_win";
+
+pub struct MergeLane {
+ pub team_id: i64,
+ pub concurrency: usize,
+ /// Combined target rate across the workers. Unset runs flat out.
+ pub rate_per_sec: Option<f64>,
+ /// Sources per call. Only a call with more than one source exercises
+ /// the leader's request-order fold.
+ pub sources_per_call: usize,
+ pub allow_identified_sources: bool,
+ pub move_limit: i64,
+ /// Persons with many distinct ids. Workers prefer them while one is
+ /// available, so the expensive merges happen before the pool thins.
+ pub wide_persons: Vec<i64>,
+ pub wide_role: WideRole,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum WideRole {
+ Source,
+ Target,
+ Both,
+}
+
+impl WideRole {
+ pub fn parse(role: &str) -> Option<Self> {
+ match role {
+ "source" => Some(Self::Source),
+ "target" => Some(Self::Target),
+ "both" => Some(Self::Both),
+ _ => None,
+ }
+ }
+}
+
+/// A merge call whose every attempt lost its response. The saga may have
+/// run anyway. The op record decides, see [`settle_unresolved`].
+pub struct UnresolvedMerge {
+ pub op_id: uuid::Uuid,
+ /// Person id and distinct id per source, in request order.
+ pub sources: Vec<(i64, String)>,
+ /// Journaled on the survivor if the op record says the merge ran.
+ pub set: HashMap<String, serde_json::Value>,
+ pub set_once: HashMap<String, serde_json::Value>,
+}
+
+pub struct MergeLaneResult {
+ pub violations: Vec<ConsistencyViolation>,
+ pub unresolved: Vec<UnresolvedMerge>,
+}
+
+/// The merge event's writes for one call. The three `$set_once` keys
+/// test the fold: a fresh key it must fill, the `$set` key it must lose
+/// to, and the seed key it must not change.
+struct MergeEvent {
+ set: HashMap<String, serde_json::Value>,
+ set_once: HashMap<String, serde_json::Value>,
+}
+
+impl MergeEvent {
+ fn new(op_id: &uuid::Uuid) -> Self {
+ let op = json!(op_id.to_string());
+ let loser = json!(SET_ONCE_LOSER);
+ Self {
+ set: HashMap::from([(format!("harness_merge_{op_id}"), op.clone())]),
+ set_once: HashMap::from([
+ (format!("harness_merge_once_{op_id}"), op),
+ (format!("harness_merge_{op_id}"), loser.clone()),
+ (SEED_KEY.to_string(), loser),
+ ]),
+ }
+ }
+
+ /// The keys and values the survivor must carry after the fold.
+ fn expected(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
+ self.set.iter().chain(
+ self.set_once
+ .iter()
+ .filter(|(_, value)| value.as_str() != Some(SET_ONCE_LOSER)),
+ )
+ }
+}
+
+/// Drive merges until the deadline. Merged acks go into `state`, and
+/// merged sources leave `pool`. Returns the violations seen live.
+#[allow(clippy::too_many_arguments)]
+pub async fn run_merges(
+ identity: &IdentityClient,
+ router: &HarnessClient,
+ lane: MergeLane,
+ pool: Arc<TargetPool>,
+ distinct_ids: Arc<HashMap<i64, String>>,
+ duration: Duration,
+ collector: &Arc<StatsCollector>,
+ state: &PersonState,
+ stop: Arc<AtomicBool>,
+) -> Result<MergeLaneResult> {
+ let deadline = Instant::now() + duration;
+ let worker_tick = lane
+ .rate_per_sec
+ .map(|rate| per_worker_tick(rate, lane.concurrency));
+ let wide: Arc<HashSet<i64>> = Arc::new(lane.wide_persons.iter().copied().collect());
+ // An ordinary pick must not spend a wide source.
+ let eligible = Arc::new(Mutex::new(
+ pool.snapshot()
+ .into_iter()
+ .filter(|id| !wide.contains(id))
+ .collect::<Vec<_>>(),
+ ));
+ let wide_sources = Arc::new(Mutex::new(match lane.wide_role {
+ WideRole::Source | WideRole::Both => lane.wide_persons.clone(),
+ WideRole::Target => Vec::new(),
+ }));
+ let wide_targets: Arc<Vec<i64>> = Arc::new(match lane.wide_role {
+ WideRole::Target | WideRole::Both => lane.wide_persons.clone(),
+ WideRole::Source => Vec::new(),
+ });
+ let dry_at: Arc<Mutex<Option<Duration>>> = Arc::new(Mutex::new(None));
+ let started = Instant::now();
+
+ let mut handles = Vec::new();
+ for _ in 0..lane.concurrency {
+ let identity = identity.clone();
+ let router = router.clone();
+ let pool = pool.clone();
+ let distinct_ids = distinct_ids.clone();
+ let eligible = eligible.clone();
+ let wide = wide.clone();
+ let wide_sources = wide_sources.clone();
+ let wide_targets = wide_targets.clone();
+ let dry_at = dry_at.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let stop = stop.clone();
+ let (team_id, allow_identified_sources, move_limit, sources_per_call) = (
+ lane.team_id,
+ lane.allow_identified_sources,
+ lane.move_limit,
+ lane.sources_per_call.max(1),
+ );
+
+ handles.push(tokio::spawn(async move {
+ let mut rng = rand::rngs::StdRng::from_entropy();
+ let mut pacer = worker_tick.map(|tick| {
+ let mut ticker = interval(tick);
+ ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
+ ticker
+ });
+ let mut violations = Vec::new();
+ let mut unresolved = Vec::new();
+ let release = |source: i64| {
+ if wide.contains(&source) {
+ wide_sources.lock().unwrap().push(source);
+ } else {
+ eligible.lock().unwrap().push(source);
+ }
+ };
+
+ while Instant::now() < deadline && !stop.load(Ordering::Relaxed) {
+ if let Some(pacer) = pacer.as_mut() {
+ pacer.tick().await;
+ }
+ let picked =
+ pick_wide_pair(&wide_sources, &wide_targets, &eligible, &pool, &mut rng)
+ .or_else(|| pick_pair(&eligible, &pool, &mut rng));
+ let Some((first_source, target)) = picked else {
+ // The pool is almost empty, or every source is
+ // reserved.
+ if pool.len() < 2 {
+ note_dry(&dry_at, started.elapsed());
+ }
+ sleep(Duration::from_millis(200)).await;
+ continue;
+ };
+ let mut sources = vec![first_source];
+ reserve_more_sources(&eligible, &mut sources, target, sources_per_call, &mut rng);
+ let Some(target_did) = distinct_ids.get(&target) else {
+ unreachable!("every pooled person was created with a distinct id");
+ };
+ let source_dids: Vec<String> = sources
+ .iter()
+ .map(|source| {
+ distinct_ids.get(source).cloned().unwrap_or_else(|| {
+ unreachable!("every pooled person was created with a distinct id")
+ })
+ })
+ .collect();
+
+ for &source in &sources {
+ state.mark_merge_pending(source).await;
+ }
+ let op_id = uuid::Uuid::new_v4();
+ let event = MergeEvent::new(&op_id);
+
+ let start = Instant::now();
+ let mut attempt = 0;
+ let response = loop {
+ attempt += 1;
+ let result = identity
+ .merge_persons(
+ team_id,
+ target_did,
+ &source_dids,
+ json!(event.set),
+ json!(event.set_once),
+ &op_id,
+ allow_identified_sources,
+ move_limit,
+ )
+ .await;
+ match result {
+ Ok(response) => break Some(response),
+ Err(e) if attempt < MERGE_ATTEMPTS => {
+ tracing::warn!(
+ ?sources,
+ target,
+ attempt,
+ error = format!("{e:#}"),
+ "merge call failed; retrying under the same op id"
+ );
+ sleep(MERGE_RETRY_BACKOFF).await;
+ }
+ Err(e) => {
+ tracing::warn!(
+ ?sources,
+ target,
+ error = format!("{e:#}"),
+ "merge call failed on every attempt; source outcomes unknown"
+ );
+ break None;
+ }
+ }
+ };
+
+ let recorder = if wide.contains(&target) || sources.iter().any(|s| wide.contains(s))
+ {
+ &collector.wide_merges
+ } else {
+ &collector.merges
+ };
+ let Some(response) = response else {
+ recorder.record_failure();
+ // The saga can still destroy the sources after this
+ // failure. The op record settles them after traffic.
+ // Until then the sources stay reserved and take no
+ // traffic.
+ for &source in &sources {
+ state.record_merge_uncertain(source).await;
+ pool.remove(source);
+ }
+ unresolved.push(UnresolvedMerge {
+ op_id,
+ sources: sources.iter().copied().zip(source_dids).collect(),
+ set: event.set,
+ set_once: event.set_once,
+ });
+ continue;
+ };
+ recorder.record_success(start.elapsed());
+
+ let mut merged = Vec::new();
+ for (&source, source_did) in sources.iter().zip(&source_dids) {
+ let outcome = response
+ .results
+ .iter()
+ .find(|r| r.source_distinct_id == *source_did)
+ .map(|r| r.outcome())
+ .unwrap_or(MergeSourceOutcome::Unspecified);
+ collector.record_merge_outcome(outcome_name(outcome));
+ if outcome == MergeSourceOutcome::Merged {
+ merged.push(source);
+ } else {
+ // Every outcome except merged leaves the source alive.
+ state.clear_merge_pending(source).await;
+ release(source);
+ }
+ }
+ if merged.is_empty() {
+ continue;
+ }
+
+ let Some(survivor) = response.survivor else {
+ // The sources are destroyed, but the survivor is
+ // unknown. Keep them reserved, so reads tolerate
+ // their absence.
+ for &source in &merged {
+ violations.push(ConsistencyViolation {
+ person_id: source,
+ key: "__merge_ack_missing_survivor".to_string(),
+ expected: json!("a merged ack carries the survivor document"),
+ actual: serde_json::Value::Null,
+ });
+ state.record_merge_uncertain(source).await;
+ pool.remove(source);
+ }
+ continue;
+ };
+ let survivor_props: serde_json::Value =
+ serde_json::from_slice(&survivor.properties).unwrap_or_else(|_| json!({}));
+ // The ack carries the folded document, so the merge
+ // event's writes must already be in it.
+ for (key, value) in event.expected() {
+ if survivor_props.get(key) != Some(value) {
+ violations.push(ConsistencyViolation {
+ person_id: survivor.id,
+ key: key.clone(),
+ expected: value.clone(),
+ actual: survivor_props
+ .get(key)
+ .cloned()
+ .unwrap_or(serde_json::Value::Null),
+ });
+ }
+ }
+ if survivor_props.get(SEED_KEY) == Some(&json!(SET_ONCE_LOSER)) {
+ violations.push(ConsistencyViolation {
+ person_id: survivor.id,
+ key: SEED_KEY.to_string(),
+ expected: json!(
+ "the value the fold carried; $set_once must not replace it"
+ ),
+ actual: json!(SET_ONCE_LOSER),
+ });
+ }
+ state
+ .record_merge(MergeAck {
+ survivor: survivor.id,
+ survivor_version: survivor.version,
+ sources: merged.clone(),
+ set: event.set,
+ set_once: event.set_once,
+ })
+ .await;
+ for &source in &merged {
+ pool.remove(source);
+ }
+
+ // A strong read after the ack must not find a living
+ // source.
+ for &source in &merged {
+ let read_start = Instant::now();
+ match router
+ .get_person(team_id, source, ConsistencyLevel::Strong)
+ .await
+ {
+ Ok(Some(person)) if !person.is_deleted => {
+ collector.reads.record_success(read_start.elapsed());
+ violations.push(ConsistencyViolation {
+ person_id: source,
+ key: "__merged_source_alive".to_string(),
+ expected: json!("not found after the merge ack"),
+ actual: json!({ "version": person.version }),
+ });
+ }
+ Ok(_) => collector.reads.record_success(read_start.elapsed()),
+ Err(e) if is_not_found(&e) => {
+ collector.reads.record_success(read_start.elapsed())
+ }
+ Err(e) => {
+ // Readability is end-of-run verification's job.
+ collector.reads.record_failure();
+ tracing::warn!(source, error = %e, "post-merge read failed");
+ }
+ }
+ }
+ }
+ (violations, unresolved)
+ }));
+ }
+
+ let mut violations = Vec::new();
+ let mut unresolved = Vec::new();
+ for handle in handles {
+ let (worker_violations, worker_unresolved) =
+ handle.await.context("merge worker panicked")?;
+ violations.extend(worker_violations);
+ unresolved.extend(worker_unresolved);
+ }
+ if let Some(at) = *dry_at.lock().unwrap() {
+ println!(
+ "Merge lane ran the pool dry {:.1}s into traffic; size --persons up or the rate down \
+ for a longer merge window",
+ at.as_secs_f64()
+ );
+ }
+ Ok(MergeLaneResult {
+ violations,
+ unresolved,
+ })
+}
+
+/// Settle each unresolved merge from its op record. A `completed` op is
+/// journaled as a merge with the sources the record says merged. An
+/// aborted op, or a missing op row, means every source lived on. An op
+/// still in flight is polled until `deadline`, which gives the sweeper
+/// time to re-drive it. An op that never settles is a violation.
+pub async fn settle_unresolved(
+ pool: &PgPool,
+ state: &PersonState,
+ unresolved: Vec<UnresolvedMerge>,
+ deadline: Duration,
+) -> Result<Vec<ConsistencyViolation>> {
+ if unresolved.is_empty() {
+ return Ok(Vec::new());
+ }
+ println!(
+ "Settling {} merge calls that lost every response from the saga's op records...",
+ unresolved.len()
+ );
+ let mut violations = Vec::new();
+ let mut pending = unresolved;
+ let started = Instant::now();
+ loop {
+ let mut still_pending = Vec::new();
+ for merge in pending {
+ let row = sqlx::query("SELECT step, outcome FROM lifecycle_op WHERE op_id = $1")
+ .bind(merge.op_id)
+ .fetch_optional(pool)
+ .await
+ .context("reading an unresolved merge op")?;
+ let Some(row) = row else {
+ // No op row means the saga never started.
+ for (source, _) in &merge.sources {
+ state.clear_merge_pending(*source).await;
+ }
+ continue;
+ };
+ let step: String = row.get("step");
+ let outcome: Option<serde_json::Value> = row.get("outcome");
+ match step.as_str() {
+ "completed" => {
+ let outcome = outcome.unwrap_or_default();
+ let merged_dids: HashSet<&str> = outcome["results"]
+ .as_array()
+ .map(|results| {
+ results
+ .iter()
+ .filter(|r| r["outcome"] == "merged")
+ .filter_map(|r| r["distinct_id"].as_str())
+ .collect()
+ })
+ .unwrap_or_default();
+ let mut merged = Vec::new();
+ for (source, did) in &merge.sources {
+ if merged_dids.contains(did.as_str()) {
+ merged.push(*source);
+ } else {
+ state.clear_merge_pending(*source).await;
+ }
+ }
+ if merged.is_empty() {
+ continue;
+ }
+ let survivor = &outcome["survivor"];
+ match (survivor["id"].as_i64(), survivor["version"].as_i64()) {
+ (Some(id), Some(version)) => {
+ state
+ .record_merge(MergeAck {
+ survivor: id,
+ survivor_version: version,
+ sources: merged,
+ set: merge.set,
+ set_once: merge.set_once,
+ })
+ .await;
+ }
+ _ => {
+ for source in merged {
+ violations.push(ConsistencyViolation {
+ person_id: source,
+ key: "__merge_record_missing_survivor".to_string(),
+ expected: json!("a completed merge records its survivor"),
+ actual: outcome.clone(),
+ });
+ }
+ }
+ }
+ }
+ "aborted" => {
+ for (source, _) in &merge.sources {
+ state.clear_merge_pending(*source).await;
+ }
+ }
+ _ => still_pending.push(merge),
+ }
+ }
+ if still_pending.is_empty() {
+ return Ok(violations);
+ }
+ if started.elapsed() > deadline {
+ for merge in still_pending {
+ for (source, _) in merge.sources {
+ violations.push(ConsistencyViolation {
+ person_id: source,
+ key: "__merge_unsettled".to_string(),
+ expected: json!(format!("op {} terminal within {deadline:?}", merge.op_id)),
+ actual: json!("in flight"),
+ });
+ }
+ }
+ return Ok(violations);
+ }
+ sleep(Duration::from_secs(2)).await;
+ pending = still_pending;
+ }
+}
+
+/// A pair with a wide person on the configured side. None when no wide
+/// source is free and no wide target is live.
+fn pick_wide_pair(
+ wide_sources: &Mutex<Vec<i64>>,
+ wide_targets: &[i64],
+ eligible: &Mutex<Vec<i64>>,
+ pool: &TargetPool,
+ rng: &mut impl Rng,
+) -> Option<(i64, i64)> {
+ let live = pool.snapshot();
+ let live_wide_targets: Vec<i64> = wide_targets
+ .iter()
+ .copied()
+ .filter(|id| live.contains(id))
+ .collect();
+ let source = {
+ let mut wide_sources = wide_sources.lock().unwrap();
+ if wide_sources.is_empty() {
+ None
+ } else {
+ let index = rng.gen_range(0..wide_sources.len());
+ Some(wide_sources.swap_remove(index))
+ }
+ };
+ match source {
+ Some(source) => {
+ let target = if live_wide_targets.is_empty() {
+ (0..16)
+ .filter_map(|_| pool.pick_random(rng))
+ .find(|&target| target != source)
+ } else {
+ live_wide_targets
+ .iter()
+ .copied()
+ .filter(|&target| target != source)
+ .nth(rng.gen_range(0..live_wide_targets.len().max(1)))
+ .or_else(|| live_wide_targets.iter().copied().find(|&t| t != source))
+ };
+ match target {
+ Some(target) => Some((source, target)),
+ None => {
+ wide_sources.lock().unwrap().push(source);
+ None
+ }
+ }
+ }
+ None if !live_wide_targets.is_empty() => {
+ let target = live_wide_targets[rng.gen_range(0..live_wide_targets.len())];
+ let mut eligible = eligible.lock().unwrap();
+ let candidates: Vec<usize> = (0..eligible.len())
+ .filter(|&i| eligible[i] != target)
+ .collect();
+ if candidates.is_empty() {
+ return None;
+ }
+ let source = eligible.swap_remove(candidates[rng.gen_range(0..candidates.len())]);
+ Some((source, target))
+ }
+ None => None,
+ }
+}
+
+/// Reserve a random eligible source and pick a different live target.
+/// None when fewer than two live persons remain or every source is
+/// reserved.
+fn pick_pair(
+ eligible: &Mutex<Vec<i64>>,
+ pool: &TargetPool,
+ rng: &mut impl Rng,
+) -> Option<(i64, i64)> {
+ let mut eligible = eligible.lock().unwrap();
+ if eligible.is_empty() || pool.len() < 2 {
+ return None;
+ }
+ let index = rng.gen_range(0..eligible.len());
+ let source = eligible.swap_remove(index);
+ // A few random draws almost always find a different target. A miss
+ // puts the source back.
+ for _ in 0..16 {
+ match pool.pick_random(rng) {
+ Some(target) if target != source => return Some((source, target)),
+ _ => {}
+ }
+ }
+ eligible.push(source);
+ None
+}
+
+/// Reserve ordinary sources until the call carries `wanted`, or the
+/// eligible set runs out. The target is never a source of its own call.
+fn reserve_more_sources(
+ eligible: &Mutex<Vec<i64>>,
+ sources: &mut Vec<i64>,
+ target: i64,
+ wanted: usize,
+ rng: &mut impl Rng,
+) {
+ let mut eligible = eligible.lock().unwrap();
+ while sources.len() < wanted {
+ let candidates: Vec<usize> = (0..eligible.len())
+ .filter(|&i| eligible[i] != target)
+ .collect();
+ if candidates.is_empty() {
+ return;
+ }
+ let source = eligible.swap_remove(candidates[rng.gen_range(0..candidates.len())]);
+ sources.push(source);
+ }
+}
+
+fn note_dry(dry_at: &Mutex<Option<Duration>>, at: Duration) {
+ let mut dry = dry_at.lock().unwrap();
+ if dry.is_none() {
+ *dry = Some(at);
+ }
+}
+
+pub fn outcome_name(outcome: MergeSourceOutcome) -> &'static str {
+ match outcome {
+ MergeSourceOutcome::Merged => "merged",
+ MergeSourceOutcome::NoopSamePerson => "noop_same_person",
+ MergeSourceOutcome::Attached => "attached",
+ MergeSourceOutcome::SkippedIllegal => "skipped_illegal",
+ MergeSourceOutcome::SkippedAlreadyIdentified => "skipped_already_identified",
+ MergeSourceOutcome::SkippedConflict => "skipped_conflict",
+ MergeSourceOutcome::SkippedMoveLimit => "skipped_move_limit",
+ MergeSourceOutcome::Error => "error",
+ MergeSourceOutcome::Unspecified => "unspecified",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The target is never one of its own sources, and each source
+ /// leaves the eligible set exactly once.
+ #[test]
+ fn extra_sources_are_reserved_apart_from_the_target() {
+ let mut rng = rand::rngs::StdRng::seed_from_u64(7);
+ let eligible = Mutex::new(vec![2, 3, 4]);
+ let mut sources = vec![1];
+ reserve_more_sources(&eligible, &mut sources, 3, 3, &mut rng);
+ sources.sort_unstable();
+ assert_eq!(sources, vec![1, 2, 4]);
+ assert_eq!(*eligible.lock().unwrap(), vec![3]);
+
+ // An empty eligible set caps the call. The target stays.
+ reserve_more_sources(&eligible, &mut sources, 3, 10, &mut rng);
+ assert_eq!(sources.len(), 3);
+ assert_eq!(*eligible.lock().unwrap(), vec![3]);
+ }
+}
diff --git a/rust/personhog-test-harness/src/scenarios/mod.rs b/rust/personhog-test-harness/src/scenarios/mod.rs
index b89c504ee881..1f8e50943605 100644
--- a/rust/personhog-test-harness/src/scenarios/mod.rs
+++ b/rust/personhog-test-harness/src/scenarios/mod.rs
@@ -2,5 +2,6 @@ pub mod blast;
pub mod chaos;
pub mod consistency;
pub mod gate;
+pub mod merge;
pub mod seed_cmd;
pub mod traffic;
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
index bc8efeb057c0..574941ba8b06 100644
--- a/rust/personhog-test-harness/src/scenarios/traffic.rs
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -27,6 +27,7 @@
//! epoch's load short and runs the normal close-out (verify what was
//! acked, record, clean up) inside the termination grace window.
+use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -47,6 +48,7 @@ use uuid::Uuid;
use crate::cli::TrafficArgs;
use crate::client::HarnessClient;
use crate::client::{IdentityClient, LifecycleClient};
+use crate::pool::TargetPool;
use crate::report::ConsistencyViolation;
use crate::scenarios::chaos::{self, ChaosConfig, TargetKind, TargetSpec};
use crate::scenarios::{blast, consistency};
@@ -261,9 +263,10 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
let collector = Arc::new(StatsCollector::new());
let state = PersonState::new();
+ let pool = Arc::new(TargetPool::new(person_ids.as_ref().clone()));
let traffic = {
let client = client.clone();
- let person_ids = person_ids.clone();
+ let person_ids = pool.clone();
let collector = collector.clone();
let state = state.clone();
let (duration, concurrency) = (args.epoch, args.concurrency);
@@ -291,7 +294,7 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
};
let probers = {
let client = client.clone();
- let person_ids = person_ids.clone();
+ let person_ids = pool.clone();
let collector = collector.clone();
let state = state.clone();
let duration = args.epoch;
@@ -357,7 +360,9 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
blast::verify_strong(client, &lane.collector, &lane.state, team_id).await?,
);
let journal = lane.state.snapshot().await;
- lane_violations.extend(verify_postgres(pool, table, team_id, &journal).await?);
+ lane_violations.extend(
+ verify_postgres(pool, table, team_id, &journal, &HashMap::new()).await?,
+ );
anyhow::Ok((team_id, lane_violations, lane.collector.writes.snapshot()))
};
close
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index 1c9ff73568f1..b9e720f3ef96 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -54,7 +54,7 @@ pub async fn seed_persons(
/// writes and whose FK blocks the person delete. Cleanup stays inside
/// the person table's own namespace: targeting the validation set must
/// never delete from the real tables.
-fn distinct_id_tables_for(person_table: &str) -> &'static [&'static str] {
+pub fn distinct_id_tables_for(person_table: &str) -> &'static [&'static str] {
if person_table == "personhog_person_tmp" {
&["personhog_persondistinctid_tmp"]
} else {
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 3f87e440520d..cf0fb8bfa511 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -259,6 +259,12 @@ impl Stack {
("PERSON_TABLE", config.pg_target_table.clone()),
("PERSON_DISTINCT_ID_TABLE", pdi_table.to_string()),
("FF_HASH_KEY_OVERRIDE_TABLE", ffhko_table.to_string()),
+ // The service default is off. The gate needs the
+ // sweeper: a leader kill abandons a merge mid-saga,
+ // and only the sweeper re-drives it. The short
+ // interval fits a short run.
+ ("LIFECYCLE_SWEEPER_ENABLED", "true".to_string()),
+ ("LIFECYCLE_SWEEP_INTERVAL_SECS", "3".to_string()),
],
&log_dir,
)?);
diff --git a/rust/personhog-test-harness/src/state.rs b/rust/personhog-test-harness/src/state.rs
index 002184e3ce47..290707e45c6f 100644
--- a/rust/personhog-test-harness/src/state.rs
+++ b/rust/personhog-test-harness/src/state.rs
@@ -13,6 +13,11 @@ use crate::report::ConsistencyViolation;
/// belongs to one worker and workers write sequentially. A write whose
/// outcome is unknown breaks that and drops its key — see
/// [`PersonState::record_write_uncertain`].
+///
+/// Merges make the journal a tree. Each person keeps the keys its own
+/// acks set. A merged source hangs off the survivor its ack named. A
+/// live person's expected document is folded from that tree, so a late
+/// ack for a merged person only updates that person's own keys.
#[derive(Clone)]
pub struct PersonState {
inner: Arc<RwLock<Journal>>,
@@ -20,7 +25,9 @@ pub struct PersonState {
#[derive(Default)]
struct Journal {
- persons: HashMap<i64, ExpectedPerson>,
+ /// Every journaled person, alive or merged. A merged person keeps
+ /// its node because its keys fold into the survivor.
+ persons: HashMap<i64, PersonNode>,
/// Persons currently frozen by a lifecycle fence, mapped to their
/// sealed version. While a person is here, no write above the sealed
/// version may be acked — the fence's whole guarantee. Writes acked at
@@ -36,17 +43,223 @@ struct Journal {
/// in whatever order the responses land, so a lower version arriving
/// after a higher one is normal.
anomalies: Vec<ConsistencyViolation>,
+ /// The tree's edges, keyed by the merged source. An edge points at
+ /// the survivor the ack named, even when that survivor is merged
+ /// already, because the fold happened into that person's document
+ /// at that person's version.
+ merged: HashMap<i64, MergeEdge>,
+ /// The reverse of `merged`: the sources folded into each person.
+ children: HashMap<i64, Vec<i64>>,
+ /// Sources with a merge call in flight. A read that cannot find one
+ /// of these is the saga at work, not lost data.
+ merge_pending: HashSet<i64>,
+}
+
+struct MergeEdge {
+ survivor: i64,
+ /// The survivor version the fold produced. Folds into one survivor
+ /// fill keys in this order.
+ fold_version: i64,
+ /// Position among the sources of one call. The leader fills from
+ /// them in request order.
+ ordinal: usize,
+}
+
+/// What the journal keeps about a person after a merge destroyed it.
+pub struct MergedSource {
+ /// The person the source folded into, as answered by the merge ack.
+ /// A later merge can destroy it too.
+ pub survivor: i64,
+ /// Highest version the leader acked for the source, before or after
+ /// the merge was journaled. The fence seals the source at its
+ /// current version, so every ack must sit at or below the sealed
+ /// version the saga recorded. An ack above the seal means the fence
+ /// failed open.
+ pub max_acked_version: i64,
+}
+
+impl MergedSource {
+ #[cfg(test)]
+ pub fn for_test(survivor: i64, max_acked_version: i64) -> Self {
+ Self {
+ survivor,
+ max_acked_version,
+ }
+ }
+}
+
+/// A MergePersons ack: the sources it merged, in request order, and the
+/// survivor's version. `set` overrides on the survivor after the fold.
+/// `set_once` fills only keys still absent after that.
+pub struct MergeAck {
+ pub survivor: i64,
+ pub survivor_version: i64,
+ pub sources: Vec<i64>,
+ pub set: HashMap<String, serde_json::Value>,
+ pub set_once: HashMap<String, serde_json::Value>,
}
+/// A live person's expected document, for verification.
+#[derive(Clone)]
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,
+}
+
+/// The keys a person's own acks set.
+struct PersonNode {
+ own: HashMap<String, serde_json::Value>,
+ last_version: i64,
/// Every version the leader acked for this person, for duplicate
/// detection.
acked_versions: HashSet<i64>,
+ /// Keys whose last write errored. Such a write can still apply, so
+ /// the person can hold a value the journal does not know. A merge
+ /// fold must not assert a source's value for such a key, because
+ /// the target wins every key it actually has, known to the journal
+ /// or not. The next ack for the key clears it.
+ uncertain_keys: HashSet<String>,
+ /// The ack version that last set each key. Diagnostics only.
+ own_origins: HashMap<String, i64>,
+}
+
+impl PersonNode {
+ fn empty() -> Self {
+ Self {
+ own: HashMap::new(),
+ last_version: 0,
+ acked_versions: HashSet::new(),
+ uncertain_keys: HashSet::new(),
+ own_origins: HashMap::new(),
+ }
+ }
+
+ fn insert_acked(&mut self, properties: HashMap<String, serde_json::Value>) {
+ self.insert_acked_at(properties, None);
+ }
+
+ fn insert_acked_at(
+ &mut self,
+ properties: HashMap<String, serde_json::Value>,
+ version: Option<i64>,
+ ) {
+ for (k, v) in properties {
+ self.uncertain_keys.remove(&k);
+ match version {
+ Some(version) => {
+ self.own_origins.insert(k.clone(), version);
+ }
+ None => {
+ self.own_origins.remove(&k);
+ }
+ }
+ self.own.insert(k, v);
+ }
+ }
+
+ /// Claim `version`. False when an earlier ack already claimed it.
+ fn claim_version(&mut self, version: i64) -> bool {
+ self.last_version = self.last_version.max(version);
+ self.acked_versions.insert(version)
+ }
+}
+
+/// How the journal came by its expectation for a key.
+enum Origin {
+ Own(Option<i64>),
+ Fold { source: i64, fold_version: i64 },
+}
+
+/// A person's document as the fold builds it: own keys first, then each
+/// merged source in fold order, filling only absent keys.
+#[derive(Default)]
+struct Folded {
+ properties: HashMap<String, serde_json::Value>,
+ /// Keys the person can hold from an errored write. Neither asserted
+ /// nor filled from a source.
+ uncertain: HashSet<String>,
+ origins: HashMap<String, Origin>,
+}
+
+impl Journal {
+ /// Follow the merge chain to the person that holds `person_id`'s
+ /// document now.
+ fn resolve(&self, mut person_id: i64) -> i64 {
+ let mut hops = 0;
+ while let Some(edge) = self.merged.get(&person_id) {
+ person_id = edge.survivor;
+ hops += 1;
+ if hops > self.merged.len() {
+ unreachable!("merge chain cycles: a person cannot survive its own merge");
+ }
+ }
+ person_id
+ }
+
+ fn node(&mut self, person_id: i64) -> &mut PersonNode {
+ self.persons
+ .entry(person_id)
+ .or_insert_with(PersonNode::empty)
+ }
+
+ fn is_live(&self, person_id: i64) -> bool {
+ !self.merged.contains_key(&person_id)
+ }
+
+ /// The leader's fold rule: a person wins every key its own acks set,
+ /// and merged sources fill the rest in fold order. A source is
+ /// folded the same way first, because that is the document its seal
+ /// carried.
+ fn fold(&self, person_id: i64) -> Folded {
+ let mut doc = Folded::default();
+ if let Some(node) = self.persons.get(&person_id) {
+ for (k, v) in &node.own {
+ doc.origins
+ .insert(k.clone(), Origin::Own(node.own_origins.get(k).copied()));
+ doc.properties.insert(k.clone(), v.clone());
+ }
+ doc.uncertain = node.uncertain_keys.clone();
+ }
+ let mut sources: Vec<(i64, usize, i64)> = self
+ .children
+ .get(&person_id)
+ .map(|children| {
+ children
+ .iter()
+ .map(|&source| {
+ let edge = &self.merged[&source];
+ (edge.fold_version, edge.ordinal, source)
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ sources.sort_unstable();
+ for (fold_version, _, source) in sources {
+ let folded = self.fold(source);
+ for (k, v) in folded.properties {
+ if doc.properties.contains_key(&k) || doc.uncertain.contains(&k) {
+ continue;
+ }
+ doc.origins.insert(
+ k.clone(),
+ Origin::Fold {
+ source,
+ fold_version,
+ },
+ );
+ doc.properties.insert(k, v);
+ }
+ for k in folded.uncertain {
+ if !doc.properties.contains_key(&k) {
+ doc.uncertain.insert(k);
+ }
+ }
+ }
+ doc
+ }
}
impl PersonState {
@@ -60,7 +273,10 @@ impl PersonState {
/// version: the leader assigns each applied update a fresh version
/// under the per-person lock, so two applied acks sharing one version
/// means two writes served from the same base state — the split-brain
- /// signature the duplicate check exists to catch.
+ /// signature the duplicate check exists to catch. An ack for a merged
+ /// person is a pre-seal write whose response landed late. It joins
+ /// that person's own keys and raises the version its tombstone must
+ /// sit above.
pub async fn record_write(
&self,
person_id: i64,
@@ -68,19 +284,9 @@ impl PersonState {
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);
- }
+ let entry = journal.node(person_id);
+ let duplicate = !entry.claim_version(version);
+ entry.insert_acked_at(properties, Some(version));
if duplicate {
journal.anomalies.push(ConsistencyViolation {
person_id,
@@ -135,27 +341,23 @@ impl PersonState {
person_id: 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(),
- });
- for (k, v) in properties {
- entry.written_properties.insert(k, v);
- }
+ self.inner
+ .write()
+ .await
+ .node(person_id)
+ .insert_acked(properties);
}
- /// Drop a key whose write errored: it may still have applied, so the
- /// journalled value could be superseded and asserting it would fail a
- /// correct stack. The next ack for the key restores coverage.
+ /// Drop a key whose write errored: the write can still apply, so the
+ /// journalled value could be superseded and asserting it would fail
+ /// a correct stack. The next ack for the key restores coverage. For
+ /// a merged source the taint folds into the survivor, because the
+ /// write can have landed before the seal.
pub async fn record_write_uncertain(&self, person_id: i64, key: &str) {
let mut journal = self.inner.write().await;
if let Some(entry) = journal.persons.get_mut(&person_id) {
- entry.written_properties.remove(key);
+ entry.own.remove(key);
+ entry.uncertain_keys.insert(key.to_string());
}
}
@@ -176,19 +378,136 @@ impl PersonState {
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(),
+ journal.node(person_id).insert_acked(properties);
+ }
+
+ /// Reserve a source for an in-flight merge call. Until
+ /// [`PersonState::record_merge`] or [`PersonState::clear_merge_pending`],
+ /// a read that cannot find the person is the saga's doing.
+ pub async fn mark_merge_pending(&self, source_id: i64) {
+ self.inner.write().await.merge_pending.insert(source_id);
+ }
+
+ /// The merge call settled without destroying the source.
+ pub async fn clear_merge_pending(&self, source_id: i64) {
+ self.inner.write().await.merge_pending.remove(&source_id);
+ }
+
+ /// Whether a not-found for this person is expected: a merge is in
+ /// flight for it, or one already destroyed it.
+ pub async fn is_merge_pending_or_merged(&self, person_id: i64) -> bool {
+ let journal = self.inner.read().await;
+ journal.merge_pending.contains(&person_id) || journal.merged.contains_key(&person_id)
+ }
+
+ /// Journal a merge ack. Each source hangs off the named survivor from
+ /// here, so the survivor's document folds the sources' keys: the
+ /// survivor wins every key it has, and the sources fill the rest in
+ /// request order. Then `set` overrides and `set_once` fills the keys
+ /// still absent. The folded version is claimed on the named
+ /// survivor, even when a later merge's ack already merged that
+ /// person. From here every source must be gone.
+ pub async fn record_merge(&self, ack: MergeAck) {
+ let mut journal = self.inner.write().await;
+ let mut ordinal = 0;
+ for source in ack.sources {
+ journal.merge_pending.remove(&source);
+ let survives_itself = source == ack.survivor || journal.resolve(ack.survivor) == source;
+ if journal.merged.contains_key(&source) || survives_itself {
+ journal.anomalies.push(ConsistencyViolation {
+ person_id: source,
+ key: "__merged_twice".to_string(),
+ expected: serde_json::json!("a person is destroyed by at most one merge"),
+ actual: serde_json::json!(ack.survivor),
+ });
+ continue;
+ }
+ journal.node(source);
+ journal.merged.insert(
+ source,
+ MergeEdge {
+ survivor: ack.survivor,
+ fold_version: ack.survivor_version,
+ ordinal,
+ },
+ );
+ journal
+ .children
+ .entry(ack.survivor)
+ .or_default()
+ .push(source);
+ ordinal += 1;
+ }
+ // The fold must include the sources attached above before
+ // `set_once` is checked.
+ let folded = journal.fold(ack.survivor);
+ let entry = journal.node(ack.survivor);
+ entry.insert_acked_at(ack.set, Some(ack.survivor_version));
+ for (key, value) in ack.set_once {
+ let present = entry.own.contains_key(&key)
+ || folded.properties.contains_key(&key)
+ || folded.uncertain.contains(&key);
+ if present {
+ continue;
+ }
+ entry.insert_acked_at(HashMap::from([(key, value)]), Some(ack.survivor_version));
+ }
+ if !entry.claim_version(ack.survivor_version) {
+ journal.anomalies.push(ConsistencyViolation {
+ person_id: ack.survivor,
+ key: "__ack_version_duplicate".to_string(),
+ expected: serde_json::json!("each version acked at most once"),
+ actual: serde_json::json!(ack.survivor_version),
});
- for (k, v) in properties {
- entry.written_properties.insert(k, v);
}
}
+ /// A merge call for `source_id` lost every response. The saga can
+ /// still destroy the person. The person stays reserved until the op
+ /// record settles it: `record_merge` when the merge ran,
+ /// `clear_merge_pending` when it did not.
+ pub async fn record_merge_uncertain(&self, source_id: i64) {
+ self.inner.write().await.merge_pending.insert(source_id);
+ }
+
+ /// Persons whose merge call never answered.
+ pub async fn merge_uncertain_ids(&self) -> Vec<i64> {
+ self.inner
+ .read()
+ .await
+ .merge_pending
+ .iter()
+ .copied()
+ .collect()
+ }
+
+ /// Persons destroyed by a journaled merge.
+ pub async fn merged_source_ids(&self) -> Vec<i64> {
+ self.inner.read().await.merged.keys().copied().collect()
+ }
+
+ /// The merged-source records for offline (Postgres) verification.
+ pub async fn snapshot_merged(&self) -> HashMap<i64, MergedSource> {
+ let journal = self.inner.read().await;
+ journal
+ .merged
+ .iter()
+ .map(|(id, edge)| {
+ (
+ *id,
+ MergedSource {
+ survivor: edge.survivor,
+ max_acked_version: journal
+ .persons
+ .get(id)
+ .map(|node| node.last_version)
+ .unwrap_or_default(),
+ },
+ )
+ })
+ .collect()
+ }
+
/// Duplicate-version and response anomalies observed while journaling.
pub async fn take_anomalies(&self) -> Vec<ConsistencyViolation> {
mem::take(&mut self.inner.write().await.anomalies)
@@ -196,7 +515,8 @@ impl PersonState {
/// 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.
+ /// acked version. A merged person has nothing to verify: its document
+ /// lives on in the survivor.
pub async fn verify(
&self,
person_id: i64,
@@ -204,30 +524,106 @@ impl PersonState {
observed_version: i64,
) -> Vec<ConsistencyViolation> {
let journal = self.inner.read().await;
- let Some(expected) = journal.persons.get(&person_id) else {
+ if !journal.is_live(person_id) {
+ return vec![];
+ }
+ let Some(node) = 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 {
+ let folded = journal.fold(person_id);
+ let mut violations = verify_properties(person_id, &folded.properties, actual_properties);
+ if observed_version < node.last_version {
violations.push(ConsistencyViolation {
person_id,
key: "__strong_read_version".to_string(),
- expected: serde_json::json!(format!(">= {}", expected.last_version)),
+ expected: serde_json::json!(format!(">= {}", node.last_version)),
actual: serde_json::json!(observed_version),
});
}
violations
}
+ /// A diagnostic account of a person's journal: its versions, the
+ /// merges that fed it, and where each of `keys` came from.
+ pub async fn describe(&self, person_id: i64, keys: &[String]) -> String {
+ let journal = self.inner.read().await;
+ let mut lines = Vec::new();
+ let mut sources: Vec<String> = journal
+ .merged
+ .iter()
+ .filter(|(_, edge)| journal.resolve(edge.survivor) == person_id)
+ .map(|(source, edge)| {
+ let max_acked = journal
+ .persons
+ .get(source)
+ .map(|node| node.last_version)
+ .unwrap_or_default();
+ format!(
+ "{source} (into {} at v{}, max acked v{max_acked})",
+ edge.survivor, edge.fold_version
+ )
+ })
+ .collect();
+ sources.sort();
+ match journal.persons.get(&person_id) {
+ Some(node) => {
+ let folded = journal.fold(person_id);
+ lines.push(format!(
+ "person {person_id}: last acked v{}, {} keys, merged sources: [{}]",
+ node.last_version,
+ folded.properties.len(),
+ sources.join(", ")
+ ));
+ for key in keys {
+ let origin = match folded.origins.get(key) {
+ Some(Origin::Own(Some(version))) => format!("own ack v{version}"),
+ Some(Origin::Own(None)) => "own no-change ack".to_string(),
+ Some(Origin::Fold {
+ source,
+ fold_version,
+ }) => format!("fold from person {source} at v{fold_version}"),
+ None if folded.uncertain.contains(key) => {
+ "uncertain: the last write errored".to_string()
+ }
+ None => "not journaled".to_string(),
+ };
+ lines.push(format!(" {key}: {origin}"));
+ }
+ }
+ None => lines.push(format!("person {person_id}: not in the journal")),
+ }
+ lines.join("\n")
+ }
+
+ /// The journaled persons that no merge destroyed.
pub async fn person_ids(&self) -> Vec<i64> {
- self.inner.read().await.persons.keys().copied().collect()
+ let journal = self.inner.read().await;
+ journal
+ .persons
+ .keys()
+ .copied()
+ .filter(|&id| journal.is_live(id))
+ .collect()
}
- /// Drain the journal into a plain map for offline (Postgres) verification.
+ /// The live persons' expected documents, for offline (Postgres)
+ /// verification.
pub async fn snapshot(&self) -> HashMap<i64, ExpectedPerson> {
- let mut journal = self.inner.write().await;
- mem::take(&mut journal.persons)
+ let journal = self.inner.read().await;
+ journal
+ .persons
+ .iter()
+ .filter(|(&id, _)| journal.is_live(id))
+ .map(|(&id, node)| {
+ (
+ id,
+ ExpectedPerson {
+ written_properties: journal.fold(id).properties,
+ last_version: node.last_version,
+ },
+ )
+ })
+ .collect()
}
}
@@ -287,6 +683,17 @@ mod tests {
.collect()
}
+ /// A single-source merge with a `$set` and no `$set_once`.
+ fn merge(source: i64, survivor: i64, survivor_version: i64, set: &[(&str, &str)]) -> MergeAck {
+ MergeAck {
+ survivor,
+ survivor_version,
+ sources: vec![source],
+ set: props(set),
+ set_once: HashMap::new(),
+ }
+ }
+
#[test]
fn verify_properties_flags_exactly_the_missing_and_mismatched_keys() {
let expected = props(&[("a", "1"), ("b", "2")]);
@@ -481,4 +888,362 @@ mod tests {
// Unjournaled persons have nothing to verify against.
assert!(state.verify(2, &actual, 0).await.is_empty());
}
+
+ /// The fold rule the survivor's journal must mirror: the survivor
+ /// keeps every key it has, the source fills the rest, the merge
+ /// event's own $set overrides, and the folded version is claimed. A
+ /// journal that let the source overwrite the survivor's keys would
+ /// flag a correct stack. One that dropped the source's keys would
+ /// pass a fold that lost them.
+ #[tokio::test]
+ async fn a_merge_folds_the_source_into_the_survivor_target_wins() {
+ let state = PersonState::new();
+ state
+ .record_write(1, 3, props(&[("shared", "target"), ("t_only", "t")]))
+ .await;
+ state
+ .record_write(2, 7, props(&[("shared", "source"), ("s_only", "s")]))
+ .await;
+
+ state.mark_merge_pending(2).await;
+ assert!(state.is_merge_pending_or_merged(2).await);
+ state
+ .record_merge(merge(2, 1, 8, &[("harness_merge", "op")]))
+ .await;
+ assert!(state.take_anomalies().await.is_empty());
+ assert!(state.is_merge_pending_or_merged(2).await);
+
+ // The source no longer verifies as a live person. The survivor
+ // holds the folded document.
+ assert_eq!(state.person_ids().await, vec![1]);
+ assert_eq!(state.merged_source_ids().await, vec![2]);
+ let folded = json!({
+ "shared": "target", "t_only": "t", "s_only": "s", "harness_merge": "op"
+ });
+ assert!(state.verify(1, &folded, 8).await.is_empty());
+ assert!(state.verify(2, &json!({}), 0).await.is_empty());
+ assert_eq!(
+ violation_keys(
+ state
+ .verify(
+ 1,
+ &json!({"shared": "source", "t_only": "t", "harness_merge": "op"}),
+ 8
+ )
+ .await
+ ),
+ vec!["s_only", "shared"]
+ );
+ // The folded version is an ack of the survivor.
+ assert_eq!(
+ violation_keys(state.verify(1, &folded, 7).await),
+ vec!["__strong_read_version"]
+ );
+
+ let merged = state.snapshot_merged().await;
+ assert_eq!(merged[&2].survivor, 1);
+ assert_eq!(merged[&2].max_acked_version, 7);
+ }
+
+ /// A pre-seal source write can ack after the merge was journaled. It
+ /// is part of the sealed document, so it fills a key the survivor
+ /// lacks and replaces an older value the journal folded from the
+ /// source. It also raises the version the tombstone must sit above.
+ /// An errored source write taints the survivor's key.
+ #[tokio::test]
+ async fn late_source_acks_route_to_the_survivor() {
+ let state = PersonState::new();
+ state
+ .record_write(1, 3, props(&[("shared", "target")]))
+ .await;
+ state.record_write(2, 5, props(&[("a", "1")])).await;
+ state.record_merge(merge(2, 1, 6, &[])).await;
+
+ state
+ .record_write(
+ 2,
+ 6,
+ props(&[("shared", "late"), ("late", "v"), ("a", "2")]),
+ )
+ .await;
+ state
+ .record_write_no_change(2, props(&[("echo", "v")]))
+ .await;
+ state.record_write_uncertain(2, "lost").await;
+ assert!(state.take_anomalies().await.is_empty());
+
+ let survivor = json!({"shared": "target", "a": "2", "late": "v", "echo": "v"});
+ assert!(state.verify(1, &survivor, 6).await.is_empty());
+ assert_eq!(
+ violation_keys(
+ state
+ .verify(
+ 1,
+ &json!({"shared": "target", "a": "1", "late": "v", "echo": "v"}),
+ 6
+ )
+ .await
+ ),
+ vec!["a"]
+ );
+ // A later survivor ack for the tainted key restores coverage.
+ state.record_write(1, 9, props(&[("lost", "found")])).await;
+ assert_eq!(
+ violation_keys(state.verify(1, &survivor, 9).await),
+ vec!["lost"]
+ );
+
+ let merged = state.snapshot_merged().await;
+ assert_eq!(merged[&2].max_acked_version, 6);
+ }
+
+ /// A key the survivor can hold from an uncertain write is never
+ /// filled from the source, because the survivor wins every key it
+ /// actually has, known to the journal or not.
+ #[tokio::test]
+ async fn an_uncertain_survivor_key_is_not_filled_from_the_source() {
+ let state = PersonState::new();
+ state.record_write(1, 3, props(&[("k", "target")])).await;
+ state.record_write_uncertain(1, "k").await;
+ state.record_write(2, 5, props(&[("k", "source")])).await;
+ state.record_merge(merge(2, 1, 6, &[])).await;
+
+ // Either value is acceptable: the key is not asserted.
+ assert!(state.verify(1, &json!({"k": "target"}), 6).await.is_empty());
+ assert!(state.verify(1, &json!({"k": "source"}), 6).await.is_empty());
+
+ // The source's own uncertain key taints the survivor too.
+ let state = PersonState::new();
+ state.record_write(3, 2, props(&[("u", "s")])).await;
+ state.record_write_uncertain(3, "u").await;
+ state.record_merge(merge(3, 4, 3, &[])).await;
+ assert!(state.verify(4, &json!({}), 3).await.is_empty());
+ state.record_write(4, 4, props(&[("u", "t")])).await;
+ assert_eq!(
+ violation_keys(state.verify(4, &json!({}), 4).await),
+ vec!["u"]
+ );
+ }
+
+ /// Survivors merge on. A merge ack that names a merged survivor and
+ /// a late ack for the first source both land on the final person.
+ /// Each hop keeps the leader's precedence: a person's own keys beat
+ /// what merged into it.
+ #[tokio::test]
+ async fn merge_chains_resolve_to_the_final_survivor() {
+ let state = PersonState::new();
+ state.record_write(1, 1, props(&[("a", "1")])).await;
+ state.record_write(2, 1, props(&[("b", "2")])).await;
+ state.record_write(3, 1, props(&[("c", "3")])).await;
+ state.record_merge(merge(1, 2, 2, &[])).await;
+ state.record_merge(merge(2, 3, 2, &[])).await;
+ // Person 4 merged into 2 at 2's version 3, but the ack lands
+ // after 2's own merge did. 2's own keys beat 4's, the merge
+ // event's $set overrode 2's key, and 2's document entered 3.
+ state
+ .record_merge(merge(4, 2, 3, &[("d", "4"), ("b", "set-4")]))
+ .await;
+ state.record_write(1, 2, props(&[("late", "1")])).await;
+ state.record_write(3, 3, props(&[("own", "3")])).await;
+ assert!(state.take_anomalies().await.is_empty());
+
+ assert_eq!(state.person_ids().await, vec![3]);
+ let mut merged = state.merged_source_ids().await;
+ merged.sort_unstable();
+ assert_eq!(merged, vec![1, 2, 4]);
+ assert!(state
+ .verify(
+ 3,
+ &json!({"a": "1", "b": "set-4", "c": "3", "d": "4", "late": "1", "own": "3"}),
+ 3
+ )
+ .await
+ .is_empty());
+ assert_eq!(
+ violation_keys(state.verify(3, &json!({"c": "3"}), 3).await),
+ vec!["a", "b", "d", "late", "own"]
+ );
+ // The fold into 2 raised the version its tombstone must sit
+ // above.
+ assert_eq!(state.snapshot_merged().await[&2].max_acked_version, 3);
+
+ // A person cannot die twice, and a merge cannot survive itself.
+ state.record_merge(merge(1, 3, 4, &[])).await;
+ state.record_merge(merge(3, 1, 5, &[])).await;
+ assert_eq!(
+ violation_keys(state.take_anomalies().await),
+ vec!["__merged_twice", "__merged_twice"]
+ );
+ }
+
+ /// A target's own write for a key beats a fill from a source, in
+ /// either ack order. Before the fold the target held the key. After
+ /// the fold the target's write overwrote the fill.
+ #[tokio::test]
+ async fn a_late_own_ack_of_a_dead_target_beats_what_merged_into_it() {
+ let state = PersonState::new();
+ state.record_write(4, 1, props(&[("k", "from-4")])).await;
+ state.record_merge(merge(4, 2, 3, &[])).await;
+ state.record_merge(merge(2, 3, 2, &[])).await;
+ assert!(state.verify(3, &json!({"k": "from-4"}), 2).await.is_empty());
+
+ state.record_write(2, 2, props(&[("k", "own-2")])).await;
+ assert!(state.verify(3, &json!({"k": "own-2"}), 2).await.is_empty());
+ assert_eq!(
+ violation_keys(state.verify(3, &json!({"k": "from-4"}), 2).await),
+ vec!["k"]
+ );
+ assert!(state.take_anomalies().await.is_empty());
+ }
+
+ /// Two merges into one survivor can ack in the opposite order to
+ /// their folds. The earlier fold (lower survivor version) filled
+ /// the key, and the later fold found it present. A journal that
+ /// applied folds in ack order would expect the later source's value
+ /// and flag a correct stack.
+ #[tokio::test]
+ async fn folds_into_one_survivor_are_ordered_by_version_not_ack_arrival() {
+ let state = PersonState::new();
+ state.record_write(1, 1, props(&[("k", "first")])).await;
+ state.record_write(2, 1, props(&[("k", "second")])).await;
+ // Person 2's merge folded at survivor version 21. Person 1's
+ // folded at 18, but its ack lands second.
+ state.record_merge(merge(2, 3, 21, &[])).await;
+ state.record_merge(merge(1, 3, 18, &[])).await;
+ assert!(state.verify(3, &json!({"k": "first"}), 21).await.is_empty());
+ assert_eq!(
+ violation_keys(state.verify(3, &json!({"k": "second"}), 21).await),
+ vec!["k"]
+ );
+ // A late ack for the earlier source folds at its own version and
+ // still beats the later fold.
+ state.record_write(1, 2, props(&[("k2", "first")])).await;
+ state.record_write(2, 2, props(&[("k2", "second")])).await;
+ assert!(state
+ .verify(3, &json!({"k": "first", "k2": "first"}), 21)
+ .await
+ .is_empty());
+ // The survivor's own write wins over every fold, in any arrival
+ // order.
+ state.record_write(3, 22, props(&[("k", "own")])).await;
+ state.record_write(4, 1, props(&[("k", "late")])).await;
+ state.record_merge(merge(4, 3, 17, &[])).await;
+ assert!(state
+ .verify(3, &json!({"k": "own", "k2": "first"}), 22)
+ .await
+ .is_empty());
+ assert!(state.take_anomalies().await.is_empty());
+ }
+
+ /// Sources of one call fill in request order. The folded version is
+ /// claimed once per call.
+ #[tokio::test]
+ async fn sources_of_one_merge_fill_in_request_order() {
+ let state = PersonState::new();
+ state
+ .record_write(1, 1, props(&[("k", "first"), ("a", "1")]))
+ .await;
+ state
+ .record_write(2, 1, props(&[("k", "second"), ("b", "2")]))
+ .await;
+ state.record_write(3, 1, props(&[("k", "third")])).await;
+ state.record_write(9, 4, props(&[("t", "9")])).await;
+ state
+ .record_merge(MergeAck {
+ survivor: 9,
+ survivor_version: 5,
+ sources: vec![2, 1, 3],
+ set: props(&[("harness_merge", "op")]),
+ set_once: HashMap::new(),
+ })
+ .await;
+ assert!(state.take_anomalies().await.is_empty());
+ let mut merged = state.merged_source_ids().await;
+ merged.sort_unstable();
+ assert_eq!(merged, vec![1, 2, 3]);
+ assert!(state
+ .verify(
+ 9,
+ &json!({"t": "9", "k": "second", "a": "1", "b": "2", "harness_merge": "op"}),
+ 5
+ )
+ .await
+ .is_empty());
+ assert_eq!(
+ violation_keys(state.verify(9, &json!({"k": "first"}), 5).await),
+ vec!["a", "b", "harness_merge", "k", "t"]
+ );
+ }
+
+ /// `$set_once` fills only keys the fold left absent: not a key the
+ /// survivor or a source holds, not the same event's `$set` key, and
+ /// not an uncertain key.
+ #[tokio::test]
+ async fn merge_set_once_fills_only_absent_keys() {
+ let state = PersonState::new();
+ state
+ .record_write(1, 3, props(&[("own", "t"), ("raced", "t")]))
+ .await;
+ state.record_write_uncertain(1, "raced").await;
+ state.record_write(2, 5, props(&[("folded", "s")])).await;
+ state
+ .record_merge(MergeAck {
+ survivor: 1,
+ survivor_version: 6,
+ sources: vec![2],
+ set: props(&[("set", "set")]),
+ set_once: props(&[
+ ("own", "once"),
+ ("folded", "once"),
+ ("set", "once"),
+ ("raced", "once"),
+ ("fresh", "once"),
+ ]),
+ })
+ .await;
+ assert!(state.take_anomalies().await.is_empty());
+ let survivor = json!({"own": "t", "folded": "s", "set": "set", "fresh": "once"});
+ assert!(state.verify(1, &survivor, 6).await.is_empty());
+ assert!(state
+ .verify(
+ 1,
+ &json!({"own": "t", "folded": "s", "set": "set", "fresh": "once", "raced": "once"}),
+ 6
+ )
+ .await
+ .is_empty());
+ assert_eq!(
+ violation_keys(
+ state
+ .verify(
+ 1,
+ &json!({"own": "once", "folded": "once", "set": "once", "fresh": "once"}),
+ 6
+ )
+ .await
+ ),
+ vec!["folded", "own", "set"]
+ );
+ }
+
+ /// A merge that lost every response keeps its journal and stays
+ /// tolerated as absent until the op record settles it either way.
+ #[tokio::test]
+ async fn an_uncertain_merge_keeps_the_source_pending_until_settled() {
+ let state = PersonState::new();
+ state.record_write(1, 1, props(&[("a", "1")])).await;
+ state.mark_merge_pending(1).await;
+ state.record_merge_uncertain(1).await;
+ assert_eq!(state.person_ids().await, vec![1]);
+ assert_eq!(state.merge_uncertain_ids().await, vec![1]);
+ assert!(state.is_merge_pending_or_merged(1).await);
+ // Settled as merged: the late fold lands like any other.
+ state.record_merge(merge(1, 5, 3, &[])).await;
+ assert!(state.merge_uncertain_ids().await.is_empty());
+ assert!(state.verify(5, &json!({"a": "1"}), 3).await.is_empty());
+ // A call that settled without a merge releases the reservation.
+ state.mark_merge_pending(2).await;
+ state.clear_merge_pending(2).await;
+ assert!(!state.is_merge_pending_or_merged(2).await);
+ }
}
diff --git a/rust/personhog-test-harness/src/stats.rs b/rust/personhog-test-harness/src/stats.rs
index a69c07d92643..eda1c0adb87b 100644
--- a/rust/personhog-test-harness/src/stats.rs
+++ b/rust/personhog-test-harness/src/stats.rs
@@ -1,3 +1,4 @@
+use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
@@ -8,6 +9,10 @@ pub struct LatencyRecorder {
histogram: Mutex<Histogram<u64>>,
successes: AtomicU64,
failures: AtomicU64,
+ /// Writes refused because a lifecycle op fenced or destroyed the
+ /// person. Counted apart from failures, because a merge run expects
+ /// them.
+ lifecycle_rejections: AtomicU64,
start_time: Instant,
}
@@ -17,6 +22,7 @@ impl LatencyRecorder {
histogram: Mutex::new(Histogram::new_with_max(60_000_000, 3).unwrap()),
successes: AtomicU64::new(0),
failures: AtomicU64::new(0),
+ lifecycle_rejections: AtomicU64::new(0),
start_time: Instant::now(),
}
}
@@ -33,11 +39,16 @@ impl LatencyRecorder {
self.failures.fetch_add(1, Ordering::Relaxed);
}
+ pub fn record_lifecycle_rejection(&self) {
+ self.lifecycle_rejections.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 lifecycle_rejections = self.lifecycle_rejections.load(Ordering::Relaxed);
+ let total = successes + failures + lifecycle_rejections;
let elapsed = self.start_time.elapsed();
let throughput_rps = if elapsed.as_secs_f64() > 0.0 {
total as f64 / elapsed.as_secs_f64()
@@ -49,6 +60,7 @@ impl LatencyRecorder {
total,
successes,
failures,
+ lifecycle_rejections,
p50_us: h.value_at_quantile(0.50),
p95_us: h.value_at_quantile(0.95),
p99_us: h.value_at_quantile(0.99),
@@ -62,6 +74,7 @@ pub struct StatsSnapshot {
pub total: u64,
pub successes: u64,
pub failures: u64,
+ pub lifecycle_rejections: u64,
pub p50_us: u64,
pub p95_us: u64,
pub p99_us: u64,
@@ -72,6 +85,14 @@ pub struct StatsSnapshot {
pub struct StatsCollector {
pub writes: LatencyRecorder,
pub reads: LatencyRecorder,
+ /// MergePersons calls. One call is one saga, so its latency is the
+ /// full merge cost.
+ pub merges: LatencyRecorder,
+ /// Merge calls that involve a wide person. Kept apart so their cost
+ /// does not hide in the median.
+ pub wide_merges: LatencyRecorder,
+ /// Merge outcomes per source, by name.
+ merge_outcomes: Mutex<BTreeMap<&'static str, u64>>,
}
impl StatsCollector {
@@ -79,6 +100,22 @@ impl StatsCollector {
Self {
writes: LatencyRecorder::new(),
reads: LatencyRecorder::new(),
+ merges: LatencyRecorder::new(),
+ wide_merges: LatencyRecorder::new(),
+ merge_outcomes: Mutex::new(BTreeMap::new()),
}
}
+
+ pub fn record_merge_outcome(&self, outcome: &'static str) {
+ if let Ok(mut outcomes) = self.merge_outcomes.lock() {
+ *outcomes.entry(outcome).or_default() += 1;
+ }
+ }
+
+ pub fn merge_outcomes(&self) -> BTreeMap<&'static str, u64> {
+ self.merge_outcomes
+ .lock()
+ .map(|outcomes| outcomes.clone())
+ .unwrap_or_default()
+ }
}
diff --git a/rust/personhog-test-harness/src/verify.rs b/rust/personhog-test-harness/src/verify.rs
index b68d86154a07..993235e29f5e 100644
--- a/rust/personhog-test-harness/src/verify.rs
+++ b/rust/personhog-test-harness/src/verify.rs
@@ -11,7 +11,7 @@ use sqlx::Row;
use tokio::time::sleep;
use crate::report::ConsistencyViolation;
-use crate::state::{verify_properties, ExpectedPerson};
+use crate::state::{verify_properties, ExpectedPerson, MergedSource};
/// How long to wait for the writer to drain acked writes into Postgres
/// before declaring them lost.
@@ -20,15 +20,24 @@ pub const QUIESCE_DEADLINE: Duration = Duration::from_secs(60);
/// 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).
+///
+/// A merged source must be a tombstone: the row is deleted, and its
+/// version is above every version the leader acked for it. The fence is
+/// checked against the sealed version on the source's
+/// `lifecycle_op_person` row. An ack above the seal means a write got
+/// through the fence. The death version alone cannot show that, because
+/// the leader derives it from its current version too.
pub async fn verify_postgres(
pool: &PgPool,
table: &str,
team_id: i64,
journal: &HashMap<i64, ExpectedPerson>,
+ merged: &HashMap<i64, MergedSource>,
) -> 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() {
+ let merged_ids: Vec<i64> = merged.keys().copied().collect();
+ if person_ids.is_empty() && merged_ids.is_empty() {
return Ok(Vec::new());
}
@@ -36,6 +45,25 @@ pub async fn verify_postgres(
"SELECT id, properties::text AS properties, version \
FROM {table} WHERE team_id = $1 AND id = ANY($2)"
);
+ let tombstone_query =
+ format!("SELECT id, is_deleted, version FROM {table} WHERE team_id = $1 AND id = ANY($2)");
+ // A mapping left on a tombstone resolves events to a person that no
+ // longer exists.
+ let leftover_dids_query = crate::seed::distinct_id_tables_for(table)
+ .iter()
+ .map(|pdi_table| {
+ format!(
+ "SELECT person_id, count(*) AS n FROM {pdi_table} \
+ WHERE team_id = $1 AND person_id = ANY($2) GROUP BY person_id"
+ )
+ })
+ .collect::<Vec<_>>();
+ // The saga records each source's seal on its op row and sets the
+ // row's status to deleted after the flip.
+ let sealed_query = "SELECT person_id, (sealed->>'version')::bigint AS sealed_version \
+ FROM lifecycle_op_person \
+ WHERE team_id = $1 AND role = 'source' AND status = 'deleted' \
+ AND person_id = ANY($2)";
let deadline = Instant::now() + QUIESCE_DEADLINE;
loop {
let rows = sqlx::query(&query)
@@ -94,6 +122,62 @@ pub async fn verify_postgres(
}
}
+ if !merged_ids.is_empty() {
+ let rows = sqlx::query(&tombstone_query)
+ .bind(team)
+ .bind(&merged_ids)
+ .fetch_all(pool)
+ .await
+ .context("reading merged sources from Postgres")?;
+ let mut tombstones: HashMap<i64, (bool, i64)> = HashMap::new();
+ for row in rows {
+ let id: i64 = row.get("id");
+ let is_deleted: bool = row.get("is_deleted");
+ let version: Option<i64> = row.get("version");
+ tombstones.insert(id, (is_deleted, version.unwrap_or(0)));
+ }
+ let mut seals: HashMap<i64, i64> = HashMap::new();
+ for row in sqlx::query(sealed_query)
+ .bind(team)
+ .bind(&merged_ids)
+ .fetch_all(pool)
+ .await
+ .context("reading merge seals from lifecycle_op_person")?
+ {
+ let person_id: i64 = row.get("person_id");
+ let sealed_version: Option<i64> = row.get("sealed_version");
+ if let Some(sealed_version) = sealed_version {
+ seals.insert(person_id, sealed_version);
+ }
+ }
+ for (person_id, source) in merged {
+ violations.extend(verify_tombstone(
+ *person_id,
+ source,
+ tombstones.get(person_id).copied(),
+ seals.get(person_id).copied(),
+ ));
+ }
+ for query in &leftover_dids_query {
+ for row in sqlx::query(query)
+ .bind(team)
+ .bind(&merged_ids)
+ .fetch_all(pool)
+ .await
+ .context("counting distinct ids left on merged sources")?
+ {
+ let person_id: i64 = row.get("person_id");
+ let n: i64 = row.get("n");
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_dids_left".to_string(),
+ expected: json!("every mapping repointed to the survivor"),
+ actual: json!(n),
+ });
+ }
+ }
+ }
+
if violations.is_empty() {
return Ok(violations);
}
@@ -107,3 +191,104 @@ pub async fn verify_postgres(
sleep(Duration::from_millis(500)).await;
}
}
+
+/// The decision table for a merged source's row. `row` is
+/// `(is_deleted, version)`, or None when the row is gone. `sealed` is
+/// the version the saga recorded at the fence, or None when the op row
+/// is missing.
+pub fn verify_tombstone(
+ person_id: i64,
+ source: &MergedSource,
+ row: Option<(bool, i64)>,
+ sealed: Option<i64>,
+) -> Vec<ConsistencyViolation> {
+ let Some((is_deleted, version)) = row else {
+ return vec![ConsistencyViolation {
+ person_id,
+ key: "__merged_source_row".to_string(),
+ expected: json!(format!(
+ "tombstone present (merged into {})",
+ source.survivor
+ )),
+ actual: Value::Null,
+ }];
+ };
+ let mut violations = Vec::new();
+ if !is_deleted {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_tombstone".to_string(),
+ expected: json!("is_deleted"),
+ actual: json!(false),
+ });
+ }
+ if version <= source.max_acked_version {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_death_version".to_string(),
+ expected: json!(format!("> {} (highest acked)", source.max_acked_version)),
+ actual: json!(version),
+ });
+ }
+ match sealed {
+ Some(sealed) if sealed < source.max_acked_version => {
+ violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_ack_above_seal".to_string(),
+ expected: json!(format!("no acked version above seal {sealed}")),
+ actual: json!(source.max_acked_version),
+ });
+ }
+ Some(_) => {}
+ None => violations.push(ConsistencyViolation {
+ person_id,
+ key: "__merged_source_seal_record".to_string(),
+ expected: json!("a deleted source row on the merge op"),
+ actual: Value::Null,
+ }),
+ }
+ violations
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn keys(violations: Vec<ConsistencyViolation>) -> Vec<String> {
+ violations.into_iter().map(|v| v.key).collect()
+ }
+
+ #[test]
+ fn tombstone_decision_table() {
+ let source = MergedSource::for_test(2, 7);
+ assert!(verify_tombstone(1, &source, Some((true, 8)), Some(7)).is_empty());
+ assert!(verify_tombstone(1, &source, Some((true, 20)), Some(9)).is_empty());
+ assert_eq!(
+ keys(verify_tombstone(1, &source, None, Some(7))),
+ vec!["__merged_source_row"]
+ );
+ assert_eq!(
+ keys(verify_tombstone(1, &source, Some((false, 8)), Some(7))),
+ vec!["__merged_source_tombstone"]
+ );
+ // Death at the highest acked version: that ack sat above the seal.
+ assert_eq!(
+ keys(verify_tombstone(1, &source, Some((true, 7)), Some(7))),
+ vec!["__merged_source_death_version"]
+ );
+ assert_eq!(
+ keys(verify_tombstone(1, &source, Some((false, 3)), Some(7))),
+ vec!["__merged_source_tombstone", "__merged_source_death_version"]
+ );
+ // The fence failed open: the ack sits above the recorded seal,
+ // but the death version cleared it.
+ assert_eq!(
+ keys(verify_tombstone(1, &source, Some((true, 20)), Some(6))),
+ vec!["__merged_source_ack_above_seal"]
+ );
+ assert_eq!(
+ keys(verify_tombstone(1, &source, Some((true, 8)), None)),
+ vec!["__merged_source_seal_record"]
+ );
+ }
+}