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.

fix(personhog): serve revived persons after destruction (#96995)

Zach Brown0d8b4eec274c
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 8b6d0be85efc..a05ca2935cc4 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -339,11 +339,15 @@ impl Engine {
if claim_attempt.is_some() {
// A stolen lease double-counts alongside the stealer;
// exact attribution would cost a query per completion.
+ // Call-driven completions raced ahead of the sweeper;
+ // a growing sweeper share means ops are being abandoned.
+ let driver_kind = if wait_for_lease { "call" } else { "sweeper" };
common_metrics::inc(
OPS_COMPLETED_TOTAL,
&[
("op_type".to_string(), row.op_type.clone()),
("final_step".to_string(), row.step.clone()),
+ ("driver".to_string(), driver_kind.to_string()),
],
1,
);
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 6ac1c1232b17..810aafb9d8cf 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -239,6 +239,29 @@ pub(crate) fn record_outcome_count(outcome: &str, count: u64) {
);
}
+/// Unsettled (skipped_conflict) verdicts by the check that produced them.
+const CONFLICTS_TOTAL: &str = "personhog_identity_merge_conflicts_total";
+
+/// Emit accumulated conflict reasons; called only after the recording
+/// transaction commits, so rollbacks and step re-runs never count.
+fn record_conflicts(conflicts: Vec<(&'static str, u64)>) {
+ for (reason, count) in conflicts {
+ record_conflict(reason, count);
+ }
+}
+
+/// Attribute each conflict verdict, so an unsettled spike reads as live
+/// contention, concurrent remaps, or vanished persons.
+pub(crate) fn record_conflict(reason: &str, count: u64) {
+ if count > 0 {
+ common_metrics::inc(
+ CONFLICTS_TOTAL,
+ &[("reason".to_string(), reason.to_string())],
+ count,
+ );
+ }
+}
+
fn record_outcomes(outcome: &Value) {
let Ok(parsed) = serde_json::from_value::<MergeOutcome>(outcome.clone()) else {
return;
@@ -486,6 +509,7 @@ fn reconcile_pending_claims(
claim_persons: &[(i64, Uuid, i32)],
marked: &[i64],
fresh: &HashMap<String, Resolution>,
+ conflicts: &mut Vec<(&'static str, u64)>,
) -> Vec<i64> {
for d in dispositions.iter_mut() {
if d.decision != DECISION_PENDING_MERGE {
@@ -501,6 +525,7 @@ fn reconcile_pending_claims(
.get(&d.distinct_id)
.is_none_or(|r| r.person_id != person_id)
{
+ conflicts.push(("remapped_after_claim", 1));
d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
}
}
@@ -562,6 +587,8 @@ impl MergeDriver {
async fn claim(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
+ // Conflict reasons emit only after a commit (see record_conflicts).
+ let mut conflicts: Vec<(&'static str, u64)> = Vec::new();
let mut tx = pool.begin().await?;
// Authoritative resolution: the handler's classification aged while
@@ -577,7 +604,7 @@ impl MergeDriver {
// The target person vanished between classification and now. The
// caller's re-drive (new op) re-classifies; this op has changed
// nothing.
- let dispositions = request
+ let dispositions: Vec<Disposition> = request
.sources
.iter()
.map(|s| Disposition {
@@ -586,7 +613,8 @@ impl MergeDriver {
decision: OUTCOME_SKIPPED_CONFLICT.to_string(),
})
.collect();
- return abort_in_claim_tx(tx, op, dispositions).await;
+ conflicts.push(("target_vanished", dispositions.len() as u64));
+ return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
};
let (target_person_id, target_person_uuid) = (target.person_id, target.person_uuid);
@@ -599,6 +627,7 @@ impl MergeDriver {
let Some(resolution) = resolved.get(&source.distinct_id) else {
// Consumed by another lifecycle op (or never existed): a
// retryable signal — the caller's re-drive re-classifies it.
+ conflicts.push(("source_consumed", 1));
dispositions.push(Disposition {
distinct_id: source.distinct_id.clone(),
person_id: None,
@@ -728,12 +757,15 @@ impl MergeDriver {
)
.execute(&mut *tx)
.await?;
+ let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE {
d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
+ converted += 1;
}
}
- return abort_in_claim_tx(tx, op, dispositions).await;
+ conflicts.push(("target_marked", converted));
+ return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
}
// Sources another live op holds: record the skip (the status keeps
@@ -763,13 +795,16 @@ impl MergeDriver {
)
.execute(&mut *tx)
.await?;
+ let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE
&& d.person_id.is_some_and(|id| conflicted_ids.contains(&id))
{
d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
+ converted += 1;
}
}
+ conflicts.push(("source_marked", converted));
}
// Post-insert liveness recheck. The resolve above and the insert run
@@ -792,14 +827,23 @@ impl MergeDriver {
)
.execute(&mut *tx)
.await?;
+ let mut converted = 0;
for d in dispositions.iter_mut() {
if d.decision == DECISION_PENDING_MERGE {
d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
+ converted += 1;
}
}
- return abort_in_claim_tx(tx, op, dispositions).await;
+ conflicts.push(("target_vanished", converted));
+ return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
}
- let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &marked, &fresh);
+ let dropped = reconcile_pending_claims(
+ &mut dispositions,
+ &claim_persons,
+ &marked,
+ &fresh,
+ &mut conflicts,
+ );
if !dropped.is_empty() {
sqlx::query!(
r#"
@@ -833,7 +877,7 @@ impl MergeDriver {
)
.execute(&mut *tx)
.await?;
- return abort_in_claim_tx(tx, op, dispositions).await;
+ return abort_in_claim_tx(tx, op, dispositions, conflicts).await;
}
// Persist the claim record on the target row; the terminal outcome
@@ -862,6 +906,7 @@ impl MergeDriver {
return Ok(());
}
tx.commit().await?;
+ record_conflicts(conflicts);
record_transition(MergeStep::Started.as_str(), MergeStep::Claimed.as_str());
Ok(())
}
@@ -874,6 +919,7 @@ async fn abort_in_claim_tx(
mut tx: Tx<'_>,
op: &OpRow,
dispositions: Vec<Disposition>,
+ conflicts: Vec<(&'static str, u64)>,
) -> Result<(), SagaError> {
let mut outcome = outcome_from_dispositions(
&dispositions,
@@ -897,6 +943,7 @@ async fn abort_in_claim_tx(
return Ok(());
}
tx.commit().await?;
+ record_conflicts(conflicts);
record_transition(MergeStep::Started.as_str(), STEP_ABORTED);
record_outcomes(&outcome);
Ok(())
@@ -1969,7 +2016,13 @@ mod tests {
("d2".to_string(), resolution(9)),
]);
- let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &[7], &fresh);
+ let dropped = reconcile_pending_claims(
+ &mut dispositions,
+ &claim_persons,
+ &[7],
+ &fresh,
+ &mut Vec::new(),
+ );
assert!(dropped.is_empty(), "person 7 is still reachable via d1");
assert_eq!(dispositions[0].decision, DECISION_PENDING_MERGE);
@@ -1988,7 +2041,13 @@ mod tests {
("d2".to_string(), resolution(9)),
]);
- let dropped = reconcile_pending_claims(&mut dispositions, &claim_persons, &[7], &fresh);
+ let dropped = reconcile_pending_claims(
+ &mut dispositions,
+ &claim_persons,
+ &[7],
+ &fresh,
+ &mut Vec::new(),
+ );
assert_eq!(dropped, vec![7]);
for d in &dispositions {
diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rs
index 885211c87c32..faefaaefee8a 100644
--- a/rust/personhog-identity/src/service/merge.rs
+++ b/rust/personhog-identity/src/service/merge.rs
@@ -22,10 +22,10 @@ use personhog_proto::personhog::types::v1::{Person as ProtoPerson, UpdatePersonP
use crate::leader::PropertyWriter;
use crate::lifecycle::engine::OpRow;
use crate::lifecycle::merge::{
- record_outcome_count, MergeOpExecutor, MergeOutcome, MergeRequest, MergeSourceEntry,
- MergeSourceRecord, OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON,
- OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_MOVE_LIMIT,
- OUTCOME_SKIPPED_REFUSED,
+ record_conflict, record_outcome_count, MergeOpExecutor, MergeOutcome, MergeRequest,
+ MergeSourceEntry, MergeSourceRecord, OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED,
+ OUTCOME_NOOP_SAME_PERSON, OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT,
+ OUTCOME_SKIPPED_MOVE_LIMIT, OUTCOME_SKIPPED_REFUSED,
};
use crate::lifecycle::validation::{
is_distinct_id_illegal, is_distinct_id_oversized, validate_merge_persons,
@@ -193,7 +193,10 @@ impl MergeEntrance {
{
OUTCOME_ATTACHED
}
- Some(AttachOutcome::AlreadyMapped { .. }) | None => OUTCOME_SKIPPED_CONFLICT,
+ Some(AttachOutcome::AlreadyMapped { .. }) | None => {
+ record_conflict("attach_race", 1);
+ OUTCOME_SKIPPED_CONFLICT
+ }
};
inline_results.insert(did, outcome.to_string());
}
diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rs
index 1732988694b0..624746bf8239 100644
--- a/rust/personhog-identity/src/storage/postgres/attach.rs
+++ b/rust/personhog-identity/src/storage/postgres/attach.rs
@@ -55,11 +55,12 @@ pub(super) async fn attach_distinct_ids(
pdi = tables.person_distinct_id,
person = tables.person,
);
+ let mut conn = super::acquire_timed(pool).await?;
let written = sqlx::query(&insert_sql)
.bind(&sorted)
.bind(person_id)
.bind(team_id as i32)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut outcomes: HashMap<String, AttachOutcome> = HashMap::new();
@@ -90,7 +91,7 @@ pub(super) async fn attach_distinct_ids(
let rows = sqlx::query(&losers_sql)
.bind(team_id as i32)
.bind(&losers)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
for row in rows {
let distinct_id: String = row.try_get("distinct_id")?;
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index 76a1bdf22e26..b8dabe1b58d1 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -8,10 +8,12 @@ mod resolve;
mod stub_create;
use std::collections::HashMap;
+use std::time::Instant;
use async_trait::async_trait;
+use sqlx::pool::PoolConnection;
use sqlx::postgres::{PgPool, PgRow};
-use sqlx::Row;
+use sqlx::{Postgres, Row, Transaction};
use personhog_common::grpc::{current_client_name, current_method_name};
@@ -22,6 +24,38 @@ use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
const POOL_LABEL: &str = "primary";
+/// Wait for a pool connection. Connection churn shows up here while
+/// every other layer reads idle.
+const DB_POOL_ACQUIRE_DURATION: &str = "personhog_identity_db_pool_acquire_duration_ms";
+
+fn record_acquire(start: Instant) {
+ common_metrics::histogram(
+ DB_POOL_ACQUIRE_DURATION,
+ &[
+ ("pool".to_string(), POOL_LABEL.to_string()),
+ ("client".to_string(), current_client_name().to_string()),
+ ("method".to_string(), current_method_name().to_string()),
+ ],
+ start.elapsed().as_secs_f64() * 1000.0,
+ );
+}
+
+/// Acquire a primary connection, recording the wait.
+pub(super) async fn acquire_timed(pool: &PgPool) -> sqlx::Result<PoolConnection<Postgres>> {
+ let start = Instant::now();
+ let conn = pool.acquire().await;
+ record_acquire(start);
+ conn
+}
+
+/// Begin a primary transaction, recording the acquire wait it contains.
+pub(super) async fn begin_timed(pool: &PgPool) -> sqlx::Result<Transaction<'_, Postgres>> {
+ let start = Instant::now();
+ let tx = pool.begin().await;
+ record_acquire(start);
+ tx
+}
+
/// Decode a person from a row whose SELECT list uses the canonical aliases
/// (`team_id::bigint AS team_id`, `properties::text AS properties`, the
/// `is_user_id` boolean CASE, …). Shared by every submodule that selects
diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rs
index 0e68bd785edf..6c78e2346df0 100644
--- a/rust/personhog-identity/src/storage/postgres/resolve.rs
+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs
@@ -39,10 +39,11 @@ pub(super) async fn resolve_distinct_ids(
pdi_table = tables.person_distinct_id,
person_table = tables.person,
);
+ let mut conn = super::acquire_timed(pool).await?;
let rows = sqlx::query(&sql)
.bind(&team_ids)
.bind(&distinct_ids)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut resolved = HashMap::with_capacity(rows.len());
diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rs
index 0b22682b1688..99d0ccedc453 100644
--- a/rust/personhog-identity/src/storage/postgres/stub_create.rs
+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs
@@ -83,7 +83,7 @@ pub(super) async fn create_person_stubs(
.collect();
let team_ids: Vec<i32> = stubs.iter().map(|s| s.team_id as i32).collect();
- let mut tx = pool.begin().await?;
+ let mut tx = super::begin_timed(pool).await?;
let mut persons =
insert_or_revive_persons(&mut tx, &tables.person, stubs, &team_ids, &uuids).await?;
@@ -113,7 +113,9 @@ pub(super) async fn create_person_stubs(
/// A conflict with a tombstoned row (same uuidv5 key, previously deleted) is
/// a revival: flip is_deleted, bump the version above the tombstone so
/// ClickHouse collapses toward the new incarnation, and reset properties.
-/// Conflicts with live rows fail the WHERE qual and return nothing here.
+/// A tombstone under a live lifecycle mark stays dead — its saga may still
+/// re-drive a release over the revival; the caller sees LostRace and
+/// retries. Conflicts with live rows fail the qual and return nothing.
///
/// A returned version of 0 means fresh insert, anything else means revival
/// (xmax can't be read back from a partitioned table).
@@ -154,6 +156,12 @@ async fn insert_or_revive_persons(
is_identified = EXCLUDED.is_identified,
last_seen_at = EXCLUDED.last_seen_at
WHERE {person_table}.is_deleted = true
+ AND NOT EXISTS (
+ SELECT 1 FROM lifecycle_op_person lop
+ WHERE lop.team_id = {person_table}.team_id
+ AND lop.person_id = {person_table}.id
+ AND lop.status IN ('marked', 'sealed')
+ )
RETURNING {person_cols}
"#,
person_cols = person_columns(person_table),
diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rs
index 8ff8c53bc9ad..b008320ccc06 100644
--- a/rust/personhog-identity/tests/storage_tests.rs
+++ b/rust/personhog-identity/tests/storage_tests.rs
@@ -564,6 +564,86 @@ async fn deleted_person_is_revived_above_the_tombstone_on_recreate() {
ctx.cleanup().await.ok();
}
+/// A tombstone under a live lifecycle mark refuses revival (LostRace);
+/// once the mark finishes, the recreate revives normally.
+#[tokio::test]
+async fn a_tombstone_under_a_live_lifecycle_mark_does_not_revive() {
+ let ctx = TestContext::new().await;
+
+ let first = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "marked-dead", &[])])
+ .await
+ .expect("first create should succeed");
+ let [StubOutcome::Committed { person, .. }] = &first[..] else {
+ panic!("expected committed outcome");
+ };
+ let person_id = person.id;
+
+ ctx.tombstone_person(person_id, 7).await;
+ ctx.tombstone_distinct_id("marked-dead", 3).await;
+ let op = uuid::Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .execute(&ctx.pool)
+ .await
+ .expect("insert mark");
+
+ let refused = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "marked-dead", &[])])
+ .await
+ .expect("create should succeed");
+ assert!(
+ matches!(refused[..], [StubOutcome::LostRace]),
+ "a live mark refuses revival, got {refused:?}"
+ );
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(&[(ctx.team_id, "marked-dead".to_string())])
+ .await
+ .expect("resolve should succeed");
+ assert!(resolved.is_empty(), "the tombstone stays tombstoned");
+
+ // The saga finished; the mark is no longer live.
+ sqlx::query("UPDATE lifecycle_op_person SET status = 'deleted' WHERE op_id = $1")
+ .bind(op)
+ .execute(&ctx.pool)
+ .await
+ .expect("finish mark");
+ let second = ctx
+ .storage
+ .create_person_stubs(&[stub(&ctx, "marked-dead", &[])])
+ .await
+ .expect("recreate should succeed");
+ let [StubOutcome::Committed { person, created }] = &second[..] else {
+ panic!("expected committed outcome, got {second:?}");
+ };
+ assert!(created);
+ assert_eq!(person.id, person_id, "revival keeps the row");
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&ctx.pool)
+ .await
+ .ok();
+ ctx.cleanup().await.ok();
+}
+
/// A revived stub that loses the mapping race must be re-tombstoned, not
/// hard-deleted: the tombstones predate this transaction and deleting them
/// would reopen the version-0-resurrection hole for the next recreate.
diff --git a/rust/personhog-leader/README.md b/rust/personhog-leader/README.md
index 01dd80b73d7a..9d7a25446c57 100644
--- a/rust/personhog-leader/README.md
+++ b/rust/personhog-leader/README.md
@@ -80,6 +80,9 @@ TBD:
- this offset is the boundary:
- below the offset: state is durably in Postgres
- at or above the offset: state is PG + the changes in our distributed log (the kafka topic)
+- death documents (tombstoned persons) stay cached only while their record awaits the writer: once the committed offset passes it, the prune drops the document and reads fall through to Postgres, which then holds the tombstone or a revival that superseded it
+- a revival therefore becomes visible at most one prune tick after the writer applies its tombstone
+- warming leaves no residue for an applied death record — neither the document (unmarked, it would answer not-found forever) nor its earlier records for the same key
#### Admission
diff --git a/rust/personhog-leader/src/cache/dirty_index.rs b/rust/personhog-leader/src/cache/dirty_index.rs
index d9f04ee583e3..431530fb090d 100644
--- a/rust/personhog-leader/src/cache/dirty_index.rs
+++ b/rust/personhog-leader/src/cache/dirty_index.rs
@@ -1,4 +1,4 @@
-use std::collections::{HashMap, VecDeque};
+use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -27,14 +27,24 @@ pub struct DirtyMark {
/// The person's routing partition, denormalized so pruning can work
/// per partition without rehashing keys.
pub partition: u32,
+ /// Whether the marked record is a death document. The prune returns
+ /// only these pairs, so the settle never touches live persons' keys.
+ pub is_deleted: bool,
+}
+
+/// What a prune pass reclaimed: the count drives shrinking and metrics;
+/// the death pairs go to the settle.
+pub struct PrunedMarks {
+ pub removed: usize,
+ pub death_marks: Vec<(PersonCacheKey, DirtyMark)>,
}
/// A partition's reclaim queue: `(offset, key)` entries in rough offset
/// order, popped from the head as the writer's committed offset passes them.
type ReclaimQueue = Arc<Mutex<VecDeque<(i64, PersonCacheKey)>>>;
-/// Maximum queue pops per prune lock hold (see `prune_partition`).
-const PRUNE_CHUNK: usize = 4_096;
+/// Maximum queue pops per prune lock hold (see `prune_chunk`).
+pub const PRUNE_CHUNK: usize = 4_096;
/// Containers below this capacity are never shrunk — the retained memory
/// is a few hundred KB at most, not worth the churn.
@@ -171,20 +181,6 @@ impl DirtyIndex {
self.map.get(key).map(|entry| *entry.value())
}
- /// Drop every mark the writer has applied, across all partitions: a
- /// mark is applied once its partition's committed offset (absent = no
- /// commit yet) has moved past it. Returns how many were pruned.
- pub fn prune_applied(&self, committed: &HashMap<u32, i64>) -> usize {
- let removed = committed
- .iter()
- .map(|(partition, committed)| self.prune_partition(*partition, *committed))
- .sum();
- if removed > 0 {
- self.maybe_shrink_map();
- }
- removed
- }
-
/// Return the map's spare capacity to the allocator. Removal never
/// shrinks it, so a catch-up after a deep outage would otherwise pin
/// the backlog's worst-case footprint forever; capacity only becomes
@@ -200,67 +196,39 @@ impl DirtyIndex {
}
}
- /// Drop marks on `partition` that the writer has applied (offset below
- /// its committed offset). Pops the reclaim queue only while its head
- /// is applied, so the cost is proportional to the marks reclaimed.
- /// The pass releases the queue lock every `PRUNE_CHUNK` pops: a
- /// catch-up after a long writer outage reclaims millions of marks in
- /// one call, and an unbroken hold would stall every new-key `mark` —
- /// the write hot path — for the whole pass. Between chunks the queue
- /// is re-fetched, so a concurrent `clear_partition` (which detaches
- /// it) ends the pass instead of racing the drain. Returns how many
- /// were pruned.
- pub fn prune_partition(&self, partition: u32, committed: i64) -> usize {
- let mut removed = 0;
- loop {
- let (chunk_removed, exhausted) = self.prune_chunk(partition, committed);
- removed += chunk_removed;
- if exhausted {
- break;
- }
- }
- // A queue never shrinks on pop, so after a catch-up it would pin
- // its backlog-peak buffer until the partition is released.
- if removed > 0 {
- if let Some(queue) = self
- .queues
- .get(&partition)
- .map(|entry| Arc::clone(entry.value()))
- {
- let mut queue = queue.lock().expect("dirty index queue lock poisoned");
- if queue.capacity() > SHRINK_CAPACITY_FLOOR && queue.len() * 4 < queue.capacity() {
- queue.shrink_to_fit();
- }
- }
- }
- removed
- }
-
- /// One bounded slice of a prune pass: re-fetch the queue, hold its
- /// lock for at most `PRUNE_CHUNK` pops, and report how many marks
- /// were removed plus whether the pass is exhausted. Exhaustion means
- /// the head is unapplied, the queue is empty, or the queue was
- /// detached by a concurrent `clear_partition` — the re-fetch is what
- /// lets a release end an in-flight pass instead of racing its drain.
- fn prune_chunk(&self, partition: u32, committed: i64) -> (usize, bool) {
+ /// One bounded prune slice: hold the queue lock for at most
+ /// `PRUNE_CHUNK` pops, remove the applied marks (offset below the
+ /// committed offset), and return the death pairs for the caller to
+ /// settle before the next slice — that keeps a catch-up's memory and
+ /// lock exposure flat, and lets `mark` (the write hot path) breathe
+ /// between slices. Exhausted means the head is unapplied, the queue
+ /// is empty, or it was detached by a concurrent `clear_partition` —
+ /// the re-fetch is what lets a release end an in-flight pass instead
+ /// of racing its drain.
+ pub fn prune_chunk(&self, partition: u32, committed: i64) -> (PrunedMarks, bool) {
+ let mut pruned = PrunedMarks {
+ removed: 0,
+ death_marks: Vec::new(),
+ };
let Some(queue) = self
.queues
.get(&partition)
.map(|entry| Arc::clone(entry.value()))
else {
- return (0, true);
+ return (pruned, true);
};
let mut queue = queue.lock().expect("dirty index queue lock poisoned");
let mut removed = 0;
let mut budget = PRUNE_CHUNK;
+ let mut exhausted = false;
while budget > 0 {
let Some(&(offset, _)) = queue.front() else {
- self.size.fetch_sub(removed, Ordering::Relaxed);
- return (removed, true);
+ exhausted = true;
+ break;
};
if offset >= committed {
- self.size.fetch_sub(removed, Ordering::Relaxed);
- return (removed, true);
+ exhausted = true;
+ break;
}
budget -= 1;
let (_, key) = queue.pop_front().expect("front was just observed");
@@ -268,12 +236,12 @@ impl DirtyIndex {
// lock: between the pop and here the key may have been
// re-marked, and removing the newer mark would silently
// reopen the stale-fallback hole.
- if self
- .map
- .remove_if(&key, |_, mark| mark.offset < committed)
- .is_some()
- {
+ if let Some(entry) = self.map.remove_if(&key, |_, mark| mark.offset < committed) {
removed += 1;
+ pruned.removed += 1;
+ if entry.1.is_deleted {
+ pruned.death_marks.push(entry);
+ }
} else if let Some(mark) = self.map.get(&key) {
// Superseded: the live mark is ahead of the committed
// offset, and the entry just popped was this key's only
@@ -289,7 +257,17 @@ impl DirtyIndex {
}
}
self.size.fetch_sub(removed, Ordering::Relaxed);
- (removed, false)
+ if exhausted {
+ // A queue never shrinks on pop; reclaim after a catch-up.
+ if queue.capacity() > SHRINK_CAPACITY_FLOOR && queue.len() * 4 < queue.capacity() {
+ queue.shrink_to_fit();
+ }
+ }
+ drop(queue);
+ if exhausted {
+ self.maybe_shrink_map();
+ }
+ (pruned, exhausted)
}
/// Drop every mark on `partition` — used when the partition is released
@@ -307,7 +285,7 @@ impl DirtyIndex {
}
}
self.size.fetch_sub(removed, Ordering::Relaxed);
- // Releases bypass prune_applied, so a released backlog's map
+ // Releases bypass the prune, so a released backlog's map
// capacity would otherwise stay pinned until some future prune.
if removed > 0 {
self.maybe_shrink_map();
@@ -378,6 +356,29 @@ mod tests {
version: offset,
offset,
partition,
+ is_deleted: false,
+ }
+ }
+
+ fn death_mark(offset: i64, partition: u32) -> DirtyMark {
+ DirtyMark {
+ is_deleted: true,
+ ..mark(offset, partition)
+ }
+ }
+
+ fn prune_all(index: &DirtyIndex, partition: u32, committed: i64) -> PrunedMarks {
+ let mut total = PrunedMarks {
+ removed: 0,
+ death_marks: Vec::new(),
+ };
+ loop {
+ let (pruned, exhausted) = index.prune_chunk(partition, committed);
+ total.removed += pruned.removed;
+ total.death_marks.extend(pruned.death_marks);
+ if exhausted {
+ return total;
+ }
}
}
@@ -397,7 +398,7 @@ mod tests {
assert_eq!(index.len(), 2);
// Pruning frees admission again.
- index.prune_partition(0, 100);
+ prune_all(&index, 0, 100);
assert!(index.can_admit(&key(3)));
}
@@ -415,17 +416,27 @@ mod tests {
#[test]
fn prune_removes_applied_marks_and_keeps_the_boundary() {
let index = DirtyIndex::new(1_000);
- index.mark(key(1), mark(4, 0));
+ index.mark(key(1), death_mark(4, 0));
index.mark(key(2), mark(5, 0));
index.mark(key(3), mark(6, 0));
// Committed offset 5 means the record at 4 is applied; the record
// at 5 is not yet.
- let pruned = index.prune_partition(0, 5);
- assert_eq!(pruned, 1);
+ let pruned = prune_all(&index, 0, 5);
+ assert_eq!(pruned.removed, 1);
+ // The death pair carries the removed key and its mark, so the
+ // settle acts on exactly what was pruned.
+ assert_eq!(pruned.death_marks.len(), 1);
+ assert_eq!(pruned.death_marks[0].0, key(1));
+ assert_eq!(pruned.death_marks[0].1.offset, 4);
assert!(index.get(&key(1)).is_none());
assert!(index.get(&key(2)).is_some());
assert!(index.get(&key(3)).is_some());
+
+ // A pruned live mark counts but yields no death pair.
+ let pruned = prune_all(&index, 0, 6);
+ assert_eq!(pruned.removed, 1);
+ assert!(pruned.death_marks.is_empty());
}
#[test]
@@ -436,12 +447,12 @@ mod tests {
// The stale queue entry at offset 1 is popped, but the live mark
// is ahead of the committed offset and must survive.
- assert_eq!(index.prune_partition(0, 3), 0);
+ assert_eq!(prune_all(&index, 0, 3).removed, 0);
assert_eq!(index.get(&key(1)).unwrap().offset, 5);
// The re-enqueued entry keeps the key reclaimable once the writer
// catches up — a dropped entry would leak the mark forever.
- assert_eq!(index.prune_partition(0, 6), 1);
+ assert_eq!(prune_all(&index, 0, 6).removed, 1);
assert!(index.get(&key(1)).is_none());
assert_eq!(index.len(), 0);
}
@@ -455,8 +466,8 @@ mod tests {
index.mark(key(1), mark(10, 0));
index.mark(key(2), mark(9, 0));
- assert_eq!(index.prune_partition(0, 10), 0);
- assert_eq!(index.prune_partition(0, 11), 2);
+ assert_eq!(prune_all(&index, 0, 10).removed, 0);
+ assert_eq!(prune_all(&index, 0, 11).removed, 2);
assert!(index.is_empty());
}
@@ -469,7 +480,7 @@ mod tests {
}
// A catch-up reclaims across chunk boundaries in a single call.
- assert_eq!(index.prune_partition(0, total), total as usize);
+ assert_eq!(prune_all(&index, 0, total).removed, total as usize);
assert!(index.is_empty());
}
@@ -484,7 +495,7 @@ mod tests {
// The first chunk of an in-flight pass reclaims its bounded slice
// and reports the pass unfinished.
let (removed, exhausted) = index.prune_chunk(0, total);
- assert_eq!(removed, PRUNE_CHUNK);
+ assert_eq!(removed.removed, PRUNE_CHUNK);
assert!(!exhausted);
// A release lands between chunks: it detaches the queue and
@@ -495,13 +506,31 @@ mod tests {
// The paused pass re-fetches, observes the detachment, and ends
// instead of racing the drain it would otherwise double-count.
let (removed, exhausted) = index.prune_chunk(0, total);
- assert_eq!(removed, 0);
+ assert_eq!(removed.removed, 0);
assert!(exhausted);
// Ownership re-acquired after the release: fresh marks live in a
// fresh queue that a new pass reclaims normally.
index.mark(key(1), mark(total + 1, 0));
- assert_eq!(index.prune_partition(0, total + 2), 1);
+ assert_eq!(prune_all(&index, 0, total + 2).removed, 1);
+ assert!(index.is_empty());
+ }
+
+ #[test]
+ fn a_death_backlog_prunes_in_bounded_chunks() {
+ let total = PRUNE_CHUNK as i64 + 100;
+ let index = DirtyIndex::new(usize::MAX);
+ for offset in 0..total {
+ index.mark(key(offset), death_mark(offset, 0));
+ }
+
+ let (first, exhausted) = index.prune_chunk(0, total);
+ assert_eq!(first.death_marks.len(), PRUNE_CHUNK);
+ assert!(!exhausted);
+
+ let (rest, exhausted) = index.prune_chunk(0, total);
+ assert_eq!(rest.death_marks.len(), 100);
+ assert!(exhausted);
assert!(index.is_empty());
}
@@ -511,7 +540,7 @@ mod tests {
index.mark(key(1), mark(1, 0));
index.mark(key(2), mark(1, 7));
- assert_eq!(index.prune_partition(0, 100), 1);
+ assert_eq!(prune_all(&index, 0, 100).removed, 1);
assert!(index.get(&key(2)).is_some());
index.mark(key(3), mark(2, 7));
@@ -533,7 +562,7 @@ mod tests {
assert_eq!(index.max_offset(7), Some(2));
assert_eq!(index.max_offset(3), None);
- index.prune_partition(0, 100);
+ prune_all(&index, 0, 100);
assert_eq!(index.max_offset(0), None);
assert_eq!(index.partitions_with_marks(), vec![7]);
}
@@ -546,7 +575,7 @@ mod tests {
index.mark(key(2), mark(3, 0));
assert_eq!(index.len(), 2);
- index.prune_partition(0, 3);
+ prune_all(&index, 0, 3);
assert_eq!(index.len(), 1);
index.clear_partition(0);
diff --git a/rust/personhog-leader/src/cache/mod.rs b/rust/personhog-leader/src/cache/mod.rs
index 31bc7065cc3a..5920501fe21e 100644
--- a/rust/personhog-leader/src/cache/mod.rs
+++ b/rust/personhog-leader/src/cache/mod.rs
@@ -2,6 +2,6 @@ mod dirty_index;
mod partitioned;
mod persons;
-pub use dirty_index::{DirtyIndex, DirtyMark};
+pub use dirty_index::{DirtyIndex, DirtyMark, PRUNE_CHUNK};
pub use partitioned::{CacheLookup, PartitionedCache};
pub use persons::{approx_person_bytes, CachedPerson, PersonCache, PersonCacheKey};
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index 97fc9013a9cd..49e20c23ee9f 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -70,6 +70,12 @@ impl PartitionedCache {
/// finished cache with `publish_warmed_partition`. Re-entrant: a
/// retried warm begins fresh, replacing any half-built predecessor.
pub fn begin_warm_partition(&self, partition: u32) {
+ // A build over a published partition would let the prune settle
+ // marks the build depends on; release drops the cache first.
+ assert!(
+ !self.partitions.contains_key(&partition),
+ "warm began for published partition {partition}"
+ );
self.warming
.insert(partition, PersonCache::new(self.per_partition_capacity));
}
@@ -82,6 +88,21 @@ impl PartitionedCache {
.put(key, person);
}
+ /// Remove a key from a partition cache under construction. An applied
+ /// death record erases its predecessors from the build this way.
+ pub fn warm_remove(&self, partition: u32, key: &PersonCacheKey) {
+ self.warming
+ .get(&partition)
+ .expect("warm_remove before begin_warm_partition")
+ .remove(key);
+ }
+
+ /// Whether the partition is published (serving reads). The prune
+ /// only settles published partitions' marks.
+ pub fn is_published(&self, partition: u32) -> bool {
+ self.partitions.contains_key(&partition)
+ }
+
/// Publish a fully-built partition cache: one `DashMap` insert flips
/// the partition from invisible to fully observable, preserving the
/// no-partial-window property `install_warmed_partition` documents.
@@ -153,10 +174,16 @@ impl PartitionedCache {
}
}
- /// Remove a single person from the partition's cache. Only tests call
- /// this, to force a deterministic eviction — production evictions come
- /// from Foyer's capacity policy. Safe regardless: the miss path
- /// recovers the person from the changelog or PG on next access.
+ /// Counter-free read for bookkeeping passes; see [`PersonCache::peek`].
+ pub fn peek(&self, partition: u32, key: &PersonCacheKey) -> Option<Arc<CachedPerson>> {
+ self.partitions
+ .get(&partition)
+ .and_then(|cache| cache.peek(key))
+ }
+
+ /// Remove one person. Called by the death-document settle and by
+ /// tests; safe regardless — the miss path recovers from the
+ /// changelog or PG.
pub fn remove(&self, partition: u32, key: &PersonCacheKey) {
if let Some(cache) = self.partitions.get(&partition) {
cache.remove(key);
@@ -191,6 +218,14 @@ mod tests {
}
}
+ #[test]
+ #[should_panic(expected = "warm began for published partition")]
+ fn a_warm_must_not_begin_over_a_published_partition() {
+ let cache = PartitionedCache::new(1 << 20);
+ cache.create_partition(0);
+ cache.begin_warm_partition(0);
+ }
+
#[test]
fn get_returns_partition_not_owned_for_unknown_partition() {
let cache = PartitionedCache::new(1 << 20);
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index b0f929fd1767..cf3236232d8a 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -45,9 +45,9 @@ pub struct CachedPerson {
pub version: i64,
pub is_identified: bool,
/// True when this entry is a recovered death document: the person was
- /// destroyed and this version closes its stream. Kept in cache (rather
- /// than dropped) so reads answer an authoritative not-found instead of
- /// falling back to a PG row the writer may not have tombstoned yet.
+ /// destroyed and this version closes its stream. Cached while its
+ /// dirty mark stands (the writer may not have tombstoned the PG row
+ /// yet); the prune-time settle drops it, and PG answers after.
pub is_deleted: bool,
/// Epoch milliseconds of the person's last observed activity, when
/// known (matching `created_at`'s unit). Max-merged on update — the
@@ -160,6 +160,13 @@ impl PersonCache {
}
}
+ /// A read that skips the hit/miss counters — for bookkeeping passes
+ /// (the death-document settle), not serving. It still promotes the
+ /// entry's recency, which is harmless for those passes.
+ pub fn peek(&self, key: &PersonCacheKey) -> Option<Arc<CachedPerson>> {
+ self.inner.get(key).map(|entry| entry.value().clone())
+ }
+
pub fn put(&self, key: PersonCacheKey, person: CachedPerson) {
self.inner.insert(key, Arc::new(person));
}
diff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rs
index b912d3153810..c4d724e94fcb 100644
--- a/rust/personhog-leader/src/lib.rs
+++ b/rust/personhog-leader/src/lib.rs
@@ -10,5 +10,6 @@ pub mod person_update;
pub mod pg;
pub mod recovery;
pub mod service;
+pub mod settle;
pub mod warming;
pub mod warnings;
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 8b8321036837..ff1ad5d45eac 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -29,7 +29,7 @@ use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
use metrics::{counter, gauge};
-use personhog_leader::cache::{DirtyIndex, PartitionedCache};
+use personhog_leader::cache::{DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::config::Config;
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::fencing::{
@@ -39,9 +39,8 @@ use personhog_leader::inflight::InflightTracker;
use personhog_leader::pg::{validate_table_name, PgFallback};
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};
-use personhog_leader::warming::{
- fetch_writer_committed_offsets, WarmClientPools, WarmingConfig, WarmingRetryPolicy,
-};
+use personhog_leader::settle::prune_and_settle_tick;
+use personhog_leader::warming::{WarmClientPools, WarmingConfig, WarmingRetryPolicy};
use personhog_leader::warnings::WarningsProducer;
common_alloc::used!();
@@ -638,6 +637,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(run_dirty_index_prune_loop(
Arc::clone(&dirty_index),
Arc::clone(&cache),
+ Arc::clone(&locks),
Arc::clone(&warm_pools),
config.kafka_person_state_topic.clone(),
Duration::from_secs(config.warm_committed_offsets_timeout_secs),
@@ -732,6 +732,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn run_dirty_index_prune_loop(
dirty_index: Arc<DirtyIndex>,
cache: Arc<PartitionedCache>,
+ locks: Arc<DashMap<PersonCacheKey, Arc<tokio::sync::Mutex<()>>>>,
pools: Arc<WarmClientPools>,
topic: String,
offsets_timeout: Duration,
@@ -744,31 +745,23 @@ async fn run_dirty_index_prune_loop(
// marks actually reclaimed — a tick never scans the index, which
// is what makes the 1s interval affordable even when a lagging
// writer has made the index large.
- let partitions = dirty_index.partitions_with_marks();
gauge!("personhog_leader_dirty_index_size").set(dirty_index.len() as f64);
gauge!("personhog_leader_dirty_index_max_entries").set(dirty_index.max_entries() as f64);
gauge!("personhog_leader_cache_weight_bytes").set(cache.usage_bytes() as f64);
- if partitions.is_empty() {
- continue;
- }
- let committed_offsets = match fetch_writer_committed_offsets(
+ let Some((partitions, committed_offsets)) = prune_and_settle_tick(
+ &dirty_index,
+ &cache,
+ &locks,
&pools.offsets,
&topic,
- &partitions,
offsets_timeout,
)
.await
- {
- Ok(offsets) => offsets,
- Err(e) => {
- tracing::warn!(error = %e, "dirty-index prune offset fetch failed");
- continue;
- }
+ else {
+ continue;
};
-
- let pruned = dirty_index.prune_applied(&committed_offsets);
- if pruned > 0 {
- counter!("personhog_leader_dirty_index_pruned_total").increment(pruned as u64);
+ if partitions.is_empty() {
+ continue;
}
// A partition absent from the committed offsets has no writer
// commit yet: nothing is applied, every mark stays, and its lag
@@ -831,6 +824,7 @@ fn preregister_metrics() {
counter!("personhog_leader_indeterminate_outcomes_total", "fenced" => fenced).increment(0);
}
counter!("personhog_leader_unresolved_versions_total").increment(0);
+ counter!("personhog_leader_death_documents_settled_total").increment(0);
gauge!("personhog_leader_unresolved_versions").set(0.0);
counter!("personhog_leader_warmed_messages_total").increment(0);
counter!("personhog_leader_warm_retries_exhausted_total", "stage" => "committed_offset")
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index ca3d79698ba8..e71f0d69e8c8 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -172,6 +172,16 @@ impl PersonHogLeaderService {
)))
}
+ /// The fence RPCs' exit gate: a success answer re-proves authority at
+ /// the moment it is given. Only a stale Ok can wrongly settle a saga;
+ /// errors bounce and retry.
+ #[allow(clippy::result_large_err)]
+ fn authoritative_ok<T>(&self, partition: u32, resp: T) -> Result<Response<T>, Status> {
+ self.check_authority(partition)?;
+ self.validate_ownership(partition)?;
+ Ok(Response::new(resp))
+ }
+
#[allow(clippy::too_many_arguments)]
pub fn new(
cache: Arc<PartitionedCache>,
@@ -684,6 +694,7 @@ impl PersonHogLeaderService {
version: person.version,
offset,
partition,
+ is_deleted: person.is_deleted,
},
);
self.cache.put(partition, cache_key.clone(), person);
@@ -1046,6 +1057,9 @@ impl PersonHogLeader for PersonHogLeaderService {
}
let person = self.lookup_or_load_locked(partition, &cache_key).await?;
+ // The load can park past the claim; the no-change answers below
+ // carry cached state, so they need ownership like any read.
+ self.check_authority(partition)?;
// A destroyed person answers not-found — the caller re-resolves;
// post-death the distinct id may have been reborn as a new person.
@@ -1340,6 +1354,10 @@ impl PersonHogLeader for PersonHogLeaderService {
}
let person = self.lookup_or_load_locked(partition, &cache_key).await?;
+ // The load can park past the claim, and a not-found here is a
+ // verdict the router delivers, so it needs ownership like any
+ // answer.
+ self.check_authority(partition)?;
if person.is_deleted {
return Err(Status::not_found("person is destroyed"));
}
@@ -1516,9 +1534,12 @@ impl PersonHogLeader for PersonHogLeaderService {
"fold target's stored properties exceed the size constraint; \
skipping the fold's document write"
);
- return Ok(Response::new(FoldPersonDocumentResponse {
- person: Some(cached_person_to_proto(&person)),
- }));
+ return self.authoritative_ok(
+ partition,
+ FoldPersonDocumentResponse {
+ person: Some(cached_person_to_proto(&person)),
+ },
+ );
}
fold_outcome = "unremediable";
folded = target_properties.clone();
@@ -1587,9 +1608,12 @@ impl PersonHogLeader for PersonHogLeaderService {
.await?;
counter!("personhog_leader_folds_total", "outcome" => fold_outcome).increment(1);
- Ok(Response::new(FoldPersonDocumentResponse {
- person: Some(proto),
- }))
+ self.authoritative_ok(
+ partition,
+ FoldPersonDocumentResponse {
+ person: Some(proto),
+ },
+ )
}
async fn fence_person(
@@ -1599,6 +1623,9 @@ impl PersonHogLeader for PersonHogLeaderService {
let partition = partition_from_metadata(&request)?;
let req = request.into_inner();
self.validate_partition(partition, req.team_id, req.person_id)?;
+ // Ownership below is in-process state, which is what a lease
+ // lapse makes stale: a fence installed here gates no writes.
+ self.check_authority(partition)?;
let op_id = Uuid::parse_str(&req.op_id)
.map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;
let op_type = req.op_type();
@@ -1675,6 +1702,9 @@ impl PersonHogLeader for PersonHogLeaderService {
// same-op re-fence takes this path too, re-sealing with fresh
// state (the saga's seal step is safe to repeat).
let person = self.lookup_or_load_locked(partition, &cache_key).await?;
+ // The load can park on the per-key lock or a recovery; the seal,
+ // not the arrival, must be backed by ownership.
+ self.check_authority(partition)?;
if person.is_deleted {
return Err(Status::not_found("person is destroyed"));
}
@@ -1687,9 +1717,12 @@ impl PersonHogLeader for PersonHogLeaderService {
self.fences.insert(cache_key, FenceState { op_id, op_type });
counter!("personhog_leader_fences_total", "action" => "fenced").increment(1);
- Ok(Response::new(FencePersonResponse {
- sealed: Some(sealed),
- }))
+ self.authoritative_ok(
+ partition,
+ FencePersonResponse {
+ sealed: Some(sealed),
+ },
+ )
}
async fn release_fence(
@@ -1699,15 +1732,13 @@ impl PersonHogLeader for PersonHogLeaderService {
let partition = partition_from_metadata(&request)?;
let req = request.into_inner();
self.validate_partition(partition, req.team_id, req.person_id)?;
+ // The aborted arm would otherwise ack under a lapsed lease; the
+ // committed arm's produce and durable-fact acks need no cover.
+ self.check_authority(partition)?;
let op_id = Uuid::parse_str(&req.op_id)
.map_err(|_| Status::invalid_argument("op_id must be a valid UUID"))?;
let outcome = req.outcome();
- // Both outcomes: a release that removed nothing and returned OK
- // would leave the real owner's fence standing while the saga
- // believes it released — a person frozen with no retry coming.
- self.validate_ownership(partition)?;
-
let cache_key = PersonCacheKey {
team_id: req.team_id,
person_id: req.person_id,
@@ -1769,10 +1800,12 @@ impl PersonHogLeader for PersonHogLeaderService {
};
// Duplicate release: the death document already exists;
- // producing another would only bump the version.
+ // producing another would only bump the version. Gate
+ // first — a refused release must leave the fence.
if current.as_ref().is_some_and(|p| p.is_deleted) {
+ let resp = self.authoritative_ok(partition, ReleaseFenceResponse {})?;
self.fences.remove(&cache_key);
- return Ok(Response::new(ReleaseFenceResponse {}));
+ return Ok(resp);
}
// The death document's identity comes from the request (a
@@ -1809,8 +1842,9 @@ impl PersonHogLeader for PersonHogLeaderService {
// already happened and the tombstone is durable;
// absorb the retry.
Ok(Some(status)) if status == "deleted" => {
+ let resp = self.authoritative_ok(partition, ReleaseFenceResponse {})?;
self.fences.remove(&cache_key);
- return Ok(Response::new(ReleaseFenceResponse {}));
+ return Ok(resp);
}
Ok(_) => {
counter!("personhog_leader_fences_total", "action" => "release_unverified")
@@ -1874,31 +1908,30 @@ impl PersonHogLeader for PersonHogLeaderService {
approx_bytes: approx_person_bytes(2),
};
self.commit_document(partition, &cache_key, death).await?;
- // The death document stays in the cache (commit_document
- // put it there): an is_deleted entry answers reads and
- // writes with an authoritative not-found from memory, the
- // same way a recovered death document does. Removing it
- // would only re-derive it — the next attempt recovers the
- // death record via the dirty mark and re-installs it — and
- // once the mark is pruned every attempt would fall through
- // to a PG read instead.
+ // The death document stays cached while its mark stands,
+ // answering an authoritative not-found from memory; the
+ // prune-time settle drops it once the writer confirms,
+ // and PG answers from then on — revival included.
self.fences.remove(&cache_key);
counter!("personhog_leader_fences_total", "action" => "released_committed")
.increment(1);
}
ReleaseOutcome::Aborted => {
// The op backed out: drop the fence, keep the entry,
- // produce nothing. The person resumes normal life.
+ // produce nothing. Gate first — a refused release must
+ // leave the fence (pinned).
+ let resp = self.authoritative_ok(partition, ReleaseFenceResponse {})?;
self.fences.remove(&cache_key);
counter!("personhog_leader_fences_total", "action" => "released_aborted")
.increment(1);
+ return Ok(resp);
}
ReleaseOutcome::Unspecified => {
return Err(Status::invalid_argument("outcome must be specified"));
}
}
- Ok(Response::new(ReleaseFenceResponse {}))
+ self.authoritative_ok(partition, ReleaseFenceResponse {})
}
}
@@ -2197,6 +2230,495 @@ mod tests {
.expect("a confirmed renewal serves the read");
}
+ /// Wiring pin for `fence_person`: with both gates removed the fence
+ /// installs. Either gate alone satisfies it; the parked and
+ /// refused-before-work pins each single out one.
+ #[tokio::test]
+ async fn fence_person_refuses_once_authority_lapses() {
+ let margin = Duration::from_secs(20);
+ let clock = Arc::new(AuthorityClock::stale_for(
+ margin,
+ margin + Duration::from_secs(1),
+ ));
+ let service = PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ };
+ let (team_id, person_id) = (7, 42);
+ service.cache.create_partition(0);
+ service.cache.put(
+ 0,
+ PersonCacheKey { team_id, person_id },
+ CachedPerson {
+ id: person_id,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id,
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
+ created_at: 0,
+ version: 1,
+ is_identified: false,
+ is_deleted: false,
+ last_seen_at: None,
+ approx_bytes: 64,
+ },
+ );
+
+ let request = || {
+ let mut request = Request::new(FencePersonRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ op_type: LifecycleOpType::Delete as i32,
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ request
+ };
+
+ let err = service
+ .fence_person(request())
+ .await
+ .expect_err("a lapsed lease must not install a fence");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+
+ clock.confirm(Instant::now());
+ service
+ .fence_person(request())
+ .await
+ .expect("a confirmed renewal installs the fence");
+ }
+
+ /// `release_fence`'s aborted arm acks without producing, so
+ /// `commit_document`'s re-check never runs; either release gate may
+ /// refuse here — the timeout test is the admission-specific pin.
+ #[tokio::test]
+ async fn release_fence_refuses_once_authority_lapses() {
+ let margin = Duration::from_secs(20);
+ let clock = Arc::new(AuthorityClock::stale_for(
+ margin,
+ margin + Duration::from_secs(1),
+ ));
+ let service = PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ };
+ let (team_id, person_id) = (7, 42);
+ service.cache.create_partition(0);
+
+ let request = || {
+ let mut request = Request::new(ReleaseFenceRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ outcome: ReleaseOutcome::Aborted as i32,
+ ..Default::default()
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ request
+ };
+
+ let err = service
+ .release_fence(request())
+ .await
+ .expect_err("a lapsed lease must not ack a release");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+
+ clock.confirm(Instant::now());
+ service
+ .release_fence(request())
+ .await
+ .expect("a confirmed renewal acks the abort");
+ }
+
+ /// A fence admitted before the lapse must not install once parked
+ /// past it. The map assertion is the point: the install, not the
+ /// status, is the danger.
+ #[tokio::test]
+ async fn a_fence_admitted_before_the_lapse_does_not_install() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ service.cache.create_partition(0);
+ // Seeded live, so a confirmed clock would seal successfully; the
+ // refusal must come from the lapse alone.
+ service.cache.put(
+ 0,
+ cache_key.clone(),
+ CachedPerson {
+ id: person_id,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id,
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
+ created_at: 0,
+ version: 1,
+ is_identified: false,
+ is_deleted: false,
+ last_seen_at: None,
+ approx_bytes: 64,
+ },
+ );
+
+ // Hold the per-key lock so the fence parks before its seal.
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let held = mutex.lock().await;
+
+ let mut request = Request::new(FencePersonRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ op_type: LifecycleOpType::Delete as i32,
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let fencing = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.fence_person(request).await }
+ });
+ tokio::task::yield_now().await;
+
+ clock.surrender();
+ drop(held);
+
+ let err = fencing
+ .await
+ .unwrap()
+ .expect_err("a fence parked past the lapse must refuse");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ assert!(
+ service.fences.is_empty(),
+ "no fence may install under a lapsed claim"
+ );
+ }
+
+ /// A release admitted while owned must not ack once parked past an
+ /// ordinary handoff: the partition (and its fences) are gone, so the
+ /// ack would report a removal that never happened. The lease stays
+ /// valid throughout — this pins the ownership re-check, not the clock.
+ #[tokio::test]
+ async fn a_release_parked_past_a_handoff_does_not_ack() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ let op_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap();
+ service.cache.create_partition(0);
+ service.fences.insert(
+ cache_key.clone(),
+ FenceState {
+ op_id,
+ op_type: LifecycleOpType::Delete,
+ },
+ );
+
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let held = mutex.lock().await;
+
+ let mut request = Request::new(ReleaseFenceRequest {
+ team_id,
+ person_id,
+ op_id: op_id.to_string(),
+ outcome: ReleaseOutcome::Aborted as i32,
+ ..Default::default()
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let releasing = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.release_fence(request).await }
+ });
+ tokio::task::yield_now().await;
+
+ // The handoff completes while the release is parked.
+ service.cache.drop_partition(0);
+ crate::fence::drop_partition_fences(&service.fences, 0, 1);
+ drop(held);
+
+ let err = releasing
+ .await
+ .unwrap()
+ .expect_err("a release parked past a handoff must refuse");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ }
+
+ /// A release admitted before the lapse must not ack once parked past
+ /// it: removing only this stale map's entry while the saga believes
+ /// the fence released would be a vacuous success.
+ #[tokio::test]
+ async fn a_release_admitted_before_the_lapse_does_not_ack() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ let op_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap();
+ service.cache.create_partition(0);
+ service.fences.insert(
+ cache_key.clone(),
+ FenceState {
+ op_id,
+ op_type: LifecycleOpType::Delete,
+ },
+ );
+
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let held = mutex.lock().await;
+
+ let mut request = Request::new(ReleaseFenceRequest {
+ team_id,
+ person_id,
+ op_id: op_id.to_string(),
+ outcome: ReleaseOutcome::Aborted as i32,
+ ..Default::default()
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let releasing = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.release_fence(request).await }
+ });
+ tokio::task::yield_now().await;
+
+ clock.surrender();
+ drop(held);
+
+ let err = releasing
+ .await
+ .unwrap()
+ .expect_err("a release parked past the lapse must refuse");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ assert!(
+ service.fences.contains_key(&cache_key),
+ "the fence must survive a refused release"
+ );
+ }
+
+ /// The admission gates on both fence RPCs refuse before any work;
+ /// only the wait distinguishes them from the later re-checks, so a
+ /// held per-key lock turns a dropped admission gate into a timeout.
+ #[tokio::test]
+ async fn fence_rpcs_arriving_after_the_lapse_are_refused_at_admission() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ service.cache.create_partition(0);
+
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let _held = mutex.lock().await;
+
+ clock.surrender();
+
+ let mut fence = Request::new(FencePersonRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ op_type: LifecycleOpType::Delete as i32,
+ });
+ fence
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let err = tokio::time::timeout(Duration::from_millis(200), service.fence_person(fence))
+ .await
+ .expect("the fence must be refused at admission, not behind the lock")
+ .expect_err("a lapsed claim must not fence");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+
+ let mut release = Request::new(ReleaseFenceRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ outcome: ReleaseOutcome::Aborted as i32,
+ ..Default::default()
+ });
+ release
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let err = tokio::time::timeout(Duration::from_millis(200), service.release_fence(release))
+ .await
+ .expect("the release must be refused at admission, not behind the lock")
+ .expect_err("a lapsed claim must not release");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ }
+
+ /// A no-change update answers cached state, which is a read: parked
+ /// past the lapse it must refuse rather than answer updated:false.
+ #[tokio::test]
+ async fn a_no_change_update_refuses_once_parked_past_the_lapse() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ service.cache.create_partition(0);
+ service.cache.put(
+ 0,
+ cache_key.clone(),
+ CachedPerson {
+ id: person_id,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id,
+ properties: serde_json::to_vec(&serde_json::json!({"plan": "pro"})).unwrap(),
+ created_at: 0,
+ version: 1,
+ is_identified: false,
+ is_deleted: false,
+ last_seen_at: None,
+ approx_bytes: 64,
+ },
+ );
+
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let held = mutex.lock().await;
+
+ // The same value the cache holds, so the no-change answer path runs.
+ let mut request = Request::new(UpdatePersonPropertiesRequest {
+ force_update: false,
+ team_id,
+ person_id,
+ event_name: "$pageview".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"plan": "pro"})).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ is_identified: None,
+ last_seen_at: None,
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let updating = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.update_person_properties(request).await }
+ });
+ tokio::task::yield_now().await;
+
+ clock.surrender();
+ drop(held);
+
+ let err = updating
+ .await
+ .unwrap()
+ .expect_err("a no-change answer parked past the lapse must refuse");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ }
+
+ /// A fold parked past the lapse must refuse, not answer: its
+ /// not-found is a verdict the router delivers to the saga, unlike
+ /// the FailedPrecondition a refusal bounces.
+ #[tokio::test]
+ async fn a_fold_parked_past_the_lapse_refuses_instead_of_answering_destroyed() {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(30), Instant::now());
+ let service = Arc::new(PersonHogLeaderService {
+ authority: Some(Arc::clone(&clock)),
+ ..make_test_service().await
+ });
+ let (team_id, person_id) = (7, 42);
+ let cache_key = PersonCacheKey { team_id, person_id };
+ service.cache.create_partition(0);
+ // A death document, so without the gate the fold answers a
+ // definitive not-found from a claim it no longer holds.
+ service.cache.put(
+ 0,
+ cache_key.clone(),
+ CachedPerson {
+ id: person_id,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id,
+ properties: b"{}".to_vec(),
+ created_at: 0,
+ version: 3,
+ is_identified: false,
+ is_deleted: true,
+ last_seen_at: None,
+ approx_bytes: 64,
+ },
+ );
+
+ let mutex = service
+ .locks
+ .entry(cache_key.clone())
+ .or_default()
+ .value()
+ .clone();
+ let held = mutex.lock().await;
+
+ let mut request = Request::new(FoldPersonDocumentRequest {
+ team_id,
+ person_id,
+ op_id: "11111111-1111-1111-1111-111111111111".to_string(),
+ sealed_snapshots: vec![wire_snapshot(source_person(43, &serde_json::json!({})), 0)],
+ event_set: b"{}".to_vec(),
+ event_set_once: b"{}".to_vec(),
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", "0".parse().unwrap());
+ let folding = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.fold_person_document(request).await }
+ });
+ tokio::task::yield_now().await;
+
+ clock.surrender();
+ drop(held);
+
+ let err = folding
+ .await
+ .unwrap()
+ .expect_err("a fold parked past the lapse must refuse");
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ }
+
/// A write is serving too, and the lease-loss path surrenders before
/// it drains — so between the surrender and the local fence landing,
/// this check is what stops a pod that no longer holds its lease from
diff --git a/rust/personhog-leader/src/settle.rs b/rust/personhog-leader/src/settle.rs
new file mode 100644
index 000000000000..175c17a49f46
--- /dev/null
+++ b/rust/personhog-leader/src/settle.rs
@@ -0,0 +1,164 @@
+//! Death-document residency maintenance: the prune tick and the settle
+//! that drops a death document once the writer has applied its record.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use dashmap::DashMap;
+use metrics::{counter, histogram};
+use tokio::sync::Mutex;
+
+use crate::cache::{CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey};
+use crate::warming::{fetch_writer_committed_offsets, ConsumerPool};
+
+/// One prune pass: fetch committed offsets, prune applied marks of the
+/// published partitions only (the settle cannot see a warming build),
+/// and settle the death documents those marks covered. Returns marked
+/// partitions and offsets for lag gauges; None if the fetch failed.
+pub async fn prune_and_settle_tick(
+ dirty_index: &DirtyIndex,
+ cache: &PartitionedCache,
+ locks: &DashMap<PersonCacheKey, Arc<Mutex<()>>>,
+ offsets_pool: &ConsumerPool,
+ topic: &str,
+ offsets_timeout: Duration,
+) -> Option<(Vec<u32>, HashMap<u32, i64>)> {
+ let partitions = dirty_index.partitions_with_marks();
+ if partitions.is_empty() {
+ return Some((partitions, HashMap::new()));
+ }
+ let committed_offsets =
+ match fetch_writer_committed_offsets(offsets_pool, topic, &partitions, offsets_timeout)
+ .await
+ {
+ Ok(offsets) => offsets,
+ Err(e) => {
+ tracing::warn!(error = %e, "dirty-index prune offset fetch failed");
+ return None;
+ }
+ };
+
+ // Prune chunk by chunk, settling each chunk's death pairs before the
+ // next, so a catch-up never materializes more than one chunk.
+ let started = Instant::now();
+ let mut removed_total = 0u64;
+ for (partition, committed) in &committed_offsets {
+ if !cache.is_published(*partition) {
+ continue;
+ }
+ loop {
+ let (pruned, exhausted) = dirty_index.prune_chunk(*partition, *committed);
+ removed_total += pruned.removed as u64;
+ if !pruned.death_marks.is_empty() {
+ drop_settled_death_documents(cache, locks, &pruned.death_marks).await;
+ }
+ if exhausted {
+ break;
+ }
+ }
+ }
+ if removed_total > 0 {
+ counter!("personhog_leader_dirty_index_pruned_total").increment(removed_total);
+ }
+ // A long tick means the settle parked on per-key locks, not an idle
+ // pass.
+ histogram!("personhog_leader_prune_tick_duration_ms")
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+ Some((partitions, committed_offsets))
+}
+
+/// Drop death documents whose marks the writer settled: past the mark,
+/// PG answers for the person — tombstoned or revived. A revival cannot
+/// precede the applied tombstone (stub creation revives only
+/// `is_deleted = true` rows), so the miss after the drop serves truth.
+pub async fn drop_settled_death_documents(
+ cache: &PartitionedCache,
+ locks: &DashMap<PersonCacheKey, Arc<Mutex<()>>>,
+ pruned: &[(PersonCacheKey, DirtyMark)],
+) {
+ for (key, mark) in pruned {
+ // Skip lock-free only on a live or newer entry. An absent entry
+ // must take the lock: a recovery holding it may be about to
+ // install this very death document.
+ let settled = |entry: &Arc<CachedPerson>| entry.is_deleted && entry.version == mark.version;
+ if cache
+ .peek(mark.partition, key)
+ .as_ref()
+ .is_some_and(|entry| !settled(entry))
+ {
+ continue;
+ }
+ {
+ let mutex = locks.entry(key.clone()).or_default().value().clone();
+ let _guard = mutex.lock().await;
+ // Re-proved under the lock so a concurrent commit's newer entry
+ // is never dropped.
+ if cache
+ .peek(mark.partition, key)
+ .as_ref()
+ .is_some_and(settled)
+ {
+ cache.remove(mark.partition, key);
+ counter!("personhog_leader_death_documents_settled_total").increment(1);
+ }
+ }
+ // Drop the just-minted lock so a delete storm cannot pile idle
+ // entries between sweeps; strong_count == 1 means the map alone holds it.
+ locks.remove_if(key, |_, m| Arc::strong_count(m) == 1);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::cache::approx_person_bytes;
+
+ fn death_person(version: i64) -> CachedPerson {
+ CachedPerson {
+ id: 1,
+ uuid: "dead-1".to_string(),
+ team_id: 7,
+ properties: Vec::new(),
+ created_at: 1_700_000_000,
+ version,
+ is_identified: true,
+ is_deleted: true,
+ last_seen_at: None,
+ approx_bytes: approx_person_bytes(0),
+ }
+ }
+
+ #[tokio::test]
+ async fn settling_a_death_document_leaves_no_lock_entry() {
+ let cache = PartitionedCache::new(16);
+ cache.create_partition(0);
+ let key = PersonCacheKey {
+ team_id: 7,
+ person_id: 1,
+ };
+ cache.put(0, key.clone(), death_person(5));
+
+ let locks: DashMap<PersonCacheKey, Arc<Mutex<()>>> = DashMap::new();
+ let pruned = vec![(
+ key.clone(),
+ DirtyMark {
+ version: 5,
+ offset: 0,
+ partition: 0,
+ is_deleted: true,
+ },
+ )];
+
+ drop_settled_death_documents(&cache, &locks, &pruned).await;
+
+ assert!(
+ cache.peek(0, &key).is_none(),
+ "settled death document should be dropped"
+ );
+ assert!(
+ locks.is_empty(),
+ "settle must not leave an idle lock entry in the map"
+ );
+ }
+}
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index 73e80edb641e..b6a3d4236929 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -683,11 +683,19 @@ pub async fn warm_from_kafka(
version: cached.version,
offset,
partition,
+ is_deleted: cached.is_deleted,
},
);
seeded += 1;
+ cache.warm_put(partition, key, cached);
+ } else if cached.is_deleted {
+ // An applied death record leaves no residue: unmarked it
+ // would answer forever, and its predecessor in the build
+ // would resurrect the destroyed person's data.
+ cache.warm_remove(partition, &key);
+ } else {
+ cache.warm_put(partition, key, cached);
}
- cache.warm_put(partition, key, cached);
} else {
// The writer never produces null-payload (tombstone) records
// to `personhog_updates` today. If one ever appears it would
@@ -813,6 +821,7 @@ mod tests {
version: 1,
offset: 7,
partition: 0,
+ is_deleted: false,
},
);
cache.warm_put(0, key.clone(), warm_test_person());
@@ -856,6 +865,7 @@ mod tests {
version: 1,
offset: 7,
partition: 0,
+ is_deleted: false,
},
);
cache.warm_put(0, key.clone(), warm_test_person());
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index 0fa28055c8e6..1ecaed777189 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -20,6 +20,7 @@ use personhog_leader::fence::{FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY};
use personhog_leader::inflight::InflightTracker;
use personhog_leader::pg::PgFallback;
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
+use personhog_leader::settle::drop_settled_death_documents;
use personhog_leader::warnings::WarningsProducer;
use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
@@ -80,6 +81,8 @@ struct FenceHarness {
cache: Arc<PartitionedCache>,
inflight: Arc<InflightTracker>,
emitted_versions: Arc<EmittedVersions>,
+ dirty_index: Arc<DirtyIndex>,
+ locks: Arc<DashMap<PersonCacheKey, Arc<tokio::sync::Mutex<()>>>>,
_cancel: CancellationToken,
_mock_cluster:
rdkafka::mocking::MockCluster<'static, rdkafka::producer::DefaultProducerContext>,
@@ -100,6 +103,8 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
let cache = Arc::new(PartitionedCache::new(1 << 20));
let inflight = Arc::new(InflightTracker::new());
let emitted_versions = Arc::new(EmittedVersions::new(1_000_000));
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let locks = Arc::new(DashMap::new());
// Recovery consumes the same mock cluster so a post-death cache miss
// can recover the death document.
let service = PersonHogLeaderService::new(
@@ -107,10 +112,10 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
kafka_producer.clone(),
CHANGELOG_TOPIC.to_string(),
fallback,
- Arc::new(DashMap::new()),
+ Arc::clone(&locks),
Arc::clone(&inflight),
NUM_PARTITIONS,
- Arc::new(DirtyIndex::new(1_000_000)),
+ Arc::clone(&dirty_index),
test_recovery(&bootstrap),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
@@ -148,6 +153,8 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
cache,
inflight,
emitted_versions,
+ dirty_index,
+ locks,
_cancel: cancel,
_mock_cluster: mock_cluster,
}
@@ -467,6 +474,151 @@ async fn a_committed_release_produces_the_death_document_above_every_version() {
.expect("cleanup");
}
+/// While the death document's mark stands, reads answer not-found even if
+/// PG already holds a revived row. Once the mark settles, the document
+/// leaves the cache and the next read serves the revival from PG.
+#[tokio::test]
+async fn a_revival_is_served_once_the_death_documents_mark_settles() {
+ let pool = common::create_persons_pool().await;
+ let mut harness = start_fence_harness(
+ test_cached_person(),
+ Some(PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ }),
+ )
+ .await;
+ let team_id = harness.team_id;
+ let partition = harness.partition;
+ let person_id = harness.person_id;
+ let person_uuid = test_cached_person().uuid;
+ let op = Uuid::now_v7();
+
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request) \
+ VALUES ($1, 'delete', $2, 'sealed', '{}'::jsonb)",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .execute(&pool)
+ .await
+ .expect("insert op");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'sealed')",
+ )
+ .bind(op)
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("insert mark");
+
+ let sealed = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, person_id, &op),
+ partition,
+ ))
+ .await
+ .expect("fence succeeds")
+ .into_inner()
+ .sealed
+ .unwrap();
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id,
+ person_uuid: person_uuid.clone(),
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sealed.version),
+ created_at: sealed.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("committed release succeeds");
+
+ let key = PersonCacheKey { team_id, person_id };
+ let death = harness
+ .cache
+ .peek(partition, &key)
+ .expect("the death document is cached");
+ assert!(death.is_deleted);
+
+ // A stub-create revived the row in place: same id and uuid, version
+ // above the death document's.
+ sqlx::query(
+ "INSERT INTO posthog_person \
+ (id, team_id, uuid, properties, created_at, version, is_identified, is_deleted) \
+ VALUES ($1, $2, $3::uuid, '{\"revived\": true}'::jsonb, now(), $4, false, false)",
+ )
+ .bind(person_id)
+ .bind(team_id as i32)
+ .bind(&person_uuid)
+ .bind(death.version + 1)
+ .execute(&pool)
+ .await
+ .expect("insert revived row");
+
+ let get = || {
+ with_partition(
+ GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ )
+ };
+ let status = harness
+ .client
+ .get_person(get())
+ .await
+ .expect_err("the death document answers while its mark stands");
+ assert_eq!(status.code(), Code::NotFound);
+
+ // The writer commits past the death record; the prune settles its mark.
+ let mark = harness
+ .dirty_index
+ .get(&key)
+ .expect("the release marks the death record");
+ let (pruned, exhausted) = harness.dirty_index.prune_chunk(partition, mark.offset + 1);
+ assert!(exhausted);
+ assert_eq!(pruned.death_marks.len(), 1);
+ drop_settled_death_documents(&harness.cache, &harness.locks, &pruned.death_marks).await;
+ assert!(
+ harness.cache.peek(partition, &key).is_none(),
+ "the settled death document leaves the cache"
+ );
+
+ let revived = harness
+ .client
+ .get_person(get())
+ .await
+ .expect("the revival is served from PG after the settle")
+ .into_inner()
+ .person
+ .unwrap();
+ assert_eq!(revived.version, death.version + 1);
+ assert_eq!(revived.uuid, person_uuid);
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup op");
+ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1 AND id = $2")
+ .bind(team_id as i32)
+ .bind(person_id)
+ .execute(&pool)
+ .await
+ .expect("cleanup person");
+}
+
/// A pre-fence write with an indeterminate produce outcome spends a
/// version the cache never learned of. The seal must cover it: sealed
/// below the spent version, the death document would derive at a version
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 80bca3bed0d1..8192ac582cfa 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -1683,6 +1683,7 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {
version: mark.version,
offset: mark.offset + 1_000,
partition: mark.partition,
+ is_deleted: mark.is_deleted,
},
);
cache.remove(routing_partition, &key);
@@ -2078,6 +2079,7 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
version: 1,
offset: 0,
partition: 0,
+ is_deleted: false,
};
// Nothing is produced yet, so each fetch parks awaiting the record;
diff --git a/rust/personhog-leader/tests/settle_integration.rs b/rust/personhog-leader/tests/settle_integration.rs
new file mode 100644
index 000000000000..98536e97f8cf
--- /dev/null
+++ b/rust/personhog-leader/tests/settle_integration.rs
@@ -0,0 +1,150 @@
+//! Death-document settle: a pruned mark drops its death document from the
+//! cache, and only its own — the removal is version-conditional and
+//! serialized on the per-key lock.
+
+mod common;
+
+use std::sync::Arc;
+
+use dashmap::DashMap;
+use personhog_leader::cache::{CachedPerson, DirtyMark, PartitionedCache, PersonCacheKey};
+use personhog_leader::settle::drop_settled_death_documents;
+
+use common::test_cached_person;
+
+const PARTITION: u32 = 0;
+
+fn death_doc(team_id: i64, person_id: i64, version: i64) -> CachedPerson {
+ CachedPerson {
+ id: person_id,
+ team_id,
+ version,
+ is_deleted: true,
+ properties: b"{}".to_vec(),
+ ..test_cached_person()
+ }
+}
+
+type LockMap = Arc<DashMap<PersonCacheKey, Arc<tokio::sync::Mutex<()>>>>;
+
+fn setup(entry: Option<CachedPerson>) -> (Arc<PartitionedCache>, LockMap, PersonCacheKey) {
+ let cache = Arc::new(PartitionedCache::new(1 << 20));
+ cache.create_partition(PARTITION);
+ let key = PersonCacheKey {
+ team_id: 7,
+ person_id: 42,
+ };
+ if let Some(entry) = entry {
+ cache.put(PARTITION, key.clone(), entry);
+ }
+ (cache, Arc::new(DashMap::new()), key)
+}
+
+fn pruned(key: &PersonCacheKey, version: i64) -> Vec<(PersonCacheKey, DirtyMark)> {
+ vec![(
+ key.clone(),
+ DirtyMark {
+ version,
+ offset: 9,
+ partition: PARTITION,
+ is_deleted: true,
+ },
+ )]
+}
+
+#[tokio::test]
+async fn a_settled_death_document_is_dropped() {
+ let (cache, locks, key) = setup(Some(death_doc(7, 42, 3)));
+
+ drop_settled_death_documents(&cache, &locks, &pruned(&key, 3)).await;
+
+ assert!(
+ cache.peek(PARTITION, &key).is_none(),
+ "the settled death document must be dropped so misses serve PG"
+ );
+}
+
+#[tokio::test]
+async fn a_newer_entry_survives_an_old_marks_settle() {
+ // A newer death document (its own mark still standing) must not be
+ // dropped by a superseded mark's prune.
+ let (cache, locks, key) = setup(Some(death_doc(7, 42, 9)));
+
+ drop_settled_death_documents(&cache, &locks, &pruned(&key, 3)).await;
+
+ assert!(
+ cache
+ .peek(PARTITION, &key)
+ .is_some_and(|entry| entry.version == 9),
+ "an entry other than the pruned mark's must never be dropped"
+ );
+}
+
+#[tokio::test]
+async fn a_live_person_survives_its_marks_settle() {
+ let live = CachedPerson {
+ is_deleted: false,
+ ..death_doc(7, 42, 3)
+ };
+ let (cache, locks, key) = setup(Some(live));
+
+ drop_settled_death_documents(&cache, &locks, &pruned(&key, 3)).await;
+
+ assert!(
+ cache.peek(PARTITION, &key).is_some(),
+ "settling a live person's mark drops nothing"
+ );
+}
+
+#[tokio::test]
+async fn the_drop_waits_for_the_per_key_lock() {
+ // Holding the person's lock holds the drop; the entry surviving while
+ // held is an invariant, not a timing bet.
+ let (cache, locks, key) = setup(Some(death_doc(7, 42, 3)));
+
+ let mutex = locks.entry(key.clone()).or_default().value().clone();
+ let held = mutex.lock().await;
+
+ let settling = tokio::spawn({
+ let (cache, locks, key) = (Arc::clone(&cache), Arc::clone(&locks), key.clone());
+ async move { drop_settled_death_documents(&cache, &locks, &pruned(&key, 3)).await }
+ });
+ tokio::task::yield_now().await;
+
+ assert!(
+ cache.peek(PARTITION, &key).is_some(),
+ "no drop may land while the per-key lock is held"
+ );
+
+ drop(held);
+ settling.await.expect("settle task");
+ assert!(
+ cache.peek(PARTITION, &key).is_none(),
+ "the drop lands once the lock frees"
+ );
+}
+
+#[tokio::test]
+async fn an_install_landing_mid_settle_is_still_dropped() {
+ // Absent at peek time: a recovery holds the lock and installs the
+ // death document before releasing. The settle must wait, not skip.
+ let (cache, locks, key) = setup(None);
+
+ let mutex = locks.entry(key.clone()).or_default().value().clone();
+ let held = mutex.lock().await;
+
+ let settling = tokio::spawn({
+ let (cache, locks, key) = (Arc::clone(&cache), Arc::clone(&locks), key.clone());
+ async move { drop_settled_death_documents(&cache, &locks, &pruned(&key, 3)).await }
+ });
+ tokio::task::yield_now().await;
+
+ cache.put(PARTITION, key.clone(), death_doc(7, 42, 3));
+ drop(held);
+
+ settling.await.expect("settle task");
+ assert!(
+ cache.peek(PARTITION, &key).is_none(),
+ "a death document installed while the settle waited must be dropped"
+ );
+}
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index b6674ca433f3..901806879b4e 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -159,6 +159,7 @@ async fn warming_handles_empty_partition() {
// The empty path must return its consumer to the pool, not drop it —
// a second empty warm reuses the same client instead of creating one.
let created_after_first = pools.warming.created_count();
+ cache.drop_partition(0);
warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("second empty warm should succeed");
@@ -519,6 +520,104 @@ async fn warming_seeds_dirty_index_only_at_or_past_the_committed_offset() {
}
}
+/// An applied death record must leave no residue in the warmed cache:
+/// not the death document (unmarked, it would answer not-found forever
+/// while PG may already hold a revival), and not the same key's earlier
+/// live record (it would resurrect the destroyed person's data). A live
+/// applied record of another key still warms.
+#[tokio::test]
+async fn warming_skips_applied_death_records() {
+ let (cluster, producer) = create_test_kafka().await;
+
+ // Key 1: live then death. Key 2: live only. Key 3: live, death,
+ // then a revival record.
+ produce_person_to_partition(&producer, 0, &make_person(1, 1)).await;
+ let mut dead = make_person(1, 1);
+ dead.is_deleted = true;
+ dead.version = 2;
+ produce_person_to_partition(&producer, 0, &dead).await;
+ produce_person_to_partition(&producer, 0, &make_person(1, 2)).await;
+ produce_person_to_partition(&producer, 0, &make_person(1, 3)).await;
+ let mut dead3 = make_person(1, 3);
+ dead3.is_deleted = true;
+ dead3.version = 2;
+ produce_person_to_partition(&producer, 0, &dead3).await;
+ let mut revived3 = make_person(1, 3);
+ revived3.version = 3;
+ produce_person_to_partition(&producer, 0, &revived3).await;
+ // Key 4: an unapplied death record (at the committed offset).
+ let mut dead4 = make_person(1, 4);
+ dead4.is_deleted = true;
+ dead4.version = 2;
+ produce_person_to_partition(&producer, 0, &dead4).await;
+
+ // Records at offsets 0..6 are applied; key 4's death record is not.
+ commit_writer_offset_at(&cluster, "personhog-writer", 0, 6);
+
+ let cache = PartitionedCache::new(1 << 20);
+ let dirty_index = DirtyIndex::new(1_000_000);
+ let (mut cfg, pools) = warming_config_for("warmer-skip-dead", &cluster);
+ cfg.lookback_offsets = 7;
+
+ warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0)
+ .await
+ .expect("warming should succeed");
+
+ let dead_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 1,
+ };
+ let live_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 2,
+ };
+ assert!(
+ matches!(cache.get(0, &dead_key), CacheLookup::PersonNotFound),
+ "an applied death record must leave no residue: neither itself nor its live predecessor"
+ );
+ assert!(
+ matches!(cache.get(0, &live_key), CacheLookup::Found(_)),
+ "an applied live record still warms"
+ );
+ let revived_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 3,
+ };
+ match cache.get(0, &revived_key) {
+ CacheLookup::Found(entry) => {
+ assert_eq!(
+ entry.version, 3,
+ "the revival record warms after its death record"
+ );
+ assert!(!entry.is_deleted);
+ }
+ other => panic!(
+ "a revived key must warm, got {:?}",
+ std::mem::discriminant(&other)
+ ),
+ }
+ assert!(dirty_index.get(&dead_key).is_none());
+ assert!(dirty_index.get(&live_key).is_none());
+ assert!(dirty_index.get(&revived_key).is_none());
+ // An unapplied death record warms in and is marked: the writer has
+ // not applied it, so PG still holds the living person.
+ let unapplied_dead_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 4,
+ };
+ match cache.get(0, &unapplied_dead_key) {
+ CacheLookup::Found(entry) => assert!(entry.is_deleted),
+ other => panic!(
+ "an unapplied death record must warm in, got {:?}",
+ std::mem::discriminant(&other)
+ ),
+ }
+ let mark = dirty_index
+ .get(&unapplied_dead_key)
+ .expect("an unapplied death record must be marked");
+ assert!(mark.is_deleted);
+}
+
/// Warming must seed the dirty index for every record the writer has not
/// applied — with no committed offset at all, that is every record — so a
/// post-warm eviction still recovers from the changelog instead of
@@ -567,6 +666,8 @@ async fn sequential_warms_reuse_pooled_clients() {
let (cfg, pools) = warming_config_for("warmer-pool", &cluster);
for partition in [0u32, 1, 0, 1] {
+ // A re-warm follows a release in production; drop to match.
+ cache.drop_partition(partition);
warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), partition)
.await
.expect("warming should succeed");
@@ -742,3 +843,145 @@ async fn warming_a_range_larger_than_the_budget_marks_every_person() {
if everything fit, this test no longer exercises eviction"
);
}
+
+/// The tick settles a published partition's applied death mark, while a
+/// warming partition keeps its marks until publish.
+#[tokio::test]
+async fn the_prune_tick_settles_published_partitions_only() {
+ let (cluster, _producer) = create_test_kafka().await;
+ let (_cfg, pools) = warming_config_for("prune-tick", &cluster);
+
+ let cache = PartitionedCache::new(1 << 20);
+ let dirty_index = DirtyIndex::new(1_000_000);
+ let locks = dashmap::DashMap::new();
+
+ let death_doc = |person_id: i64| {
+ let mut person = make_person(1, person_id);
+ person.is_deleted = true;
+ person.version = 2;
+ personhog_leader::cache::CachedPerson::try_from(person).unwrap()
+ };
+ let death_mark = |partition: u32| personhog_leader::cache::DirtyMark {
+ version: 2,
+ offset: 0,
+ partition,
+ is_deleted: true,
+ };
+ let published_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 1,
+ };
+ let warming_key = PersonCacheKey {
+ team_id: 1,
+ person_id: 2,
+ };
+
+ cache.create_partition(0);
+ cache.put(0, published_key.clone(), death_doc(1));
+ dirty_index.mark(published_key.clone(), death_mark(0));
+
+ cache.begin_warm_partition(1);
+ cache.warm_put(1, warming_key.clone(), death_doc(2));
+ dirty_index.mark(warming_key.clone(), death_mark(1));
+
+ commit_writer_offset_at(&cluster, "personhog-writer", 0, 1);
+ commit_writer_offset_at(&cluster, "personhog-writer", 1, 1);
+
+ personhog_leader::settle::prune_and_settle_tick(
+ &dirty_index,
+ &cache,
+ &locks,
+ &pools.offsets,
+ CHANGELOG_TOPIC,
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("offset fetch succeeds");
+
+ assert!(dirty_index.get(&published_key).is_none());
+ assert!(
+ cache.peek(0, &published_key).is_none(),
+ "the published partition's death document settles"
+ );
+ assert!(
+ dirty_index.get(&warming_key).is_some(),
+ "a warming partition keeps its marks until publish"
+ );
+
+ // After publish, the next tick settles the waiting mark.
+ cache.publish_warmed_partition(1);
+ personhog_leader::settle::prune_and_settle_tick(
+ &dirty_index,
+ &cache,
+ &locks,
+ &pools.offsets,
+ CHANGELOG_TOPIC,
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("offset fetch succeeds");
+ assert!(dirty_index.get(&warming_key).is_none());
+ assert!(cache.peek(1, &warming_key).is_none());
+}
+
+/// One tick drains a death backlog larger than a prune chunk: the chunk
+/// loop must run to exhaustion, not stop after the first slice.
+#[tokio::test]
+async fn the_prune_tick_drains_a_multi_chunk_death_backlog() {
+ let (cluster, _producer) = create_test_kafka().await;
+ let (_cfg, pools) = warming_config_for("prune-tick-backlog", &cluster);
+
+ let cache = PartitionedCache::new(1 << 20);
+ let dirty_index = DirtyIndex::new(usize::MAX);
+ let locks = dashmap::DashMap::new();
+ cache.create_partition(0);
+
+ let total = personhog_leader::cache::PRUNE_CHUNK as i64 + 1;
+ for offset in 0..total {
+ let mut person = make_person(1, offset);
+ person.is_deleted = true;
+ person.version = 2;
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: offset,
+ };
+ cache.put(
+ 0,
+ key.clone(),
+ personhog_leader::cache::CachedPerson::try_from(person).unwrap(),
+ );
+ dirty_index.mark(
+ key,
+ personhog_leader::cache::DirtyMark {
+ version: 2,
+ offset,
+ partition: 0,
+ is_deleted: true,
+ },
+ );
+ }
+ commit_writer_offset_at(&cluster, "personhog-writer", 0, total);
+
+ personhog_leader::settle::prune_and_settle_tick(
+ &dirty_index,
+ &cache,
+ &locks,
+ &pools.offsets,
+ CHANGELOG_TOPIC,
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("offset fetch succeeds");
+
+ assert!(dirty_index.is_empty(), "every mark settles in one tick");
+ for person_id in [0, total / 2, total - 1] {
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id,
+ };
+ assert!(
+ cache.peek(0, &key).is_none(),
+ "death document for person {person_id} must be dropped"
+ );
+ }
+}