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): verify delete releases from one mark read per op (#101972)

Zach Brown5848566b2adc
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index a098d9395673..7724175f3218 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -111,6 +111,7 @@ Several failure modes are handled explicitly:
- **Zombie writes: closed behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode. The lane count (`FENCING_LANES`) binds the same way: a takeover fences one transactional id per lane, so while a roll mixes lane counts, a successor on the smaller count leaves a predecessor's extra lanes unfenced, and only the lease gate bounds what those lanes can still commit.
- **Zombie reads: closed behind `LEASE_GATED_AUTHORITY` (default off).** The keepalive publishes its last confirmed renewal and the request path refuses once that stamp is older than the renewal margin — checked at admission and again before answering, since the claim can lapse while a read is served. A stalled keepalive therefore fences implicitly. The model confirms fencing and the gate are complementary rather than alternative: each alone leaves stale reads; only together does every safety property hold.
- *Residual, recorded because the model's `serve_read` points here:* the closure is only as prompt as the claim's lapse. Natural expiry always lapses the stamp before etcd deletes anything, but an out-of-band *revocation* removes the registration while the stamp is still fresh, and only the deliberately best-effort registration watch converts that into an immediate surrender. With the watch dead, the stamp stays valid for up to one heartbeat (`prompt_detection_is_what_makes_the_read_gate_hold` pins exactly this). No production path revokes another pod's lease, so reaching the window takes an operator.
+- **A release's mark check leans on the gate too.** The leader answers a committed release from the op's mark snapshot for a fence it sealed before the snapshot was read. A zombie's sealed fences and snapshot outlive its authority, so with the gate off a release it should no longer serve can trust a pre-settle snapshot where the row would have said deleted; with the gate on, admission refuses it.
- **Acquisition is gated on the same claim.** A zombie waking inside its lease window would otherwise re-acquire the partition's transactional id on its way to noticing it is dead, fencing the legitimate owner — the broker grants the epoch to whoever initializes last. Warming and resume consult the authority stamp before acquiring and again after, dropping the fence rather than building on a claim they no longer hold. The e2e zombie gate manufactures the waking-zombie shape and asserts by consequence; the per-arm rejection coverage lives in the deterministic fencing integration tests. Because the two mechanisms only work together, `KAFKA_TRANSACTIONAL_FENCING` is refused at startup without `LEASE_GATED_AUTHORITY`.
- **A condemned producer heals in place.** An abort that did not land, or a commit whose outcome stayed unknown, leaves a producer no later window can be begun from. It is condemned and given up on the next write, which answers as unowned (`FailedPrecondition`, the router's bounce class) rather than as a retryable failure, and the serving-side verification re-acquires on the next convergence tick — gated on the authority stamp, which is what gives a pod the standing to bump the epoch.
- **A commit outlives the request that started it.** A request cancelled mid-produce loses its handler, but the produce runs as its own task holding the person lock and the drain's in-flight count, so the record lands in the cache in version order and the drain waits for it like any other write. The drain still settles (bounded, best-effort, never failing the drain) a window nobody waits on before acking, which a failed send leaves behind for the committer to abort; the successor's `init_transactions` aborts whatever could not settle — safe in either ordering, because the transaction coordinator serializes the in-flight commit against the successor's init on the shared transactional id.
diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rs
index cd752a80430a..7167fef2e589 100644
--- a/rust/personhog-leader/src/fence.rs
+++ b/rust/personhog-leader/src/fence.rs
@@ -8,11 +8,10 @@
//! in-process copy, and on the write path it is authoritative: a fenced
//! write is rejected from memory alone, never a database read.
//!
-//! Postgres is read in exactly one place — the takeover scan, once per
-//! partition acquisition, before the partition accepts writes. That plus
-//! the `FencePerson` RPC are the only two ways an entry gets in, and
-//! together they cover every mark. Entries leave in exactly two ways: a
-//! `ReleaseFence`, or dropping the whole partition.
+//! Postgres is read off the write path only: the takeover scan before a
+//! partition serves, the heal below, and a release's mark check. The scan
+//! and the `FencePerson` RPC are the only ways an entry gets in; a
+//! `ReleaseFence`, a partition drop, or the heal takes it out.
//!
//! The leader never reclaims a fence on its own, and deliberately so.
//! personhog-identity owns lifecycle correctness: every op is driven to a
@@ -41,12 +40,15 @@
//! partition to change hands.
use std::collections::HashMap;
-use std::sync::Arc;
-use std::time::Duration;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, PoisonError};
+use std::time::{Duration, Instant};
+use async_trait::async_trait;
use dashmap::DashMap;
use metrics::{counter, gauge, histogram};
-use sqlx::Row;
+use sqlx::{PgPool, Row};
+use tokio::sync::OnceCell;
use tonic::Status;
use uuid::Uuid;
@@ -56,11 +58,13 @@ use personhog_proto::personhog::types::v1::LifecycleOpType;
use crate::cache::PersonCacheKey;
use crate::pg::PgFallback;
-/// A person's live fence: the operation that froze it.
+/// A person's live fence: the operation that froze it, and when this pod
+/// sealed it. A takeover fence, rebuilt from the rows, has no seal time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FenceState {
pub op_id: Uuid,
pub op_type: LifecycleOpType,
+ pub sealed_at: Option<Instant>,
}
pub type FenceMap = Arc<DashMap<PersonCacheKey, FenceState>>;
@@ -186,6 +190,7 @@ pub async fn rebuild_partition_fences(
FenceState {
op_id: row.get("op_id"),
op_type: LifecycleOpType::from_op_type_str(&op_type),
+ sealed_at: None,
},
);
installed += 1;
@@ -343,30 +348,6 @@ pub async fn mark_status(
.await
}
-/// [`mark_status`] for a whole batch in one pool acquire, keyed by person
-/// id. A person with no row is absent from the map, which the caller
-/// reads as it reads `None` from the single lookup.
-pub async fn mark_statuses(
- fallback: &PgFallback,
- op_id: Uuid,
- team_id: i64,
- person_ids: &[i64],
-) -> Result<HashMap<i64, String>, sqlx::Error> {
- let mut conn = crate::pg::acquire_timed(&fallback.pool, "mark_statuses").await?;
- let sql = format!(
- "SELECT person_id, status FROM {} \
- WHERE op_id = $1 AND team_id = $2 AND person_id = ANY($3) AND role <> 'target'",
- fallback.lifecycle.op_person
- );
- let rows: Vec<(i64, String)> = sqlx::query_as(&sql)
- .bind(op_id)
- .bind(team_id as i32)
- .bind(person_ids)
- .fetch_all(&mut *conn)
- .await?;
- Ok(rows.into_iter().collect())
-}
-
/// The fold's check: the status of the op's mark row claiming this person
/// as its merge target. `None` when the op never claimed the person as
/// target — including when it holds the person under another role, which
@@ -395,3 +376,338 @@ pub async fn target_mark_status(
.fetch_optional(&mut *conn)
.await
}
+
+/// A memory bound only; what a snapshot may vouch for does not depend on its age.
+const MARK_SNAPSHOT_TTL: Duration = Duration::from_secs(30);
+
+/// Keeps the snapshot map bounded without a sweeper task.
+const MARK_SNAPSHOT_PRUNE_THRESHOLD: usize = 1_000;
+
+/// Paces the prune scan under a burst of fresh snapshots.
+const MARK_SNAPSHOT_PRUNE_INTERVAL: Duration = Duration::from_secs(5);
+
+const MARK_SNAPSHOTS_TOTAL: &str = "personhog_leader_mark_snapshots_total";
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct MarkRow {
+ pub team_id: i64,
+ pub person_id: i64,
+ pub status: String,
+}
+
+#[async_trait]
+pub trait MarkSource: Send + Sync {
+ async fn load_op(&self, op_id: Uuid) -> Result<Vec<MarkRow>, sqlx::Error>;
+}
+
+/// Merge targets are excluded because targets are never destroyed.
+pub struct PgMarkSource {
+ pool: PgPool,
+ op_person_table: String,
+}
+
+#[async_trait]
+impl MarkSource for PgMarkSource {
+ async fn load_op(&self, op_id: Uuid) -> Result<Vec<MarkRow>, sqlx::Error> {
+ let mut conn = crate::pg::acquire_timed(&self.pool, "mark_snapshot").await?;
+ let sql = format!(
+ "SELECT team_id, person_id, status FROM {} \
+ WHERE op_id = $1 AND role <> 'target'",
+ self.op_person_table
+ );
+ let rows = sqlx::query(&sql).bind(op_id).fetch_all(&mut *conn).await?;
+ Ok(rows
+ .into_iter()
+ .map(|row| MarkRow {
+ team_id: i64::from(row.get::<i32, _>("team_id")),
+ person_id: row.get("person_id"),
+ status: row.get("status"),
+ })
+ .collect())
+ }
+}
+
+/// The op's mark rows as of one read.
+#[derive(Debug)]
+pub struct MarkSnapshot {
+ fetched_at: Instant,
+ rows: HashMap<(i64, i64), String>,
+}
+
+impl MarkSnapshot {
+ /// A fence this pod sealed before the read and that still stands; a
+ /// takeover fence never qualifies.
+ pub fn vouches_for(&self, fence: &FenceState) -> bool {
+ fence
+ .sealed_at
+ .is_some_and(|sealed_at| sealed_at < self.fetched_at)
+ }
+
+ pub fn status(&self, team_id: i64, person_id: i64) -> Option<&str> {
+ self.rows.get(&(team_id, person_id)).map(String::as_str)
+ }
+}
+
+/// The op's mark rows, read once per op per pod. The row still has to
+/// vouch for the (op, person) pair.
+pub struct MarkVerifier {
+ source: Arc<dyn MarkSource>,
+ ttl: Duration,
+ snapshots: DashMap<Uuid, Arc<OnceCell<Arc<MarkSnapshot>>>>,
+ last_prune: Mutex<Instant>,
+}
+
+impl MarkVerifier {
+ pub fn new(fallback: &PgFallback) -> Self {
+ let source = PgMarkSource {
+ pool: fallback.pool.clone(),
+ op_person_table: fallback.lifecycle.op_person.clone(),
+ };
+ Self::with_source(Arc::new(source), MARK_SNAPSHOT_TTL)
+ }
+
+ pub fn with_source(source: Arc<dyn MarkSource>, ttl: Duration) -> Self {
+ Self {
+ source,
+ ttl,
+ snapshots: DashMap::new(),
+ last_prune: Mutex::new(Instant::now()),
+ }
+ }
+
+ /// The op's snapshot, shared by every release that arrives while it is
+ /// fresh. A failed load leaves the cell empty for the next call to retry.
+ pub async fn snapshot(&self, op_id: Uuid) -> Result<Arc<MarkSnapshot>, sqlx::Error> {
+ loop {
+ let cell = self.cell(op_id);
+ let loaded_now = AtomicBool::new(false);
+ let snapshot = cell
+ .get_or_try_init(|| async {
+ loaded_now.store(true, Ordering::Relaxed);
+ counter!(MARK_SNAPSHOTS_TOTAL, "outcome" => "load").increment(1);
+ // Taken before the read, so a fence sealed earlier predates every row.
+ let fetched_at = Instant::now();
+ let rows = self.source.load_op(op_id).await?;
+ Ok::<_, sqlx::Error>(Arc::new(MarkSnapshot {
+ fetched_at,
+ rows: rows
+ .into_iter()
+ .map(|row| ((row.team_id, row.person_id), row.status))
+ .collect(),
+ }))
+ })
+ .await?;
+ if loaded_now.load(Ordering::Relaxed) {
+ return Ok(Arc::clone(snapshot));
+ }
+ // Only a snapshot someone else loaded can expire here, so a TTL
+ // shorter than one load cannot make this loop spin.
+ if snapshot.fetched_at.elapsed() > self.ttl {
+ counter!(MARK_SNAPSHOTS_TOTAL, "outcome" => "expired").increment(1);
+ self.snapshots
+ .remove_if(&op_id, |_, current| Arc::ptr_eq(current, &cell));
+ continue;
+ }
+ counter!(MARK_SNAPSHOTS_TOTAL, "outcome" => "hit").increment(1);
+ return Ok(Arc::clone(snapshot));
+ }
+ }
+
+ fn cell(&self, op_id: Uuid) -> Arc<OnceCell<Arc<MarkSnapshot>>> {
+ if let Some(cell) = self.snapshots.get(&op_id) {
+ return Arc::clone(&cell);
+ }
+ if self.snapshots.len() >= MARK_SNAPSHOT_PRUNE_THRESHOLD {
+ let mut last_prune = self
+ .last_prune
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ if last_prune.elapsed() >= MARK_SNAPSHOT_PRUNE_INTERVAL {
+ let ttl = self.ttl;
+ // A cell still loading goes too; its waiters hold their own handle.
+ self.snapshots.retain(|_, cell| {
+ cell.get()
+ .is_some_and(|snapshot| snapshot.fetched_at.elapsed() <= ttl)
+ });
+ *last_prune = Instant::now();
+ }
+ }
+ Arc::clone(&self.snapshots.entry(op_id).or_default())
+ }
+}
+
+#[cfg(test)]
+mod mark_verifier_tests {
+ use std::sync::atomic::AtomicUsize;
+
+ use super::*;
+
+ struct CountingSource {
+ rows: Vec<MarkRow>,
+ loads: AtomicUsize,
+ fail_next_load: AtomicBool,
+ }
+
+ impl CountingSource {
+ fn sealed(persons: i64) -> Arc<Self> {
+ Arc::new(Self {
+ rows: (1..=persons)
+ .map(|person_id| MarkRow {
+ team_id: 1,
+ person_id,
+ status: "sealed".to_string(),
+ })
+ .collect(),
+ loads: AtomicUsize::new(0),
+ fail_next_load: AtomicBool::new(false),
+ })
+ }
+
+ fn loads(&self) -> usize {
+ self.loads.load(Ordering::SeqCst)
+ }
+ }
+
+ #[async_trait]
+ impl MarkSource for CountingSource {
+ async fn load_op(&self, _op_id: Uuid) -> Result<Vec<MarkRow>, sqlx::Error> {
+ self.loads.fetch_add(1, Ordering::SeqCst);
+ if self.fail_next_load.swap(false, Ordering::SeqCst) {
+ return Err(sqlx::Error::PoolTimedOut);
+ }
+ Ok(self.rows.clone())
+ }
+ }
+
+ #[tokio::test]
+ async fn releases_of_one_op_share_one_load_and_unknown_persons_stay_unverified() {
+ let source = CountingSource::sealed(50);
+ let verifier = Arc::new(MarkVerifier::with_source(source.clone(), MARK_SNAPSHOT_TTL));
+ let op = Uuid::now_v7();
+
+ let mut releases = tokio::task::JoinSet::new();
+ for person_id in 1..=50 {
+ let verifier = Arc::clone(&verifier);
+ releases.spawn(async move {
+ verifier
+ .snapshot(op)
+ .await
+ .map(|snapshot| snapshot.status(1, person_id).map(str::to_owned))
+ });
+ }
+ while let Some(joined) = releases.join_next().await {
+ let status = joined.expect("lookup task").expect("lookup succeeds");
+ assert_eq!(status.as_deref(), Some("sealed"));
+ }
+ assert_eq!(source.loads(), 1, "one load serves every victim of the op");
+
+ let snapshot = verifier.snapshot(op).await.expect("lookup succeeds");
+ assert_eq!(
+ snapshot.status(1, 51),
+ None,
+ "a person the op never claimed is unverified"
+ );
+ assert_eq!(
+ snapshot.status(2, 1),
+ None,
+ "the row must match the team too"
+ );
+ assert_eq!(source.loads(), 1);
+ }
+
+ #[test]
+ fn a_snapshot_vouches_only_for_a_fence_sealed_before_its_read() {
+ let read = Instant::now();
+ let snapshot = MarkSnapshot {
+ fetched_at: read,
+ rows: HashMap::new(),
+ };
+ let fence = |sealed_at| FenceState {
+ op_id: Uuid::nil(),
+ op_type: LifecycleOpType::Delete,
+ sealed_at,
+ };
+ assert!(snapshot.vouches_for(&fence(Some(read - Duration::from_millis(1)))));
+ assert!(!snapshot.vouches_for(&fence(Some(read + Duration::from_millis(1)))));
+ assert!(!snapshot.vouches_for(&fence(None)));
+ }
+
+ #[tokio::test]
+ async fn an_expired_snapshot_is_read_again() {
+ let source = CountingSource::sealed(1);
+ let verifier = MarkVerifier::with_source(source.clone(), Duration::ZERO);
+ let op = Uuid::now_v7();
+
+ verifier.snapshot(op).await.expect("first lookup");
+ assert_eq!(source.loads(), 1, "the loader keeps its own snapshot");
+ let snapshot = verifier.snapshot(op).await.expect("second lookup");
+ assert_eq!(snapshot.status(1, 1), Some("sealed"));
+ assert_eq!(source.loads(), 2, "an expired snapshot is replaced");
+ }
+
+ #[tokio::test]
+ async fn a_failed_load_is_retried_by_the_next_release() {
+ let source = CountingSource::sealed(1);
+ source.fail_next_load.store(true, Ordering::SeqCst);
+ let verifier = MarkVerifier::with_source(source.clone(), MARK_SNAPSHOT_TTL);
+ let op = Uuid::now_v7();
+
+ verifier
+ .snapshot(op)
+ .await
+ .expect_err("the failed load surfaces to the release");
+ let snapshot = verifier.snapshot(op).await.expect("second lookup");
+ assert_eq!(snapshot.status(1, 1), Some("sealed"));
+ assert_eq!(source.loads(), 2, "nothing from the failed load is trusted");
+ }
+
+ #[tokio::test]
+ async fn a_fence_sealed_during_the_read_is_not_vouched_for() {
+ struct RecordingSource(Mutex<Option<Instant>>);
+
+ #[async_trait]
+ impl MarkSource for RecordingSource {
+ async fn load_op(&self, _op_id: Uuid) -> Result<Vec<MarkRow>, sqlx::Error> {
+ *self.0.lock().unwrap() = Some(Instant::now());
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ Ok(Vec::new())
+ }
+ }
+
+ let source = Arc::new(RecordingSource(Mutex::new(None)));
+ let verifier = MarkVerifier::with_source(source.clone(), MARK_SNAPSHOT_TTL);
+ let snapshot = verifier.snapshot(Uuid::now_v7()).await.expect("load");
+ let sealed_during_read = source.0.lock().unwrap().expect("the source was read");
+ assert!(!snapshot.vouches_for(&FenceState {
+ op_id: Uuid::nil(),
+ op_type: LifecycleOpType::Delete,
+ sealed_at: Some(sealed_during_read),
+ }));
+ }
+
+ #[tokio::test]
+ async fn the_prune_runs_on_an_interval_and_drops_cells_that_never_loaded() {
+ let source = CountingSource::sealed(1);
+ let verifier = MarkVerifier::with_source(source, Duration::ZERO);
+ for _ in 0..MARK_SNAPSHOT_PRUNE_THRESHOLD {
+ verifier.snapshot(Uuid::now_v7()).await.expect("load");
+ }
+ verifier.cell(Uuid::now_v7());
+ assert_eq!(verifier.snapshots.len(), MARK_SNAPSHOT_PRUNE_THRESHOLD + 1);
+
+ verifier.snapshot(Uuid::now_v7()).await.expect("load");
+ assert_eq!(
+ verifier.snapshots.len(),
+ MARK_SNAPSHOT_PRUNE_THRESHOLD + 2,
+ "no scan inside the interval"
+ );
+
+ *verifier.last_prune.lock().unwrap() = Instant::now() - MARK_SNAPSHOT_PRUNE_INTERVAL;
+ verifier.snapshot(Uuid::now_v7()).await.expect("load");
+ assert_eq!(
+ verifier.snapshots.len(),
+ 1,
+ "expired snapshots and the cell that never loaded go; the new op's stays"
+ );
+ }
+}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index c814bfa278c6..0a6016e49650 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -27,6 +27,7 @@ use crate::cache::{
use crate::emitted::{EmittedVersionGuard, EmittedVersions};
use crate::fence::{
fenced_status, semantic_refusal, target_mark_status, FenceHealer, FenceMap, FenceState,
+ MarkVerifier,
};
use crate::fencing::{FencedChangelogProducers, FencedProduceError};
use crate::inflight::{InflightGuard, InflightTracker};
@@ -126,6 +127,9 @@ pub struct PersonHogLeaderService {
/// construction. Absent without one (dev fixtures) — ghost fences
/// then last until the partition changes hands, as before.
fence_healer: Option<Arc<FenceHealer>>,
+ /// The committed-release mark check, one query per op per pod. Absent
+ /// without a fallback pool, in which case a release is refused.
+ mark_verifier: Option<MarkVerifier>,
/// Memory fuse for the fence map (see `fence_map_max_entries` in the
/// config for the full policy): at this many live fences, FencePerson
/// sheds new fences with RESOURCE_EXHAUSTED.
@@ -238,6 +242,7 @@ impl PersonHogLeaderService {
fence_healer: fallback
.as_ref()
.map(|f| Arc::new(FenceHealer::new(f.clone(), Arc::clone(&fences)))),
+ mark_verifier: fallback.as_ref().map(MarkVerifier::new),
fallback,
inflight,
num_partitions,
@@ -2208,6 +2213,7 @@ mod tests {
FenceState {
op_id,
op_type: LifecycleOpType::Delete,
+ sealed_at: None,
},
);
@@ -2267,6 +2273,7 @@ mod tests {
FenceState {
op_id,
op_type: LifecycleOpType::Delete,
+ sealed_at: None,
},
);
diff --git a/rust/personhog-leader/src/service/lifecycle.rs b/rust/personhog-leader/src/service/lifecycle.rs
index 0b1d39a59270..5824de382c97 100644
--- a/rust/personhog-leader/src/service/lifecycle.rs
+++ b/rust/personhog-leader/src/service/lifecycle.rs
@@ -2,6 +2,7 @@
//! seals its state, and a release closes the fence with the op's outcome.
//! The single-call and batch handlers share the per-person helpers here.
+use std::sync::Arc;
use std::time::Instant;
use futures::StreamExt;
@@ -16,7 +17,9 @@ use tonic::{Request, Response, Status};
use uuid::Uuid;
use crate::cache::{approx_person_bytes, CachedPerson, PersonCacheKey};
-use crate::fence::{fenced_status, mark_status, mark_statuses, semantic_refusal, FenceState};
+use crate::fence::{
+ fenced_status, mark_status, semantic_refusal, FenceState, MarkSnapshot, MarkVerifier,
+};
use crate::pg::PgFallback;
use super::{cached_person_to_proto, partition_from_metadata, PersonHogLeaderService};
@@ -108,27 +111,44 @@ fn record_release_phase(phase: &'static str, started: Instant) {
.record(started.elapsed().as_secs_f64() * 1000.0);
}
+fn no_lifecycle_db() -> Status {
+ semantic_refusal(
+ "no lifecycle database configured; refusing to produce a death document",
+ "no-lifecycle-db",
+ )
+}
+
impl PersonHogLeaderService {
#[allow(clippy::result_large_err)]
fn lifecycle_db(&self) -> Result<&PgFallback, Status> {
- self.fallback.as_ref().ok_or_else(|| {
- semantic_refusal(
- "no lifecycle database configured; refusing to produce a death document",
- "no-lifecycle-db",
- )
- })
+ self.fallback.as_ref().ok_or_else(no_lifecycle_db)
+ }
+
+ #[allow(clippy::result_large_err)]
+ fn mark_verifier(&self) -> Result<&MarkVerifier, Status> {
+ self.mark_verifier.as_ref().ok_or_else(no_lifecycle_db)
+ }
+
+ /// The op's marks, read once per op per pod.
+ async fn mark_snapshot(&self, op_id: Uuid) -> Result<Arc<MarkSnapshot>, Status> {
+ let verifier = self.mark_verifier()?;
+ let started = Instant::now();
+ let snapshot = verifier.snapshot(op_id).await.map_err(mark_lookup_failed);
+ record_release_phase("snapshot", started);
+ snapshot
}
- /// The committed half of a release for one person, given its mark
- /// row's status. Shared by `ReleaseFence` and `ReleaseFences` so what
- /// destroys a person is decided in one place.
+ /// The committed half of a release for one person, verified against
+ /// the op's snapshot or its own mark row. Shared by `ReleaseFence` and
+ /// `ReleaseFences` so what destroys a person is decided in one place.
async fn release_committed(
&self,
partition: u32,
team_id: i64,
op_id: Uuid,
release: &CommittedRelease,
- mark: Option<&str>,
+ snapshot: &MarkSnapshot,
+ lifecycle_db: &PgFallback,
) -> Result<(), Status> {
let cache_key = PersonCacheKey {
team_id,
@@ -145,10 +165,9 @@ impl PersonHogLeaderService {
record_release_phase("lock_wait", lock_started);
// Releasing another op's fence would break that op's seal.
- if let Some(entry) = self.fences.get(&cache_key) {
- if entry.op_id != op_id {
- return Err(fenced_status(entry.value()));
- }
+ let fence = self.fences.get(&cache_key).map(|entry| *entry.value());
+ if let Some(fence) = fence.filter(|fence| fence.op_id != op_id) {
+ return Err(fenced_status(&fence));
}
// Release must stay idempotent for the saga's retry and the
@@ -184,10 +203,19 @@ impl PersonHogLeaderService {
}
}
- // The mark row must vouch for the op before anything is destroyed:
- // the in-memory fence was installed on the request's word alone, so
- // request plus fence is never enough. Unverifiable is refused.
- match mark {
+ // The op's mark must vouch before anything is destroyed; the fence
+ // stands on the request's word alone, and unverifiable is refused.
+ let mark = if fence.is_some_and(|fence| snapshot.vouches_for(&fence)) {
+ snapshot
+ .status(team_id, release.person_id)
+ .map(str::to_owned)
+ } else {
+ let read_started = Instant::now();
+ let mark = mark_status(lifecycle_db, op_id, team_id, release.person_id).await;
+ record_release_phase("verify_mark", read_started);
+ mark.map_err(mark_lookup_failed)?
+ };
+ match mark.as_deref() {
// A live mark: the op holds the person; proceed.
Some("marked") | Some("sealed") => {}
// The mark already settled as deleted: this release
@@ -325,7 +353,18 @@ impl PersonHogLeaderService {
.emitted_versions
.floor_for(partition, &cache_key, person.version);
- self.fences.insert(cache_key, FenceState { op_id, op_type });
+ // A same-op re-fence leaves the fence alone: a fresh seal time would
+ // turn a takeover fence into one the op's snapshot may vouch for.
+ if !refence {
+ self.fences.insert(
+ cache_key,
+ FenceState {
+ op_id,
+ op_type,
+ sealed_at: Some(Instant::now()),
+ },
+ );
+ }
counter!("personhog_leader_fences_total", "action" => "fenced").increment(1);
Ok(sealed)
}
@@ -498,12 +537,16 @@ impl PersonHogLeaderService {
)));
};
let lifecycle_db = self.lifecycle_db()?;
- let verify_started = Instant::now();
- let mark = mark_status(lifecycle_db, op_id, req.team_id, req.person_id).await;
- record_release_phase("verify_mark", verify_started);
- let mark = mark.map_err(mark_lookup_failed)?;
- self.release_committed(partition, req.team_id, op_id, &release, mark.as_deref())
- .await?;
+ let snapshot = self.mark_snapshot(op_id).await?;
+ self.release_committed(
+ partition,
+ req.team_id,
+ op_id,
+ &release,
+ &snapshot,
+ lifecycle_db,
+ )
+ .await?;
}
ReleaseOutcome::Aborted => {
self.release_aborted(partition, req.team_id, req.person_id, op_id)
@@ -568,19 +611,21 @@ impl PersonHogLeaderService {
)));
};
let lifecycle_db = self.lifecycle_db()?;
- let person_ids: Vec<i64> = releases.iter().map(|r| r.person_id).collect();
- let verify_started = Instant::now();
- let marks = mark_statuses(lifecycle_db, op_id, team_id, &person_ids).await;
- record_release_phase("verify_mark", verify_started);
- let marks = marks.map_err(mark_lookup_failed)?;
+ let snapshot = self.mark_snapshot(op_id).await?;
// The releases run together so their death documents share
// fencing windows, and every one runs to completion: a
// sibling's failure cancels no produce in flight.
let release_futures: Vec<_> = releases
.iter()
.map(|release| {
- let mark = marks.get(&release.person_id).map(String::as_str);
- self.release_committed(partition, team_id, op_id, release, mark)
+ self.release_committed(
+ partition,
+ team_id,
+ op_id,
+ release,
+ &snapshot,
+ lifecycle_db,
+ )
})
.collect();
let results: Vec<_> = futures::stream::iter(release_futures)
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index 04447ac498d0..3ce09c6a4dc8 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -14,9 +14,13 @@ use common::{
unique_team_id, CHANGELOG_TOPIC, NUM_PARTITIONS,
};
use personhog_common::partitioning::partition_for_person;
-use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey};
+use personhog_leader::cache::{
+ CacheLookup, CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey,
+};
use personhog_leader::emitted::EmittedVersions;
-use personhog_leader::fence::{FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY};
+use personhog_leader::fence::{
+ rebuild_partition_fences, FenceMap, FENCED_METADATA_KEY, FENCED_OP_ID_METADATA_KEY,
+};
use personhog_leader::inflight::InflightTracker;
use personhog_leader::pg::{LifecycleTables, PgFallback};
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
@@ -84,6 +88,7 @@ struct FenceHarness {
emitted_versions: Arc<EmittedVersions>,
dirty_index: Arc<DirtyIndex>,
locks: Arc<DashMap<PersonCacheKey, Arc<tokio::sync::Mutex<()>>>>,
+ fences: FenceMap,
_cancel: CancellationToken,
_mock_cluster:
rdkafka::mocking::MockCluster<'static, rdkafka::producer::DefaultProducerContext>,
@@ -106,6 +111,7 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
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());
+ let fences: FenceMap = 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(
@@ -120,7 +126,7 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
test_recovery(&bootstrap),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
- Arc::new(DashMap::new()),
+ Arc::clone(&fences),
None,
None,
Arc::clone(&emitted_versions),
@@ -156,6 +162,7 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
emitted_versions,
dirty_index,
locks,
+ fences,
_cancel: cancel,
_mock_cluster: mock_cluster,
}
@@ -1394,6 +1401,7 @@ async fn the_takeover_scan_rebuilds_exactly_the_partitions_live_fences() {
personhog_leader::fence::FenceState {
op_id: Uuid::now_v7(),
op_type: personhog_proto::personhog::types::v1::LifecycleOpType::Delete,
+ sealed_at: None,
},
);
let reinstalled = rebuild_partition_fences(&fallback, &fences, ghost_partition, NUM_PARTITIONS)
@@ -3068,3 +3076,368 @@ async fn a_batched_release_with_a_person_off_the_routed_partition_is_refused_who
.await
.expect("cleanup op");
}
+
+/// A fence the takeover scan installed can postdate a release the previous
+/// owner acked, so a replayed release must read the settled row, not the
+/// op's snapshot, or it destroys a person recreated under the same key.
+#[tokio::test]
+async fn a_takeover_fence_reads_the_row_not_the_snapshot() {
+ let pool = common::create_persons_pool().await;
+ let fallback = PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
+ };
+ let mut harness = start_fence_harness(test_cached_person(), Some(fallback.clone())).await;
+ let (team_id, partition, victim) = (harness.team_id, harness.partition, harness.person_id);
+ let key = |person_id| PersonCacheKey { team_id, person_id };
+
+ let sibling = another_person_on_harness_partition(&harness, victim);
+ let sibling_uuid = Uuid::now_v7().to_string();
+ seed_person(
+ &harness.cache,
+ partition,
+ CachedPerson {
+ id: sibling,
+ team_id,
+ uuid: sibling_uuid.clone(),
+ ..test_cached_person()
+ },
+ );
+
+ let op = Uuid::now_v7();
+ insert_delete_marks(&pool, op, team_id, &[victim, sibling]).await;
+ sqlx::query("UPDATE lifecycle_op_person SET mark_active = true WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("activate marks");
+
+ // The previous owner sealed the victim; its release carries these values.
+ let victim_seal = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, victim, &op),
+ partition,
+ ))
+ .await
+ .expect("seal succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed");
+
+ // This pod takes the partition over and rebuilds both fences from the rows.
+ rebuild_partition_fences(&fallback, &harness.fences, partition, NUM_PARTITIONS)
+ .await
+ .expect("scan runs");
+
+ // The sibling's release loads the op's snapshot before the rows settle.
+ let sibling_seal = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, sibling, &op),
+ partition,
+ ))
+ .await
+ .expect("seal succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed");
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: sibling,
+ person_uuid: sibling_uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sibling_seal.version),
+ created_at: sibling_seal.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("the sibling's release succeeds");
+
+ // The op settles, and the victim is recreated under the same key.
+ sqlx::query(
+ "UPDATE lifecycle_op_person SET status = 'deleted', mark_active = false WHERE op_id = $1",
+ )
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("settle");
+ seed_person(
+ &harness.cache,
+ partition,
+ CachedPerson {
+ team_id,
+ ..test_cached_person()
+ },
+ );
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: victim,
+ person_uuid: test_cached_person().uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(victim_seal.version),
+ created_at: victim_seal.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("a settled release is absorbed");
+
+ match harness.cache.get(partition, &key(victim)) {
+ CacheLookup::Found(entry) => assert!(
+ !entry.is_deleted,
+ "a settled release must not destroy the recreated person"
+ ),
+ _ => panic!("the recreated person stays cached"),
+ }
+ assert!(
+ harness.fences.get(&key(victim)).is_none(),
+ "the settled fence is dropped"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup op");
+}
+
+#[tokio::test]
+async fn a_same_op_re_fence_leaves_a_takeover_fence_unsealed() {
+ let pool = common::create_persons_pool().await;
+ let fallback = PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
+ };
+ let mut harness = start_fence_harness(test_cached_person(), Some(fallback.clone())).await;
+ let (team_id, partition, victim) = (harness.team_id, harness.partition, harness.person_id);
+ let key = PersonCacheKey {
+ team_id,
+ person_id: victim,
+ };
+
+ let op = Uuid::now_v7();
+ insert_delete_marks(&pool, op, team_id, &[victim]).await;
+ sqlx::query("UPDATE lifecycle_op_person SET mark_active = true WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("activate marks");
+
+ rebuild_partition_fences(&fallback, &harness.fences, partition, NUM_PARTITIONS)
+ .await
+ .expect("scan runs");
+ assert!(harness
+ .fences
+ .get(&key)
+ .expect("takeover fence")
+ .sealed_at
+ .is_none());
+
+ // The identity replays the op's fence call against the new owner.
+ harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, victim, &op),
+ partition,
+ ))
+ .await
+ .expect("the re-fence succeeds");
+ assert!(
+ harness
+ .fences
+ .get(&key)
+ .expect("fence survives")
+ .sealed_at
+ .is_none(),
+ "a same-op re-fence must not stamp a takeover fence with a seal time"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup op");
+}
+
+#[tokio::test]
+async fn a_release_trusts_the_snapshot_only_under_a_fence_sealed_before_it() {
+ let pool = common::create_persons_pool().await;
+ let fallback = PgFallback {
+ pool: pool.clone(),
+ table: "posthog_person".to_string(),
+ lifecycle: LifecycleTables::new("lifecycle_op", "lifecycle_op_person"),
+ };
+ let mut harness = start_fence_harness(test_cached_person(), Some(fallback)).await;
+ let (team_id, partition, victim) = (harness.team_id, harness.partition, harness.person_id);
+ let key = |person_id| PersonCacheKey { team_id, person_id };
+
+ let sibling = another_person_on_harness_partition(&harness, victim);
+ let sibling_uuid = Uuid::now_v7().to_string();
+ seed_person(
+ &harness.cache,
+ partition,
+ CachedPerson {
+ id: sibling,
+ team_id,
+ uuid: sibling_uuid.clone(),
+ ..test_cached_person()
+ },
+ );
+
+ let op = Uuid::now_v7();
+ insert_delete_marks(&pool, op, team_id, &[victim, sibling]).await;
+ sqlx::query("UPDATE lifecycle_op_person SET mark_active = true WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("activate marks");
+
+ let victim_seal = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, victim, &op),
+ partition,
+ ))
+ .await
+ .expect("seal succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed");
+ let sibling_seal = harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, sibling, &op),
+ partition,
+ ))
+ .await
+ .expect("seal succeeds")
+ .into_inner()
+ .sealed
+ .expect("sealed");
+
+ // The sibling's release loads the op's snapshot; the victim's answers
+ // from it and drops the victim's fence.
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: sibling,
+ person_uuid: sibling_uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(sibling_seal.version),
+ created_at: sibling_seal.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("the sibling's release succeeds");
+ // The victim's row settles under its standing seal fence, which cannot
+ // happen in service; it shows which arm the release answered from.
+ sqlx::query(
+ "UPDATE lifecycle_op_person SET status = 'deleted' WHERE op_id = $1 AND person_id = $2",
+ )
+ .bind(op)
+ .bind(victim)
+ .execute(&pool)
+ .await
+ .expect("settle the victim's row");
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: victim,
+ person_uuid: test_cached_person().uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(victim_seal.version),
+ created_at: victim_seal.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("the victim's release succeeds");
+ match harness.cache.get(partition, &key(victim)) {
+ CacheLookup::Found(entry) => assert!(
+ entry.is_deleted,
+ "a fence sealed before the snapshot answers from it"
+ ),
+ _ => panic!("the victim stays cached"),
+ }
+
+ // The op settles, the victim is recreated under the same key, and a
+ // late same-op fence call seals the recreated person.
+ sqlx::query(
+ "UPDATE lifecycle_op_person SET status = 'deleted', mark_active = false WHERE op_id = $1",
+ )
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("settle");
+ seed_person(
+ &harness.cache,
+ partition,
+ CachedPerson {
+ team_id,
+ ..test_cached_person()
+ },
+ );
+ harness
+ .client
+ .fence_person(with_partition(
+ fence_request(team_id, victim, &op),
+ partition,
+ ))
+ .await
+ .expect("the late fence succeeds");
+
+ harness
+ .client
+ .release_fence(with_partition(
+ ReleaseFenceRequest {
+ team_id,
+ person_id: victim,
+ person_uuid: test_cached_person().uuid,
+ op_id: op.to_string(),
+ outcome: ReleaseOutcome::Committed.into(),
+ sealed_version: Some(victim_seal.version),
+ created_at: victim_seal.created_at,
+ },
+ partition,
+ ))
+ .await
+ .expect("a settled release is absorbed");
+
+ match harness.cache.get(partition, &key(victim)) {
+ CacheLookup::Found(entry) => assert!(
+ !entry.is_deleted,
+ "a settled release must not destroy the recreated person"
+ ),
+ _ => panic!("the recreated person stays cached"),
+ }
+ assert!(
+ harness.fences.get(&key(victim)).is_none(),
+ "the settled fence is dropped"
+ );
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op)
+ .execute(&pool)
+ .await
+ .expect("cleanup op");
+}