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): recover evicted dirty persons from the changelog (#70910)

Zach Brown108c7d22f743
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 5bdc22d36f3a..b06e4e9577d5 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -568,6 +568,17 @@ jobs:
./target/debug/personhog-test-harness gate \
--leaders 2 --partitions 4 --persons 100 --concurrency 10 --duration 10s
+ # Regression gate for eviction under writer lag: the cache is
+ # sized far below the person count so dirty entries evict while
+ # the paused writer guarantees their PG rows are stale. Before
+ # the dirty-index recovery this run lost thousands of acked
+ # writes.
+ - name: Run the e2e gate under cache eviction pressure + writer lag
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 3 --partitions 8 --persons 50 --concurrency 10 --duration 15s \
+ --cache-capacity 10 --writer-pause-after 3s --writer-pause-duration 8s
+
- name: Run the e2e gate under chaos (kill + scale-up)
run: |
./target/debug/personhog-test-harness gate \
diff --git a/rust/.config/nextest.toml b/rust/.config/nextest.toml
index 99db22d79a27..5db7073b1ca4 100644
--- a/rust/.config/nextest.toml
+++ b/rust/.config/nextest.toml
@@ -1,3 +1,18 @@
+# The k3s integration tests each boot a privileged single-node Kubernetes
+# cluster in docker. Their #[serial] attributes only lock within a process,
+# and nextest runs one process per test, so without this group the clusters
+# boot concurrently and starve each other (and the runner) — the K8s-aware
+# assignment paths then stall on a slow API server and time out. max-threads
+# serializes them across processes; threads-required keeps the rest of the
+# suite from saturating the runner while a cluster is up.
+[test-groups]
+k3s = { max-threads = 1 }
+
+[[profile.default.overrides]]
+filter = 'binary(k3s_integration)'
+test-group = 'k3s'
+threads-required = 4
+
# CI profile: emits JUnit XML (target/nextest/ci/junit.xml) so test results can be
# uploaded to Trunk for flaky-test detection.
[profile.ci]
diff --git a/rust/common/k8s-awareness/src/watcher.rs b/rust/common/k8s-awareness/src/watcher.rs
index c1097cd1cc33..31772823eceb 100644
--- a/rust/common/k8s-awareness/src/watcher.rs
+++ b/rust/common/k8s-awareness/src/watcher.rs
@@ -6,6 +6,7 @@ use futures::StreamExt;
use k8s_openapi::api::apps::v1::{Deployment, ReplicaSet, StatefulSet};
use kube::api::{Api, ListParams};
use kube::runtime::watcher::{self, Config as WatcherConfig, Event};
+use kube::runtime::WatchStreamExt;
use kube::Client;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
@@ -167,7 +168,9 @@ async fn run_deployment_watcher(
let api: Api<Deployment> = Api::namespaced(client.clone(), namespace);
let config = WatcherConfig::default().fields(&format!("metadata.name={}", controller.name));
- let stream = watcher::watcher(api, config);
+ // Without backoff, an unreachable API server makes the watcher retry
+ // its connection in a hot loop, flooding logs at sub-millisecond rate.
+ let stream = watcher::watcher(api, config).default_backoff();
tokio::pin!(stream);
loop {
@@ -402,7 +405,8 @@ async fn run_statefulset_watcher(
let api: Api<StatefulSet> = Api::namespaced(client.clone(), namespace);
let config = WatcherConfig::default().fields(&format!("metadata.name={}", controller.name));
- let stream = watcher::watcher(api, config);
+ // Same backoff rationale as the deployment watcher above.
+ let stream = watcher::watcher(api, config).default_backoff();
tokio::pin!(stream);
loop {
diff --git a/rust/personhog-leader/src/cache/dirty_index.rs b/rust/personhog-leader/src/cache/dirty_index.rs
new file mode 100644
index 000000000000..d9f04ee583e3
--- /dev/null
+++ b/rust/personhog-leader/src/cache/dirty_index.rs
@@ -0,0 +1,556 @@
+use std::collections::{HashMap, VecDeque};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use dashmap::mapref::entry::Entry;
+use dashmap::DashMap;
+
+use super::PersonCacheKey;
+
+/// A mark for a person whose latest acked state may not yet be applied to
+/// Postgres by the writer.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DirtyMark {
+ /// Version of the latest acked changelog record for this person.
+ /// Recovery cross-checks it against the record it fetches: the two
+ /// derive from the same state, so a mismatch means the acked state and
+ /// the produced record diverged.
+ pub version: i64,
+ /// Changelog offset of that record. Because records are full state and
+ /// the topic is compacted by person key, this single record is always
+ /// sufficient to reconstruct the person — and compaction never removes
+ /// the latest record for a key. Only the topic's `delete` retention
+ /// bounds it, which matters solely if a mark outlives the retention
+ /// window (a writer outage of days); even then recovery fails loudly
+ /// with a retryable error rather than serving stale state.
+ pub offset: i64,
+ /// The person's routing partition, denormalized so pruning can work
+ /// per partition without rehashing keys.
+ pub partition: u32,
+}
+
+/// 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;
+
+/// Containers below this capacity are never shrunk — the retained memory
+/// is a few hundred KB at most, not worth the churn.
+const SHRINK_CAPACITY_FLOOR: usize = 4 * PRUNE_CHUNK;
+
+/// Index of persons whose latest acked state is (or may be) newer than what
+/// the writer has applied to Postgres.
+///
+/// The cache evicts freely; this index is what keeps eviction safe. On a
+/// cache miss the leader consults it before trusting the PG fallback: a
+/// marked person is recovered from the changelog record at the marked
+/// offset, an unmarked person's PG row is known current. Entries cost
+/// ~100 bytes with map overhead, so even an hours-long writer outage is
+/// far cheaper to track here than to ride out by pinning person state.
+///
+/// Marks are added under the per-key lock after every acked produce, and
+/// removed by a periodic prune once the writer's committed offset passes
+/// them (committed offset semantics: the record at `committed - 1` is the
+/// last one applied, so a mark is prunable when `offset < committed`).
+///
+/// The prune predicate is an offset threshold and marks arrive in roughly
+/// offset order per partition, so reclaim is a queue pop, not a map scan:
+/// alongside the map, each partition keeps an offset-ordered reclaim queue
+/// of `(offset, key)` entries, and a prune pops from the head only while
+/// entries are below the committed offset. A tick therefore costs work
+/// proportional to the marks actually reclaimed — never the index size —
+/// which is what lets the prune loop run every second.
+///
+/// The queue is a hint; the map is the truth. Every marked key has exactly
+/// one live queue entry, carrying some offset at or below its map offset:
+/// `mark` enqueues only brand-new keys, so a re-marked key's queue entry
+/// goes stale, and when the prune pops it and finds the map ahead of the
+/// committed offset it re-enqueues the entry at the map's offset instead
+/// of removing the mark. Task scheduling can also interleave near-
+/// simultaneous marks slightly out of offset order; the prune stops at the
+/// first unapplied head, so an inversion only delays the entries behind it
+/// until a later tick.
+///
+/// The index is soft-bounded by `max_entries`: under a sustained writer
+/// outage it would otherwise grow one mark per unique person written —
+/// gigabytes over hours at production churn, and an OOM restart replays
+/// the same backlog through warming. Write admission (`can_admit`) is
+/// checked before producing, so the bound sheds new write volume instead
+/// of ever refusing to record a fact: `mark` itself never fails, because
+/// warming must be able to record marks for records that are already
+/// durable regardless of the bound.
+pub struct DirtyIndex {
+ map: DashMap<PersonCacheKey, DirtyMark>,
+ /// Per-partition reclaim queues (see the struct docs). A prune pass
+ /// holds a queue's lock for at most `PRUNE_CHUNK` pops and re-fetches
+ /// the queue from this map between chunks, so `clear_partition` —
+ /// which detaches the queue and then takes the same lock — waits out
+ /// at most one chunk before draining, and a paused pass finds the
+ /// queue gone instead of racing the drain. Entries popped before the
+ /// detach have already had their map marks removed; everything else
+ /// is still in the queue for the drain — no entry escapes a release.
+ queues: DashMap<u32, ReclaimQueue>,
+ /// Highest offset ever marked per partition since its last clear.
+ /// Map offsets only grow and pruning removes low offsets first, so
+ /// while any mark lives this equals the largest live mark — an O(1)
+ /// read for the writer-lag gauge.
+ max_marked: DashMap<u32, i64>,
+ /// Entry count maintained alongside the map: `DashMap::len()` takes a
+ /// read lock on every shard, which is too expensive for the admission
+ /// check on the write hot path. Kept in step by `mark` (insert only)
+ /// and the removal methods; approximate under concurrent mutation,
+ /// which a soft bound tolerates.
+ size: AtomicUsize,
+ max_entries: usize,
+}
+
+impl DirtyIndex {
+ pub fn new(max_entries: usize) -> Self {
+ Self {
+ map: DashMap::new(),
+ queues: DashMap::new(),
+ max_marked: DashMap::new(),
+ size: AtomicUsize::new(0),
+ max_entries,
+ }
+ }
+
+ /// Whether a write for `key` may be admitted: either the index has
+ /// room to grow, or the key is already marked (updating a mark does
+ /// not grow the index). Checked before the produce — a durable but
+ /// unmarked write would silently reopen the stale-fallback hole.
+ /// Concurrent in-flight writes can overshoot the bound by the request
+ /// concurrency; it is a memory bound, not an exact count.
+ pub fn can_admit(&self, key: &PersonCacheKey) -> bool {
+ self.size.load(Ordering::Relaxed) < self.max_entries || self.map.contains_key(key)
+ }
+
+ /// Record the latest acked offset for a person. Writers hold the
+ /// per-key lock, so marks normally arrive in offset order; the guard
+ /// against regressing keeps a concurrent warm-seeding pass from
+ /// clobbering a newer mark with an older replayed one. The map is
+ /// updated before the queue so a concurrent prune popping the entry
+ /// always sees the mark.
+ pub fn mark(&self, key: PersonCacheKey, mark: DirtyMark) {
+ let partition = mark.partition;
+ let offset = mark.offset;
+ let is_new = match self.map.entry(key.clone()) {
+ Entry::Occupied(mut entry) => {
+ if mark.offset > entry.get().offset {
+ *entry.get_mut() = mark;
+ }
+ false
+ }
+ Entry::Vacant(entry) => {
+ entry.insert(mark);
+ self.size.fetch_add(1, Ordering::Relaxed);
+ true
+ }
+ };
+ self.max_marked
+ .entry(partition)
+ .and_modify(|max| *max = (*max).max(offset))
+ .or_insert(offset);
+ if is_new {
+ let queue = Arc::clone(
+ self.queues
+ .entry(partition)
+ .or_insert_with(|| Arc::new(Mutex::new(VecDeque::new())))
+ .value(),
+ );
+ queue
+ .lock()
+ .expect("dirty index queue lock poisoned")
+ .push_back((offset, key));
+ }
+ }
+
+ pub fn get(&self, key: &PersonCacheKey) -> Option<DirtyMark> {
+ 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
+ /// reclaimable through removals, so callers invoke this after removing
+ /// something. The threshold makes it a no-op both during steady lag
+ /// (the map is genuinely full) and right after a shrink (capacity
+ /// tracks the live count again), so a draining backlog triggers at
+ /// most a few shrinks, each cheap because little survives to rehash.
+ fn maybe_shrink_map(&self) {
+ let capacity = self.map.capacity();
+ if capacity > SHRINK_CAPACITY_FLOOR && self.len() * 4 < capacity {
+ self.map.shrink_to_fit();
+ }
+ }
+
+ /// 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) {
+ let Some(queue) = self
+ .queues
+ .get(&partition)
+ .map(|entry| Arc::clone(entry.value()))
+ else {
+ return (0, true);
+ };
+ let mut queue = queue.lock().expect("dirty index queue lock poisoned");
+ let mut removed = 0;
+ let mut budget = PRUNE_CHUNK;
+ while budget > 0 {
+ let Some(&(offset, _)) = queue.front() else {
+ self.size.fetch_sub(removed, Ordering::Relaxed);
+ return (removed, true);
+ };
+ if offset >= committed {
+ self.size.fetch_sub(removed, Ordering::Relaxed);
+ return (removed, true);
+ }
+ budget -= 1;
+ let (_, key) = queue.pop_front().expect("front was just observed");
+ // The removal re-checks the map's offset under the shard
+ // 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()
+ {
+ removed += 1;
+ } 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
+ // queue presence (`mark` enqueues keys once). Dropping
+ // it would leave the mark unreclaimable — pops are the
+ // only reclaim path — so re-enqueue at the map's
+ // offset. The tail lands past the committed threshold,
+ // so the head check terminates the pass before
+ // re-processing it; the resulting disorder only delays
+ // that key's reclaim, since removal is always re-proved
+ // against the map.
+ queue.push_back((mark.offset, key.clone()));
+ }
+ }
+ self.size.fetch_sub(removed, Ordering::Relaxed);
+ (removed, false)
+ }
+
+ /// Drop every mark on `partition` — used when the partition is released
+ /// to another owner, whose warming rebuilds its own marks.
+ pub fn clear_partition(&self, partition: u32) -> usize {
+ let Some((_, queue)) = self.queues.remove(&partition) else {
+ return 0;
+ };
+ self.max_marked.remove(&partition);
+ let mut queue = queue.lock().expect("dirty index queue lock poisoned");
+ let mut removed = 0;
+ while let Some((_, key)) = queue.pop_front() {
+ if self.map.remove(&key).is_some() {
+ removed += 1;
+ }
+ }
+ self.size.fetch_sub(removed, Ordering::Relaxed);
+ // Releases bypass prune_applied, so a released backlog's map
+ // capacity would otherwise stay pinned until some future prune.
+ if removed > 0 {
+ self.maybe_shrink_map();
+ }
+ removed
+ }
+
+ /// Partitions that currently hold marks — the prune loop's targeting
+ /// set for the writer committed-offset fetch.
+ pub fn partitions_with_marks(&self) -> Vec<u32> {
+ self.queues
+ .iter()
+ .filter(|entry| {
+ !entry
+ .value()
+ .lock()
+ .expect("dirty index queue lock poisoned")
+ .is_empty()
+ })
+ .map(|entry| *entry.key())
+ .collect()
+ }
+
+ /// Highest live marked offset for a partition, if any — feeds the
+ /// writer-lag gauge.
+ pub fn max_offset(&self, partition: u32) -> Option<i64> {
+ let has_marks = self.queues.get(&partition).is_some_and(|queue| {
+ !queue
+ .value()
+ .lock()
+ .expect("dirty index queue lock poisoned")
+ .is_empty()
+ });
+ if !has_marks {
+ return None;
+ }
+ self.max_marked.get(&partition).map(|max| *max.value())
+ }
+
+ pub fn len(&self) -> usize {
+ self.size.load(Ordering::Relaxed)
+ }
+
+ /// The soft entry bound — exported as a gauge so fullness
+ /// (`len / max_entries`) is alertable before writes start shedding.
+ pub fn max_entries(&self) -> usize {
+ self.max_entries
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn key(person_id: i64) -> PersonCacheKey {
+ PersonCacheKey {
+ team_id: 1,
+ person_id,
+ }
+ }
+
+ fn mark(offset: i64, partition: u32) -> DirtyMark {
+ DirtyMark {
+ version: offset,
+ offset,
+ partition,
+ }
+ }
+
+ #[test]
+ fn admission_is_denied_at_capacity_except_for_marked_keys() {
+ let index = DirtyIndex::new(1);
+ assert!(index.can_admit(&key(1)));
+ index.mark(key(1), mark(1, 0));
+
+ // At capacity: new keys are denied, the marked key is not.
+ assert!(!index.can_admit(&key(2)));
+ assert!(index.can_admit(&key(1)));
+
+ // Marks themselves are never refused (warming records facts about
+ // already-durable records regardless of the bound).
+ index.mark(key(2), mark(2, 0));
+ assert_eq!(index.len(), 2);
+
+ // Pruning frees admission again.
+ index.prune_partition(0, 100);
+ assert!(index.can_admit(&key(3)));
+ }
+
+ #[test]
+ fn mark_keeps_the_newest_offset() {
+ let index = DirtyIndex::new(1_000);
+ index.mark(key(1), mark(5, 0));
+ index.mark(key(1), mark(3, 0));
+ assert_eq!(index.get(&key(1)).unwrap().offset, 5);
+
+ index.mark(key(1), mark(7, 0));
+ assert_eq!(index.get(&key(1)).unwrap().offset, 7);
+ }
+
+ #[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(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);
+ assert!(index.get(&key(1)).is_none());
+ assert!(index.get(&key(2)).is_some());
+ assert!(index.get(&key(3)).is_some());
+ }
+
+ #[test]
+ fn remarked_key_survives_prune_until_its_newest_offset_is_applied() {
+ let index = DirtyIndex::new(1_000);
+ index.mark(key(1), mark(1, 0));
+ index.mark(key(1), mark(5, 0));
+
+ // 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!(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!(index.get(&key(1)).is_none());
+ assert_eq!(index.len(), 0);
+ }
+
+ #[test]
+ fn prune_stops_at_the_first_unapplied_head() {
+ let index = DirtyIndex::new(1_000);
+ // Near-simultaneous marks can enqueue slightly out of offset
+ // order; the prune stops at the first unapplied head, delaying
+ // (not losing) the applied entry behind it.
+ 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!(index.is_empty());
+ }
+
+ #[test]
+ fn prune_reclaims_a_backlog_larger_than_one_chunk() {
+ let total = PRUNE_CHUNK as i64 * 2 + 100;
+ let index = DirtyIndex::new(usize::MAX);
+ for offset in 0..total {
+ index.mark(key(offset), mark(offset, 0));
+ }
+
+ // A catch-up reclaims across chunk boundaries in a single call.
+ assert_eq!(index.prune_partition(0, total), total as usize);
+ assert!(index.is_empty());
+ }
+
+ #[test]
+ fn clear_between_chunks_ends_the_pass_without_leaking_marks() {
+ let total = PRUNE_CHUNK as i64 + 500;
+ let index = DirtyIndex::new(usize::MAX);
+ for offset in 0..total {
+ index.mark(key(offset), mark(offset, 0));
+ }
+
+ // 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!(!exhausted);
+
+ // A release lands between chunks: it detaches the queue and
+ // drains every remaining mark — nothing escapes.
+ assert_eq!(index.clear_partition(0), 500);
+ assert_eq!(index.len(), 0);
+
+ // 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!(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!(index.is_empty());
+ }
+
+ #[test]
+ fn prune_and_clear_are_scoped_to_the_partition() {
+ let index = DirtyIndex::new(1_000);
+ index.mark(key(1), mark(1, 0));
+ index.mark(key(2), mark(1, 7));
+
+ assert_eq!(index.prune_partition(0, 100), 1);
+ assert!(index.get(&key(2)).is_some());
+
+ index.mark(key(3), mark(2, 7));
+ assert_eq!(index.clear_partition(7), 2);
+ assert!(index.is_empty());
+ }
+
+ #[test]
+ fn partition_targeting_and_max_offset_track_live_marks() {
+ let index = DirtyIndex::new(1_000);
+ index.mark(key(1), mark(4, 0));
+ index.mark(key(2), mark(9, 0));
+ index.mark(key(3), mark(2, 7));
+
+ let mut partitions = index.partitions_with_marks();
+ partitions.sort_unstable();
+ assert_eq!(partitions, vec![0, 7]);
+ assert_eq!(index.max_offset(0), Some(9));
+ assert_eq!(index.max_offset(7), Some(2));
+ assert_eq!(index.max_offset(3), None);
+
+ index.prune_partition(0, 100);
+ assert_eq!(index.max_offset(0), None);
+ assert_eq!(index.partitions_with_marks(), vec![7]);
+ }
+
+ #[test]
+ fn size_tracks_inserts_updates_and_removals() {
+ let index = DirtyIndex::new(1_000);
+ index.mark(key(1), mark(1, 0));
+ index.mark(key(1), mark(2, 0)); // update, not growth
+ index.mark(key(2), mark(3, 0));
+ assert_eq!(index.len(), 2);
+
+ index.prune_partition(0, 3);
+ assert_eq!(index.len(), 1);
+
+ index.clear_partition(0);
+ assert_eq!(index.len(), 0);
+ assert!(index.is_empty());
+ }
+}
diff --git a/rust/personhog-leader/src/cache/mod.rs b/rust/personhog-leader/src/cache/mod.rs
index bf1f31edff54..216d259d1528 100644
--- a/rust/personhog-leader/src/cache/mod.rs
+++ b/rust/personhog-leader/src/cache/mod.rs
@@ -1,5 +1,7 @@
+mod dirty_index;
mod partitioned;
mod persons;
+pub use dirty_index::{DirtyIndex, DirtyMark};
pub use partitioned::{CacheLookup, PartitionedCache};
pub use persons::{CachedPerson, PersonCache, PersonCacheKey};
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index 1d37eea89ee4..461cff649adc 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -84,6 +84,16 @@ impl PartitionedCache {
cache.put(key, person);
}
}
+
+ /// 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.
+ pub fn remove(&self, partition: u32, key: &PersonCacheKey) {
+ if let Some(cache) = self.partitions.get(&partition) {
+ cache.remove(key);
+ }
+ }
}
#[cfg(test)]
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index da785e47e58a..20ac4eae1966 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -1,8 +1,9 @@
use std::hash::Hash;
use std::sync::Arc;
-use foyer::{Cache, CacheBuilder};
+use foyer::{Cache, CacheBuilder, Event, EventListener};
use metrics::counter;
+use personhog_proto::personhog::types::v1::Person;
/// Key for person cache lookups: (team_id, person_id).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -24,22 +25,67 @@ pub struct CachedPerson {
// TODO: Add properties_last_updated_at and properties_last_operation
}
+/// Decodes a changelog `Person` record into cache form. The only fallible
+/// step is parsing the properties JSON; callers add their own context
+/// (offset, partition) to the error.
+impl TryFrom<Person> for CachedPerson {
+ type Error = serde_json::Error;
+
+ fn try_from(person: Person) -> Result<Self, Self::Error> {
+ Ok(Self {
+ id: person.id,
+ uuid: person.uuid,
+ team_id: person.team_id,
+ properties: serde_json::from_slice(&person.properties)?,
+ created_at: person.created_at,
+ version: person.version,
+ is_identified: person.is_identified,
+ })
+ }
+}
+
+/// Counts entries leaving the cache, by reason. Evictions are the
+/// operationally interesting ones: evicting a recently written person is
+/// exactly what the dirty index + changelog recovery exist to make safe,
+/// and a sustained eviction rate is the early signal that the configured
+/// capacity is undersized for the working set.
+struct CacheEventMetrics;
+
+impl EventListener for CacheEventMetrics {
+ type Key = PersonCacheKey;
+ type Value = Arc<CachedPerson>;
+
+ fn on_leave(&self, reason: Event, _key: &Self::Key, _value: &Self::Value) {
+ let reason = match reason {
+ Event::Evict => "evict",
+ Event::Remove => "remove",
+ Event::Clear => "clear",
+ // Every successful update overwrites its cache entry, so
+ // Replace fires once per write — pure hot-path noise that
+ // would drown the signal this metric exists for.
+ Event::Replace => return,
+ };
+ counter!("personhog_leader_cache_entries_left_total", "reason" => reason).increment(1);
+ }
+}
+
/// In-memory person cache backed by Foyer.
///
-/// For the PoC we use Foyer's in-memory cache. The hybrid (disk+memory)
-/// layer can be added later by switching to `HybridCache`.
-///
-/// TODO: Foyer is an eviction-based cache, but the leader is the source of truth
-/// for its partitions. A cache miss currently returns NotFound, losing the person.
-/// Add a Postgres fallback on cache miss so eviction degrades to a slower read
-/// rather than data loss.
+/// Foyer evicts freely under capacity pressure; that is safe because the
+/// service's miss path never trusts a stale source. Persons in the dirty
+/// index (acked but not yet applied to PG by the writer) recover from
+/// their changelog record; everyone else's PG fallback row is current.
+/// A hybrid (disk+memory) tier remains a possible capacity optimization
+/// by switching to `HybridCache`.
pub struct PersonCache {
inner: Cache<PersonCacheKey, Arc<CachedPerson>>,
}
impl PersonCache {
pub fn new(capacity: usize) -> Self {
- let cache = CacheBuilder::new(capacity).build();
+ let cache = CacheBuilder::new(capacity)
+ .with_event_listener(Arc::new(CacheEventMetrics))
+ .build();
Self { inner: cache }
}
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index 68ea2e348421..123579cd6f70 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -125,9 +125,50 @@ pub struct Config {
#[envconfig(default = "5000")]
pub warm_retry_max_backoff_ms: u64,
+ // ── Dirty index / changelog recovery ─────────────────────────
+ /// How often to poll the writer's committed offsets and prune dirty
+ /// index marks the writer has applied to PG. A tick costs one batched
+ /// OffsetFetch plus work proportional to the marks actually reclaimed
+ /// (the index is never scanned), so a short interval is cheap — and it
+ /// bounds how long an applied-but-unpruned mark keeps sending reads to
+ /// the changelog for state PG already has.
+ #[envconfig(default = "1")]
+ pub dirty_index_prune_interval_secs: u64,
+
+ /// Overall deadline for recovering one evicted dirty person from the
+ /// changelog, including transient-failure retries. A point read that
+ /// hasn't returned in a few seconds isn't going to, and each recovery
+ /// occupies a pooled consumer for its whole duration — a long deadline
+ /// amplifies a broker blip into pool exhaustion.
+ #[envconfig(default = "5")]
+ pub recovery_recv_timeout_secs: u64,
+
+ /// Number of pooled changelog-recovery consumers, bounding concurrent
+ /// recoveries the way a DB connection pool bounds queries. Each is a
+ /// full Kafka client (its own connections and background threads), but
+ /// even 16 is fewer than the per-partition consumers this pool
+ /// replaced. Under a benchmarked writer outage a pool of 4 queued
+ /// recoveries for ~10ms on average and tripled write p99; 16 zeroed
+ /// the queueing. The `personhog_leader_recovery_pool_wait_ms`
+ /// histogram shows when this is undersized.
+ #[envconfig(default = "16")]
+ pub recovery_pool_size: usize,
+
+ /// Soft bound on dirty index entries (~100 bytes each). The index
+ /// grows one mark per unique person written since the writer's
+ /// committed offset, so this bound is the memory runway a writer
+ /// outage gets before new-person writes shed with RESOURCE_EXHAUSTED.
+ /// The default (~1 GB worst case) buys hours at heavy churn.
+ #[envconfig(default = "10000000")]
+ pub dirty_index_max_entries: usize,
+
// ── PG fallback ───────────────────────────────────────────────
- /// Read-only Postgres URL for cache miss fallback. If empty, cache
- /// misses return NotFound without querying PG.
+ /// Postgres URL for cache miss fallback. If empty, cache misses
+ /// return NotFound without querying PG. Must point at the primary:
+ /// the dirty index prunes a mark as soon as the writer's committed
+ /// offset shows the primary has the row, so reading an async replica
+ /// here would serve stale rows for unmarked persons and silently
+ /// break read-your-write. Leader reads are strong reads.
#[envconfig(default = "")]
pub fallback_database_url: String,
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 5704448a9fbf..841a65b74279 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -6,7 +6,7 @@ use personhog_coordination::error::Result;
use personhog_coordination::pod::HandoffHandler;
use tracing::info;
-use crate::cache::PartitionedCache;
+use crate::cache::{DirtyIndex, PartitionedCache};
use crate::inflight::InflightTracker;
use crate::warming::{warm_from_kafka, WarmingConfig};
@@ -43,6 +43,7 @@ const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
pub struct LeaderHandoffHandler {
cache: Arc<PartitionedCache>,
inflight: Arc<InflightTracker>,
+ dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
}
@@ -50,11 +51,13 @@ impl LeaderHandoffHandler {
pub fn new(
cache: Arc<PartitionedCache>,
inflight: Arc<InflightTracker>,
+ dirty_index: Arc<DirtyIndex>,
warming: WarmingConfig,
) -> Self {
Self {
cache,
inflight,
+ dirty_index,
warming,
}
}
@@ -82,7 +85,7 @@ impl HandoffHandler for LeaderHandoffHandler {
async fn warm_partition(&self, partition: u32) -> Result<()> {
info!(partition, "warming partition cache from kafka");
- warm_from_kafka(&self.warming, &self.cache, partition).await?;
+ warm_from_kafka(&self.warming, &self.cache, &self.dirty_index, partition).await?;
// This pod may still carry a fence from a previous ownership of
// the partition (a drain whose handoff never completed); taking
// ownership through a fresh warm re-admits writes.
@@ -95,6 +98,9 @@ impl HandoffHandler for LeaderHandoffHandler {
info!(partition, "releasing partition");
self.inflight.unfence(partition);
self.cache.drop_partition(partition);
+ // The new owner's warming rebuilds its own marks; stale marks here
+ // would only pin memory for a partition this pod no longer serves.
+ self.dirty_index.clear_partition(partition);
info!(partition, "partition released");
Ok(())
}
@@ -118,31 +124,33 @@ mod tests {
/// cover the parts of `LeaderHandoffHandler` that don't require
/// Kafka: drain semantics, release semantics, and `owns_partition`.
fn handler() -> LeaderHandoffHandler {
+ let kafka = KafkaConfig {
+ kafka_producer_linger_ms: 0,
+ kafka_producer_queue_mib: 50,
+ kafka_message_timeout_ms: 5000,
+ kafka_compression_codec: "none".to_string(),
+ kafka_hosts: "localhost:9092".to_string(),
+ kafka_tls: false,
+ kafka_producer_queue_messages: 1000,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
+ kafka_producer_acks: None,
+ kafka_producer_retries: None,
+ };
LeaderHandoffHandler::new(
Arc::new(PartitionedCache::new(100)),
Arc::new(InflightTracker::new()),
+ Arc::new(DirtyIndex::new(1_000_000)),
WarmingConfig {
- kafka: KafkaConfig {
- kafka_producer_linger_ms: 0,
- kafka_producer_queue_mib: 50,
- kafka_message_timeout_ms: 5000,
- kafka_compression_codec: "none".to_string(),
- kafka_hosts: "localhost:9092".to_string(),
- kafka_tls: false,
- kafka_producer_queue_messages: 1000,
- kafka_client_rack: String::new(),
- kafka_client_id: String::new(),
- kafka_producer_batch_size: None,
- kafka_producer_batch_num_messages: None,
- kafka_producer_enable_idempotence: None,
- kafka_producer_max_in_flight_requests_per_connection: None,
- kafka_producer_topic_metadata_refresh_interval_ms: None,
- kafka_producer_message_max_bytes: None,
- kafka_producer_sticky_partitioning_linger_ms: None,
- kafka_producer_partitioner: None,
- kafka_producer_acks: None,
- kafka_producer_retries: None,
- },
+ kafka,
topic: "personhog_updates".to_string(),
pod_name: "test".to_string(),
writer_consumer_group: "personhog-writer".to_string(),
diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rs
index a5d8a2edcc15..e7857dd478a6 100644
--- a/rust/personhog-leader/src/kafka.rs
+++ b/rust/personhog-leader/src/kafka.rs
@@ -7,8 +7,11 @@ use tracing::error;
use personhog_proto::personhog::types::v1::Person;
/// Formats the Kafka message key for person state changelog messages.
-/// The topic should be configured with `cleanup.policy=compact` so that
-/// Kafka retains only the latest state per person.
+/// The topic must include `compact` in its `cleanup.policy` so Kafka
+/// retains the latest state per person. Deployed config is
+/// `compact,delete`, where retention bounds even the latest record —
+/// acceptable because nothing reads records older than the writer's
+/// committed offset, which retention outruns by design.
pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
format!("{team_id}:{person_id}")
}
@@ -25,7 +28,9 @@ pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
/// config matching the router's murmur2 (librdkafka's default partitioner
/// is CRC32-based and routes keys differently). A partition-count mismatch
/// fails loudly at produce time instead of silently mis-sharding.
-/// Returns `Ok(())` on successful delivery, or an error string on failure.
+/// Returns the record's changelog offset on successful delivery — the
+/// dirty index records it so an evicted entry can be recovered from the
+/// changelog later — or an error string on failure.
///
/// The handoff protocol relies on "handler returned Ok == message durable in Kafka."
/// That requires the delivery future to be awaited before returning (done here) and
@@ -37,7 +42,7 @@ pub async fn produce_person_changelog(
topic: &str,
partition: u32,
person: &Person,
-) -> Result<(), String> {
+) -> Result<i64, String> {
let key = changelog_message_key(person.team_id, person.id);
let payload = person.encode_to_vec();
@@ -48,9 +53,9 @@ pub async fn produce_person_changelog(
match producer.send_result(record) {
Ok(delivery_future) => match delivery_future.await {
- Ok(Ok(_)) => {
+ Ok(Ok((_, offset))) => {
counter!("personhog_leader_kafka_produces_total").increment(1);
- Ok(())
+ Ok(offset)
}
Ok(Err((kafka_err, _))) => {
counter!("personhog_leader_kafka_produce_errors_total").increment(1);
diff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rs
index cb66d59aa26d..b2175a4bddf8 100644
--- a/rust/personhog-leader/src/lib.rs
+++ b/rust/personhog-leader/src/lib.rs
@@ -5,5 +5,6 @@ pub mod inflight;
pub mod kafka;
pub mod person_update;
pub mod pg;
+pub mod recovery;
pub mod service;
pub mod warming;
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index eeda26012364..4f650b050d14 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -3,6 +3,7 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{routing::get, Router};
+use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::create_kafka_producer;
use common_metrics::setup_metrics_routes;
use dashmap::DashMap;
@@ -21,10 +22,16 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
-use personhog_leader::cache::PartitionedCache;
+use metrics::{counter, gauge};
+use personhog_leader::cache::{DirtyIndex, PartitionedCache};
use personhog_leader::config::Config;
use personhog_leader::coordination::LeaderHandoffHandler;
+use personhog_leader::inflight::InflightTracker;
+use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService};
+use personhog_leader::warming::{
+ fetch_writer_committed_offsets, WarmingConfig, WarmingRetryPolicy,
+};
common_alloc::used!();
@@ -173,7 +180,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!(num_partitions, "loaded partition count from etcd");
let locks = Arc::new(DashMap::new());
- let inflight = Arc::new(personhog_leader::inflight::InflightTracker::new());
+ let inflight = Arc::new(InflightTracker::new());
+ let dirty_index = Arc::new(DirtyIndex::new(config.dirty_index_max_entries));
+ let recovery = Arc::new(
+ ChangelogRecovery::new(RecoveryConfig {
+ kafka: config.kafka.clone(),
+ topic: config.kafka_person_state_topic.clone(),
+ pod_name: config.pod_name.clone(),
+ recv_timeout: Duration::from_secs(config.recovery_recv_timeout_secs),
+ pool_size: config.recovery_pool_size,
+ })
+ .expect("Failed to build changelog recovery consumer pool"),
+ );
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
kafka_producer,
@@ -182,12 +200,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Arc::clone(&locks),
Arc::clone(&inflight),
num_partitions,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
);
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
- personhog_leader::warming::WarmingConfig {
+ Arc::clone(&dirty_index),
+ WarmingConfig {
kafka: config.kafka.clone(),
topic: config.kafka_person_state_topic.clone(),
pod_name: config.pod_name.clone(),
@@ -200,7 +221,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.warm_fetch_watermarks_timeout_secs,
),
recv_timeout: Duration::from_secs(config.warm_recv_timeout_secs),
- retry: personhog_leader::warming::WarmingRetryPolicy {
+ retry: WarmingRetryPolicy {
max_attempts: config.warm_retry_max_attempts,
initial_backoff: Duration::from_millis(config.warm_retry_initial_backoff_ms),
max_backoff: Duration::from_millis(config.warm_retry_max_backoff_ms),
@@ -236,6 +257,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
});
+ tokio::spawn(run_dirty_index_prune_loop(
+ Arc::clone(&dirty_index),
+ config.kafka.clone(),
+ config.kafka_person_state_topic.clone(),
+ config.writer_consumer_group.clone(),
+ Duration::from_secs(config.warm_committed_offsets_timeout_secs),
+ Duration::from_secs(config.dirty_index_prune_interval_secs.max(1)),
+ ));
+
// gRPC server. Mirrors the replica's middleware stack so the router's
// per-backend metrics (processing time, transport/network overhead) and
// response compression behave identically on both backends. No tonic
@@ -316,3 +346,70 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
monitor_guard.wait().await?;
Ok(())
}
+
+/// Periodically drop dirty-index marks the writer has applied to PG, and
+/// export the dirty-count and writer-lag gauges as a side effect. One
+/// batched OffsetFetch covers every partition with marks, so each tick
+/// costs a single short-lived consumer.
+async fn run_dirty_index_prune_loop(
+ dirty_index: Arc<DirtyIndex>,
+ kafka: KafkaConfig,
+ topic: String,
+ writer_group: String,
+ offsets_timeout: Duration,
+ prune_interval: Duration,
+) {
+ let mut interval = tokio::time::interval(prune_interval);
+ loop {
+ interval.tick().await;
+ // One batched OffsetFetch, then queue pops proportional to the
+ // 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);
+ if partitions.is_empty() {
+ continue;
+ }
+ let committed_offsets = match fetch_writer_committed_offsets(
+ &kafka,
+ &writer_group,
+ &topic,
+ &partitions,
+ offsets_timeout,
+ )
+ .await
+ {
+ Ok(offsets) => offsets,
+ Err(e) => {
+ tracing::warn!(error = %e, "dirty-index prune offset fetch failed");
+ continue;
+ }
+ };
+
+ let pruned = dirty_index.prune_applied(&committed_offsets);
+ if pruned > 0 {
+ counter!("personhog_leader_dirty_index_pruned_total").increment(pruned as u64);
+ }
+ // A partition absent from the committed offsets has no writer
+ // commit yet: nothing is applied, every mark stays, and its lag
+ // is the entire marked backlog. A partition the prune fully
+ // reclaimed has no live marks left — the writer caught up, so its
+ // lag reads zero.
+ for partition in &partitions {
+ let lag = match dirty_index.max_offset(*partition) {
+ Some(max_offset) => {
+ let committed = committed_offsets.get(partition).copied().unwrap_or(0);
+ (max_offset + 1 - committed).max(0)
+ }
+ None => 0,
+ };
+ gauge!(
+ "personhog_leader_writer_uncommitted_offsets",
+ "partition" => partition.to_string()
+ )
+ .set(lag as f64);
+ }
+ }
+}
diff --git a/rust/personhog-leader/src/recovery.rs b/rust/personhog-leader/src/recovery.rs
new file mode 100644
index 000000000000..46bc26afe477
--- /dev/null
+++ b/rust/personhog-leader/src/recovery.rs
@@ -0,0 +1,291 @@
+use std::collections::VecDeque;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use common_kafka::config::KafkaConfig;
+use metrics::{counter, histogram};
+use prost::Message as ProtoMessage;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::{Offset, TopicPartitionList};
+use tokio::sync::Semaphore;
+use tokio::time::timeout;
+
+use personhog_proto::personhog::types::v1::Person;
+
+use crate::cache::{CachedPerson, DirtyMark, PersonCacheKey};
+use crate::warming::make_consumer;
+
+/// How long to wait before retrying a transiently failed fetch.
+const RETRY_BACKOFF: Duration = Duration::from_millis(100);
+
+/// Configuration for targeted changelog recovery.
+#[derive(Clone)]
+pub struct RecoveryConfig {
+ pub kafka: KafkaConfig,
+ pub topic: String,
+ pub pod_name: String,
+ /// Overall deadline for one recovery, including transient-failure
+ /// retries.
+ pub recv_timeout: Duration,
+ /// Number of pooled consumers, bounding concurrent recoveries.
+ pub pool_size: usize,
+}
+
+/// Classifies a failed fetch step for the retry loop: transient failures
+/// (broker errors, timeouts, the sought record not coming back) retry
+/// until the recovery deadline; permanent ones (a record that contradicts
+/// its mark) fail immediately.
+enum FetchError {
+ Transient(String),
+ Permanent(String),
+}
+
+/// Fetches single persons from the changelog — the recovery path for cache
+/// entries evicted while the writer still lags. It reads Kafka, never
+/// Postgres, so the leader's availability stays decoupled from writer
+/// progress.
+///
+/// Every changelog record carries the person's full state, so the one
+/// record at the dirty index's marked offset supersedes anything before
+/// it; no replay is needed. And because the topic compacts by person key,
+/// compaction never removes the latest record for a key — the only offset
+/// the index ever holds — so the fetch lands on it for as long as the
+/// topic's `delete` retention keeps it, far longer than any mark should
+/// live.
+///
+/// A fresh `assign` positions any consumer at any (partition, offset), so
+/// the consumers are fungible and pooled globally: a fixed set is built at
+/// startup — where construction failure is loud and nothing is in flight —
+/// and checked out per fetch, bounding concurrent recoveries at the pool
+/// size the way a DB connection pool bounds queries. Checkout transfers
+/// exclusive ownership through the idle deque (the semaphore only counts;
+/// a permit holder always finds a consumer), so no lock is held while a
+/// fetch waits on Kafka or backs off between retries. The pool-wait
+/// histogram is the tuning signal for the pool size. Errors never manage
+/// the pool — librdkafka clients self-heal their connections — so
+/// transient fetch failures retry on the same consumer within the
+/// recovery deadline. Checkout is an RAII guard (`PooledConsumer`) that
+/// returns the consumer and only then releases its permit on Drop, so
+/// the consumer comes home on every path including future cancellation —
+/// a client disconnecting mid-recovery drops the request future at an
+/// await point, and anything less than Drop-based return would leak the
+/// consumer while freeing its permit, eventually leaving permits with an
+/// empty pool.
+pub struct ChangelogRecovery {
+ topic: String,
+ recv_timeout: Duration,
+ idle: Mutex<VecDeque<StreamConsumer>>,
+ permits: Semaphore,
+}
+
+impl ChangelogRecovery {
+ pub fn new(cfg: RecoveryConfig) -> Result<Self, String> {
+ if cfg.pool_size == 0 {
+ return Err("recovery pool size must be at least 1".to_string());
+ }
+ let group = format!("personhog-leader-recovery-{pod}", pod = cfg.pod_name);
+ let mut idle = VecDeque::with_capacity(cfg.pool_size);
+ for _ in 0..cfg.pool_size {
+ idle.push_back(
+ make_consumer(&cfg.kafka, &group)
+ .map_err(|e| format!("create recovery consumer: {e}"))?,
+ );
+ }
+ Ok(Self {
+ topic: cfg.topic,
+ recv_timeout: cfg.recv_timeout,
+ idle: Mutex::new(idle),
+ permits: Semaphore::new(cfg.pool_size),
+ })
+ }
+
+ /// Check a consumer out of the pool. The returned guard owns both the
+ /// consumer and its semaphore permit; its Drop parks the consumer
+ /// (best-effort unassign so it does not keep fetching a partition
+ /// tail), returns it to the idle deque, and only then releases the
+ /// permit — so a slot never opens before its consumer is home, on
+ /// every path including cancellation of the awaiting future.
+ async fn checkout(&self) -> Result<PooledConsumer<'_>, String> {
+ let wait_start = Instant::now();
+ let permit = self
+ .permits
+ .acquire()
+ .await
+ .map_err(|_| "recovery pool closed".to_string())?;
+ histogram!("personhog_leader_recovery_pool_wait_ms")
+ .record(wait_start.elapsed().as_secs_f64() * 1000.0);
+ let consumer = self
+ .idle
+ .lock()
+ .expect("recovery pool lock poisoned")
+ .pop_front()
+ .expect("a permit guarantees an idle consumer");
+ Ok(PooledConsumer {
+ pool: self,
+ consumer: Some(consumer),
+ _permit: permit,
+ })
+ }
+
+ /// Fetch a person's latest state from the changelog record the dirty
+ /// index marked for its most recent acked produce. The decoded record
+ /// must carry the mark's key and version exactly: the mark was written
+ /// from the same state the record was encoded from, so any mismatch
+ /// means acked state and produced state diverged — a bug worth failing
+ /// loudly over, never worth serving.
+ pub async fn fetch_person_at(
+ &self,
+ mark: &DirtyMark,
+ expected: &PersonCacheKey,
+ ) -> Result<CachedPerson, String> {
+ let partition = mark.partition;
+ let offset = mark.offset;
+ let partition_i32 = i32::try_from(partition)
+ .map_err(|_| format!("partition {partition} exceeds i32::MAX"))?;
+
+ let consumer = self.checkout().await?;
+
+ // Each attempt repositions with a fresh assign: it starts fetching
+ // at the target immediately (repositioning a live stream via seek
+ // stalls ~1s while librdkafka drains the previous position's
+ // outstanding long-poll) and purges records buffered by a previous
+ // attempt.
+ let deadline = Instant::now() + self.recv_timeout;
+ loop {
+ let attempt = self
+ .attempt_fetch(&consumer, partition_i32, mark, expected, deadline)
+ .await;
+ match attempt {
+ Ok(person) => return Ok(person),
+ Err(FetchError::Permanent(message)) => return Err(message),
+ Err(FetchError::Transient(message)) => {
+ if Instant::now() + RETRY_BACKOFF >= deadline {
+ return Err(message);
+ }
+ counter!("personhog_leader_recovery_retries_total").increment(1);
+ tracing::debug!(
+ partition,
+ offset,
+ error = %message,
+ "transient recovery failure, retrying"
+ );
+ tokio::time::sleep(RETRY_BACKOFF).await;
+ }
+ }
+ }
+ }
+
+ /// One positioning-and-receive attempt against a locked consumer.
+ async fn attempt_fetch(
+ &self,
+ consumer: &StreamConsumer,
+ partition_i32: i32,
+ mark: &DirtyMark,
+ expected: &PersonCacheKey,
+ deadline: Instant,
+ ) -> Result<CachedPerson, FetchError> {
+ let mut tpl = TopicPartitionList::new();
+ tpl.add_partition_offset(&self.topic, partition_i32, Offset::Offset(mark.offset))
+ .map_err(|e| FetchError::Permanent(format!("tpl add_partition_offset: {e}")))?;
+ consumer
+ .assign(&tpl)
+ .map_err(|e| FetchError::Transient(format!("recovery consumer assign: {e}")))?;
+
+ let offset = mark.offset;
+ loop {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let msg = match timeout(remaining, consumer.recv()).await {
+ Ok(Ok(msg)) => msg,
+ Ok(Err(e)) => return Err(FetchError::Transient(format!("recovery recv: {e}"))),
+ Err(_) => {
+ return Err(FetchError::Transient(format!(
+ "recovery timed out after {:?} seeking partition {} offset {offset}",
+ self.recv_timeout, mark.partition
+ )));
+ }
+ };
+
+ // Skip anything that is not the sought record.
+ if msg.partition() != partition_i32 || msg.offset() < offset {
+ continue;
+ }
+ if msg.offset() > offset {
+ // A record past the target before the target itself means
+ // the sought record was not returned: either a stale
+ // buffered record from a previous position, which the next
+ // attempt's assign purges, or a record genuinely gone from
+ // the changelog, which keeps failing until the deadline.
+ return Err(FetchError::Transient(format!(
+ "recovery expected offset {offset} but read {}; record missing from changelog",
+ msg.offset()
+ )));
+ }
+
+ return decode_person(msg.payload(), mark, expected).map_err(FetchError::Permanent);
+ }
+ }
+}
+
+/// A consumer checked out of the recovery pool, together with the permit
+/// that reserved it. Drop parks the consumer, returns it to the idle
+/// deque, and then releases the permit (declaration order: the permit
+/// field drops last).
+struct PooledConsumer<'a> {
+ pool: &'a ChangelogRecovery,
+ consumer: Option<StreamConsumer>,
+ _permit: tokio::sync::SemaphorePermit<'a>,
+}
+
+impl std::ops::Deref for PooledConsumer<'_> {
+ type Target = StreamConsumer;
+
+ fn deref(&self) -> &StreamConsumer {
+ self.consumer.as_ref().expect("consumer present until drop")
+ }
+}
+
+impl Drop for PooledConsumer<'_> {
+ fn drop(&mut self) {
+ let consumer = self.consumer.take().expect("consumer present until drop");
+ if let Err(e) = consumer.unassign() {
+ tracing::warn!(error = %e, "recovery consumer unassign failed");
+ }
+ self.pool
+ .idle
+ .lock()
+ .expect("recovery pool lock poisoned")
+ .push_back(consumer);
+ }
+}
+
+fn decode_person(
+ payload: Option<&[u8]>,
+ mark: &DirtyMark,
+ expected: &PersonCacheKey,
+) -> Result<CachedPerson, String> {
+ let offset = mark.offset;
+ let payload =
+ payload.ok_or_else(|| format!("recovery record at offset {offset} has no payload"))?;
+ let person = <Person as ProtoMessage>::decode(payload)
+ .map_err(|e| format!("recovery decode failed at offset {offset}: {e}"))?;
+
+ if person.team_id != expected.team_id || person.id != expected.person_id {
+ return Err(format!(
+ "recovery record key mismatch at offset {offset}: expected team_id={} person_id={}, \
+ found team_id={} person_id={}",
+ expected.team_id, expected.person_id, person.team_id, person.id
+ ));
+ }
+
+ if person.version != mark.version {
+ return Err(format!(
+ "recovery record version mismatch at offset {offset}: acked version {}, record \
+ carries {} — acked state and produced record diverged",
+ mark.version, person.version
+ ));
+ }
+
+ CachedPerson::try_from(person)
+ .map_err(|e| format!("recovery properties decode failed at offset {offset}: {e}"))
+}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 823fab19885a..005ed1ed19f7 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -1,8 +1,9 @@
use std::sync::Arc;
+use std::time::Instant;
use common_kafka::kafka_producer::KafkaContext;
use dashmap::DashMap;
-use metrics::counter;
+use metrics::{counter, histogram};
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
use personhog_proto::personhog::types::v1::{
GetPersonRequest, GetPersonResponse, Person, UpdatePersonPropertiesRequest,
@@ -15,11 +16,14 @@ use tonic::{Request, Response, Status};
use personhog_common::partitioning::partition_for_person;
-use crate::cache::{CacheLookup, CachedPerson, PartitionedCache, PersonCacheKey};
+use crate::cache::{
+ CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey,
+};
use crate::inflight::InflightTracker;
use crate::kafka::produce_person_changelog;
use crate::person_update::{apply_property_updates, compute_event_property_updates};
use crate::pg::load_person_from_pg;
+use crate::recovery::ChangelogRecovery;
pub struct PersonHogLeaderService {
cache: Arc<PartitionedCache>,
@@ -37,9 +41,15 @@ pub struct PersonHogLeaderService {
/// source the router uses). Used to validate the router's routing
/// decision against each request's key.
num_partitions: u32,
+ /// Persons whose latest acked state the writer may not have applied to
+ /// PG yet. Consulted on every cache miss: marked persons recover from
+ /// the changelog, unmarked persons' PG rows are known current.
+ dirty_index: Arc<DirtyIndex>,
+ recovery: Arc<ChangelogRecovery>,
}
impl PersonHogLeaderService {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
cache: Arc<PartitionedCache>,
producer: FutureProducer<KafkaContext>,
@@ -48,6 +58,8 @@ impl PersonHogLeaderService {
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
inflight: Arc<InflightTracker>,
num_partitions: u32,
+ dirty_index: Arc<DirtyIndex>,
+ recovery: Arc<ChangelogRecovery>,
) -> Self {
Self {
cache,
@@ -57,6 +69,8 @@ impl PersonHogLeaderService {
fallback_pool,
inflight,
num_partitions,
+ dirty_index,
+ recovery,
}
}
@@ -84,6 +98,88 @@ impl PersonHogLeaderService {
Ok(())
}
+ fn record_cache_hit() {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "cache", "outcome" => "ok"
+ )
+ .increment(1);
+ }
+
+ /// Recover a cache miss from the right source. A person in the dirty
+ /// index has acked state the writer may not have applied to PG yet, so
+ /// the PG row cannot be trusted — recover the full latest state from
+ /// the changelog record at the marked offset instead. If that fetch
+ /// fails, the only honest answer is a retryable error: falling back to
+ /// PG would serve exactly the staleness this index exists to prevent.
+ /// Unmarked persons' PG rows are known current — but only while this
+ /// pod owns the partition, so the no-mark path re-checks ownership
+ /// before trusting PG. Assumes the caller holds the per-key lock.
+ async fn recover_or_load(
+ &self,
+ partition: u32,
+ key: &PersonCacheKey,
+ ) -> Result<Arc<CachedPerson>, Status> {
+ let Some(mark) = self.dirty_index.get(key) else {
+ // "No mark" means PG is current — but only while this pod owns
+ // the partition. Handoffs drain writes, not reads, so a read
+ // admitted before the freeze can still be executing here when
+ // `release_partition` clears the partition's marks (the new
+ // owner rebuilds its own), and to that reader a still-dirty
+ // person now looks safe to load from PG. Re-checking the cache
+ // AFTER the index read settles which world we're in: release
+ // drops the cache partition first and clears marks second, so
+ // if this miss was caused by release, the partition is already
+ // gone from the cache and we fail closed; if the partition is
+ // still present, the marks were intact when we read them and
+ // the absence is genuine. There is no interleaving that gets
+ // past both checks into a stale PG read.
+ return match self.cache.get(partition, key) {
+ CacheLookup::Found(person) => {
+ Self::record_cache_hit();
+ Ok(person)
+ }
+ CacheLookup::PersonNotFound => self.load_from_pg(partition, key).await,
+ CacheLookup::PartitionNotOwned => Err(Status::failed_precondition(format!(
+ "partition {partition} not owned by this leader"
+ ))),
+ };
+ };
+
+ let started = Instant::now();
+ let result = self.recovery.fetch_person_at(&mark, key).await;
+ histogram!("personhog_leader_person_load_duration_ms", "source" => "changelog")
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+ match result {
+ Ok(person) => {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "changelog", "outcome" => "ok"
+ )
+ .increment(1);
+ self.cache.put(partition, key.clone(), person.clone());
+ Ok(Arc::new(person))
+ }
+ Err(e) => {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "changelog", "outcome" => "error"
+ )
+ .increment(1);
+ tracing::error!(
+ team_id = key.team_id,
+ person_id = key.person_id,
+ offset = mark.offset,
+ error = %e,
+ "changelog recovery failed for dirty person"
+ );
+ Err(Status::unavailable(
+ "person state is pending durable write and changelog recovery failed; retry",
+ ))
+ }
+ }
+ }
+
/// Load a person from PG and populate the cache. Assumes the caller
/// holds the per-key lock.
async fn load_from_pg(
@@ -98,16 +194,37 @@ impl PersonHogLeaderService {
)));
};
- match load_person_from_pg(pool, key).await {
+ let started = Instant::now();
+ let result = load_person_from_pg(pool, key).await;
+ histogram!("personhog_leader_person_load_duration_ms", "source" => "pg")
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+ match result {
Ok(Some(person)) => {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "pg", "outcome" => "ok"
+ )
+ .increment(1);
self.cache.put(partition, key.clone(), person.clone());
Ok(Arc::new(person))
}
- Ok(None) => Err(Status::not_found(format!(
- "person not found: team_id={}, person_id={}",
- key.team_id, key.person_id
- ))),
+ Ok(None) => {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "pg", "outcome" => "not_found"
+ )
+ .increment(1);
+ Err(Status::not_found(format!(
+ "person not found: team_id={}, person_id={}",
+ key.team_id, key.person_id
+ )))
+ }
Err(e) => {
+ counter!(
+ "personhog_leader_person_loads_total",
+ "source" => "pg", "outcome" => "error"
+ )
+ .increment(1);
counter!("personhog_leader_pg_fallback_errors_total").increment(1);
tracing::error!(
team_id = key.team_id,
@@ -129,7 +246,10 @@ impl PersonHogLeaderService {
) -> Result<Arc<CachedPerson>, Status> {
// Fast path: cache hit (no lock needed)
match self.cache.get(partition, key) {
- CacheLookup::Found(person) => return Ok(person),
+ CacheLookup::Found(person) => {
+ Self::record_cache_hit();
+ return Ok(person);
+ }
CacheLookup::PartitionNotOwned => {
return Err(Status::failed_precondition(format!(
"partition {} not owned by this leader",
@@ -145,10 +265,11 @@ impl PersonHogLeaderService {
// Double-check cache -- another request may have loaded it
if let CacheLookup::Found(person) = self.cache.get(partition, key) {
+ Self::record_cache_hit();
return Ok(person);
}
- self.load_from_pg(partition, key).await
+ self.recover_or_load(partition, key).await
}
/// Look up a person from cache, falling back to PG on miss.
@@ -159,12 +280,15 @@ impl PersonHogLeaderService {
key: &PersonCacheKey,
) -> Result<Arc<CachedPerson>, Status> {
match self.cache.get(partition, key) {
- CacheLookup::Found(person) => Ok(person),
+ CacheLookup::Found(person) => {
+ Self::record_cache_hit();
+ Ok(person)
+ }
CacheLookup::PartitionNotOwned => Err(Status::failed_precondition(format!(
"partition {} not owned by this leader",
partition
))),
- CacheLookup::PersonNotFound => self.load_from_pg(partition, key).await,
+ CacheLookup::PersonNotFound => self.recover_or_load(partition, key).await,
}
}
}
@@ -285,6 +409,20 @@ impl PersonHogLeader for PersonHogLeaderService {
.clone();
let _guard = mutex.lock().await;
+ // Admission check before any work: if the dirty index is at
+ // capacity and this person is not already marked, acking the write
+ // would leave it durable but unmarked — reopening the
+ // stale-fallback hole on eviction. Shed instead; the index drains
+ // (and admission resumes) as the writer catches up.
+ if !self.dirty_index.can_admit(&cache_key) {
+ counter!("personhog_leader_writes_shed_total", "reason" => "dirty_index_full")
+ .increment(1);
+ return Err(Status::resource_exhausted(
+ "dirty index at capacity: the writer is behind and this person's write cannot \
+ be tracked; retry later",
+ ));
+ }
+
let person = self.lookup_or_load_locked(partition, &cache_key).await?;
// Compute property updates
@@ -331,20 +469,40 @@ impl PersonHogLeader for PersonHogLeaderService {
// Produce to Kafka first, then update the cache on success.
// Readers only ever see durably committed state.
- if let Err(e) =
- produce_person_changelog(&self.producer, &self.changelog_topic, partition, &proto).await
+ let offset = match produce_person_changelog(
+ &self.producer,
+ &self.changelog_topic,
+ partition,
+ &proto,
+ )
+ .await
{
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- error = %e,
- "failed to produce person state changelog"
- );
- return Err(Status::internal(format!(
- "failed to durably store person state: {e}"
- )));
- }
+ Ok(offset) => offset,
+ Err(e) => {
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ error = %e,
+ "failed to produce person state changelog"
+ );
+ return Err(Status::internal(format!(
+ "failed to durably store person state: {e}"
+ )));
+ }
+ };
+ // Mark before the cache insert: a reader that misses the cache in
+ // the gap sees the mark and recovers this exact record from the
+ // changelog. The mark outlives eviction and is pruned once the
+ // writer's committed offset passes it.
+ self.dirty_index.mark(
+ cache_key.clone(),
+ DirtyMark {
+ version: updated_person.version,
+ offset,
+ partition,
+ },
+ );
self.cache.put(partition, cache_key, updated_person);
counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);
@@ -370,12 +528,75 @@ pub fn sweep_idle_locks(locks: &DashMap<PersonCacheKey, Arc<Mutex<()>>>) -> usiz
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
+ use std::time::Duration;
+
+ use common_kafka::config::KafkaConfig;
+ use envconfig::Envconfig;
+ use health::HealthRegistry;
+ use rdkafka::ClientConfig;
+ use tonic::Code;
+
use super::*;
+ use crate::recovery::RecoveryConfig;
fn make_key(team_id: i64, person_id: i64) -> PersonCacheKey {
PersonCacheKey { team_id, person_id }
}
+ /// A service with no PG pool and a producer that never connects —
+ /// enough to exercise the miss path, where no test reaches Kafka or PG.
+ async fn make_test_service() -> PersonHogLeaderService {
+ let kafka = KafkaConfig::init_from_hashmap(&HashMap::new()).unwrap();
+ let liveness = HealthRegistry::new("test")
+ .register("kafka".to_string(), Duration::from_secs(60))
+ .await;
+ let producer = ClientConfig::new()
+ .set("bootstrap.servers", "127.0.0.1:1")
+ .create_with_context(KafkaContext::from(liveness))
+ .unwrap();
+ PersonHogLeaderService::new(
+ Arc::new(PartitionedCache::new(16)),
+ producer,
+ "personhog_updates".to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ 1,
+ Arc::new(DirtyIndex::new(16)),
+ Arc::new(
+ ChangelogRecovery::new(RecoveryConfig {
+ kafka,
+ topic: "personhog_updates".to_string(),
+ pod_name: "test".to_string(),
+ recv_timeout: Duration::from_millis(10),
+ pool_size: 1,
+ })
+ .expect("build recovery pool"),
+ ),
+ )
+ }
+
+ #[tokio::test]
+ async fn unmarked_miss_fails_closed_once_partition_is_released() {
+ let service = make_test_service().await;
+ let key = make_key(1, 1);
+
+ // Owned and unmarked: PG is trusted (NOT_FOUND, since the test
+ // service has no pool).
+ service.cache.create_partition(0);
+ let err = service.recover_or_load(0, &key).await.unwrap_err();
+ assert_eq!(err.code(), Code::NotFound);
+
+ // Released mid-miss (cache dropped, then marks cleared — release
+ // order): the same lookup must fail closed rather than trust a
+ // possibly-stale PG row the cleared mark no longer guards.
+ service.cache.drop_partition(0);
+ service.dirty_index.clear_partition(0);
+ let err = service.recover_or_load(0, &key).await.unwrap_err();
+ assert_eq!(err.code(), Code::FailedPrecondition);
+ }
+
#[test]
fn sweep_removes_idle_entries() {
let locks = DashMap::new();
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index 67c38c1dfa67..38bbc9c609dc 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -1,3 +1,4 @@
+use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -12,7 +13,7 @@ use tokio::time::timeout;
use personhog_coordination::error::{Error as CoordError, Result as CoordResult};
use personhog_proto::personhog::types::v1::Person;
-use crate::cache::{CachedPerson, PartitionedCache, PersonCacheKey};
+use crate::cache::{CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey};
/// Retry policy for transient warming-metadata failures.
#[derive(Clone, Copy)]
@@ -113,7 +114,7 @@ pub struct WarmingConfig {
/// durable-progress marker. Two callers reuse it: the warming consume loop
/// (which seeks explicitly per partition) and a short-lived OffsetFetch
/// query against the writer's group (which never subscribes or consumes).
-fn make_consumer(
+pub(crate) fn make_consumer(
kafka: &KafkaConfig,
group_id: &str,
) -> Result<StreamConsumer, rdkafka::error::KafkaError> {
@@ -136,34 +137,62 @@ fn make_consumer(
/// Query the writer consumer group's committed offset for a partition.
/// Returns `None` if the writer has no commit yet for the partition
/// (typical for a freshly-created topic).
+async fn fetch_writer_committed_offset(
+ kafka: &KafkaConfig,
+ writer_group: &str,
+ topic: &str,
+ partition: u32,
+ timeout: Duration,
+) -> CoordResult<Option<i64>> {
+ let offsets =
+ fetch_writer_committed_offsets(kafka, writer_group, topic, &[partition], timeout).await?;
+ Ok(offsets.get(&partition).copied())
+}
+
+/// Query the writer consumer group's committed offsets for many partitions
+/// in one OffsetFetch round-trip, with one short-lived consumer for the
+/// whole batch. Partitions without a commit are absent from the result.
+/// The batch shape suits the dirty-index prune loop, which polls every
+/// owned partition on a cadence — per-partition consumers would be
+/// constant churn.
///
/// The OffsetFetch RPC inside `committed_offsets` is synchronous in rdkafka
/// and parks the calling thread for up to `timeout`. We run it on the
/// blocking pool so a slow broker can't stall the tokio runtime.
-async fn fetch_writer_committed_offset(
+pub async fn fetch_writer_committed_offsets(
kafka: &KafkaConfig,
writer_group: &str,
topic: &str,
- partition: i32,
+ partitions: &[u32],
timeout: Duration,
-) -> CoordResult<Option<i64>> {
+) -> CoordResult<HashMap<u32, i64>> {
+ if partitions.is_empty() {
+ return Ok(HashMap::new());
+ }
let kafka = kafka.clone();
let writer_group = writer_group.to_string();
let topic = topic.to_string();
+ let partitions = partitions.to_vec();
tokio::task::spawn_blocking(move || {
let consumer = make_consumer(&kafka, &writer_group)
.map_err(|e| CoordError::invalid_state(format!("create offset query consumer: {e}")))?;
let mut tpl = TopicPartitionList::new();
- tpl.add_partition(&topic, partition);
+ for partition in &partitions {
+ tpl.add_partition(&topic, *partition as i32);
+ }
let committed = consumer
.committed_offsets(tpl, timeout)
.map_err(|e| CoordError::invalid_state(format!("committed_offsets for group: {e}")))?;
- Ok(committed
- .find_partition(&topic, partition)
- .and_then(|tp| match tp.offset() {
- Offset::Offset(o) => Some(o),
- _ => None,
- }))
+ let mut offsets = HashMap::new();
+ for partition in partitions {
+ if let Some(Offset::Offset(offset)) = committed
+ .find_partition(&topic, partition as i32)
+ .map(|tp| tp.offset())
+ {
+ offsets.insert(partition, offset);
+ }
+ }
+ Ok(offsets)
})
.await
.map_err(|e| CoordError::invalid_state(format!("offset query join: {e}")))?
@@ -208,6 +237,7 @@ fn resolve_start_offset(committed: Option<i64>, earliest: i64, lookback: i64) ->
pub async fn warm_from_kafka(
cfg: &WarmingConfig,
cache: &PartitionedCache,
+ dirty_index: &DirtyIndex,
partition: u32,
) -> CoordResult<()> {
let start = Instant::now();
@@ -223,7 +253,7 @@ pub async fn warm_from_kafka(
&cfg.kafka,
&cfg.writer_consumer_group,
&cfg.topic,
- partition_i32,
+ partition,
cfg.committed_offsets_timeout,
)
.await
@@ -293,7 +323,7 @@ pub async fn warm_from_kafka(
// entire range warms successfully. Any decode/IO failure mid-range
// aborts warming with no observable cache mutation, which keeps a
// partial cache from masking PG fallback reads.
- let mut buffered: Vec<(PersonCacheKey, CachedPerson)> = Vec::new();
+ let mut buffered: Vec<(PersonCacheKey, CachedPerson, i64)> = Vec::new();
let mut last_offset: i64 = -1;
loop {
@@ -317,25 +347,16 @@ pub async fn warm_from_kafka(
let person = <Person as ProtoMessage>::decode(payload).map_err(|e| {
CoordError::invalid_state(format!("warm decode failed at offset {offset}: {e}"))
})?;
- let properties = serde_json::from_slice(&person.properties).map_err(|e| {
+ let cached = CachedPerson::try_from(person).map_err(|e| {
CoordError::invalid_state(format!(
"warm properties decode failed at offset {offset}: {e}"
))
})?;
- let cached = CachedPerson {
- id: person.id,
- uuid: person.uuid,
- team_id: person.team_id,
- properties,
- created_at: person.created_at,
- version: person.version,
- is_identified: person.is_identified,
- };
let key = PersonCacheKey {
team_id: cached.team_id,
person_id: cached.id,
};
- buffered.push((key, cached));
+ buffered.push((key, cached, offset));
} else {
// The writer never produces null-payload (tombstone) records
// to `personhog_updates` today. If one ever appears it would
@@ -357,6 +378,27 @@ pub async fn warm_from_kafka(
}
}
+ // Records at or above the writer's committed offset are not yet in PG:
+ // seed the dirty index so that, if the cache later evicts them, a miss
+ // recovers from the changelog instead of trusting a stale PG row. With
+ // no committed offset the writer has applied nothing, so every record
+ // is marked. Seeding happens before the install publishes the
+ // partition, so no request can observe the cache without the marks.
+ let mut seeded = 0u64;
+ for (key, cached, offset) in &buffered {
+ if committed_offset.is_none_or(|committed| *offset >= committed) {
+ dirty_index.mark(
+ key.clone(),
+ DirtyMark {
+ version: cached.version,
+ offset: *offset,
+ partition,
+ },
+ );
+ seeded += 1;
+ }
+ }
+
// Atomic install: the populated `PersonCache` is built first, then a
// single `DashMap::insert` publishes it. The previous pattern
// (`create_partition` + per-record `put` loop) created a window
@@ -366,13 +408,17 @@ pub async fn warm_from_kafka(
// yet persisted. Atomicity here removes the dependency on the
// protocol invariant ("no reads during Warming") for correctness.
let count = buffered.len() as u64;
- cache.install_warmed_partition(partition, buffered);
+ cache.install_warmed_partition(
+ partition,
+ buffered.into_iter().map(|(key, cached, _)| (key, cached)),
+ );
let elapsed = start.elapsed();
tracing::info!(
pod = cfg.pod_name,
partition,
messages = count,
+ dirty_seeded = seeded,
hwm,
start_offset,
elapsed_ms = elapsed.as_millis() as u64,
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 7737ef4c39ab..bacc6a5b8466 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -25,8 +25,10 @@ use rdkafka::producer::{DefaultProducerContext, FutureProducer};
use assignment_coordination::store::{EtcdStore, StoreConfig};
use personhog_common::partitioning::partition_for_person;
-use personhog_leader::cache::{CachedPerson, PartitionedCache, PersonCacheKey};
+use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::coordination::LeaderHandoffHandler;
+use personhog_leader::inflight::InflightTracker;
+use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::PersonHogLeaderService;
use personhog_proto::personhog::leader::v1::person_hog_leader_client::PersonHogLeaderClient;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
@@ -229,6 +231,23 @@ pub fn test_warming_config(
}
}
+/// Recovery pointed at the given broker. A short receive timeout keeps
+/// tests that exercise failed recoveries fast.
+pub fn test_recovery(kafka_bootstrap: &str) -> Arc<ChangelogRecovery> {
+ let mut kafka = test_kafka_config();
+ kafka.kafka_hosts = kafka_bootstrap.to_string();
+ Arc::new(
+ ChangelogRecovery::new(RecoveryConfig {
+ kafka,
+ topic: CHANGELOG_TOPIC.to_string(),
+ pod_name: "test-pod".to_string(),
+ recv_timeout: Duration::from_secs(2),
+ pool_size: 2,
+ })
+ .expect("build recovery pool"),
+ )
+}
+
/// Create a producer against local Kafka for e2e tests.
pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
let registry = HealthRegistry::new("test");
@@ -304,10 +323,16 @@ pub async fn start_leader_pod(
// Pod with real handoff handler. Warming consumer reads from the same
// mock broker the producer is publishing to so the topic actually
// exists when warming queries watermarks.
- let inflight = Arc::new(personhog_leader::inflight::InflightTracker::new());
+ let inflight = Arc::new(InflightTracker::new());
+ // One dirty index per pod, shared by handler and service exactly as
+ // main.rs wires them: warming seeds the marks the service consults.
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ // Recovery must read the broker the service produces to.
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
+ Arc::clone(&dirty_index),
test_warming_config(name, &mock_cluster.bootstrap_servers()),
);
let pod = PodHandle::new(
@@ -331,6 +356,8 @@ pub async fn start_leader_pod(
Arc::new(DashMap::new()),
Arc::clone(&inflight),
NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ recovery,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let leader_addr = listener.local_addr().unwrap();
@@ -367,10 +394,13 @@ pub async fn start_leader_pod_with_lease_ttl(
let (mock_cluster, kafka_producer) = create_test_kafka().await;
let heartbeat_secs = (lease_ttl as u64 / 3).max(1);
- let inflight = Arc::new(personhog_leader::inflight::InflightTracker::new());
+ let inflight = Arc::new(InflightTracker::new());
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
+ Arc::clone(&dirty_index),
test_warming_config(name, &mock_cluster.bootstrap_servers()),
);
let pod = PodHandle::new(
@@ -395,6 +425,8 @@ pub async fn start_leader_pod_with_lease_ttl(
Arc::new(DashMap::new()),
Arc::clone(&inflight),
NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ recovery,
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let leader_addr = listener.local_addr().unwrap();
@@ -473,8 +505,10 @@ pub async fn start_leader_with_pg_fallback(
CHANGELOG_TOPIC.to_string(),
Some(pool),
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(&mock_cluster.bootstrap_servers()),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 791421ab998f..6dd4efe9fe2f 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -9,13 +9,15 @@ use common::{
create_leader_client, create_local_kafka_producer, create_test_kafka,
create_test_kafka_with_partitions, person_id_for_partition, seed_person, start_coordinator,
start_leader_pod, start_leader_pod_with_lease_ttl, start_leader_with_pg_fallback, start_router,
- test_cached_person, test_store, test_warming_config, wait_for_condition, CHANGELOG_TOPIC,
- KAFKA_BOOTSTRAP, NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
+ test_cached_person, test_recovery, test_store, test_warming_config, wait_for_condition,
+ CHANGELOG_TOPIC, KAFKA_BOOTSTRAP, NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
};
use personhog_common::partitioning::partition_for_person;
use personhog_coordination::pod::HandoffHandler;
use personhog_coordination::strategy::StickyBalancedStrategy;
-use personhog_leader::cache::{CacheLookup, PartitionedCache};
+use personhog_leader::cache::{
+ CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey,
+};
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
use personhog_leader::service::PersonHogLeaderService;
@@ -172,8 +174,10 @@ async fn unowned_partition_returns_failed_precondition() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -246,8 +250,10 @@ async fn missing_partition_metadata_returns_invalid_argument() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
// Warm the partition and seed the person so the only failure mode
@@ -323,8 +329,10 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
// Key (1, 42) hashes to some true partition; pick a different one and
@@ -398,6 +406,8 @@ async fn writes_fenced_after_drain_reads_still_served() {
let cache = Arc::new(PartitionedCache::new(100));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
let inflight = Arc::new(InflightTracker::new());
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(KAFKA_BOOTSTRAP);
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
kafka_producer,
@@ -406,12 +416,15 @@ async fn writes_fenced_after_drain_reads_still_served() {
Arc::new(DashMap::new()),
Arc::clone(&inflight),
NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
);
- // The handler shares the cache and inflight tracker with the service,
- // exactly as main.rs wires them.
+ // The handler shares the cache, inflight tracker, dirty index, and
+ // recovery pool with the service, exactly as main.rs wires them.
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
+ Arc::clone(&dirty_index),
test_warming_config("fence-pod", KAFKA_BOOTSTRAP),
);
@@ -502,6 +515,8 @@ async fn drain_fences_before_waiting_on_inflight() {
let cache = Arc::new(PartitionedCache::new(100));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
let inflight = Arc::new(InflightTracker::new());
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(KAFKA_BOOTSTRAP);
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
kafka_producer,
@@ -510,10 +525,13 @@ async fn drain_fences_before_waiting_on_inflight() {
Arc::new(DashMap::new()),
Arc::clone(&inflight),
NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
);
let handler = Arc::new(LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
+ Arc::clone(&dirty_index),
test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP),
));
@@ -812,12 +830,14 @@ async fn update_produces_person_state_to_kafka() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
cache.create_partition(routing_partition);
- let person = personhog_leader::cache::CachedPerson {
+ let person = CachedPerson {
id: PERSON_ID,
..test_cached_person()
};
@@ -918,8 +938,10 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
cache.create_partition(0);
@@ -969,7 +991,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
assert_eq!(result.unwrap_err().code(), tonic::Code::Internal);
// Cache was never updated since the produce failed before the cache write
- let cache_key = personhog_leader::cache::PersonCacheKey {
+ let cache_key = PersonCacheKey {
team_id: 1,
person_id: 42,
};
@@ -1022,8 +1044,10 @@ async fn e2e_update_produces_to_local_kafka() {
CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
- Arc::new(personhog_leader::inflight::InflightTracker::new()),
+ Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
);
cache.create_partition(0);
@@ -1155,15 +1179,12 @@ async fn pg_fallback_loads_person_on_cache_miss() {
assert_eq!(person.team_id, team_id as i64);
// Verify person is now cached
- let key = personhog_leader::cache::PersonCacheKey {
+ let key = PersonCacheKey {
team_id: team_id as i64,
person_id,
};
assert!(
- matches!(
- cache.get(partition, &key),
- personhog_leader::cache::CacheLookup::Found(_)
- ),
+ matches!(cache.get(partition, &key), CacheLookup::Found(_)),
"person should be cached after PG fallback"
);
@@ -1251,3 +1272,599 @@ async fn update_triggers_pg_fallback_then_applies_changes() {
cancel.cancel();
}
+
+// ============================================================
+// Dirty-index recovery: eviction of a person whose latest state
+// exists only in the changelog must recover from Kafka, never PG
+// ============================================================
+
+#[tokio::test]
+async fn evicted_dirty_person_recovers_from_changelog() {
+ const PERSON_ID: i64 = 2;
+ let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+
+ let cache = Arc::new(PartitionedCache::new(100));
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ // Recovery reads from the same mock broker the update produces to.
+ // Deliberately no PG pool: a recovery path that (wrongly) fell back to
+ // PG would return NotFound and fail the final assertion.
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
+ );
+
+ cache.create_partition(routing_partition);
+ let person = CachedPerson {
+ id: PERSON_ID,
+ ..test_cached_person()
+ };
+ seed_person(&cache, routing_partition, person);
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let mut client = create_leader_client(addr).await;
+
+ // The update produces the v2 record and marks the dirty index.
+ client
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Recovered"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(dirty_index.len(), 1, "the acked write must be marked dirty");
+
+ // Simulate eviction of the freshly written entry.
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: PERSON_ID,
+ };
+ cache.remove(routing_partition, &key);
+
+ // The read must return the updated state, recovered from the changelog
+ // record at the marked offset.
+ let response = client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ read_options: None,
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap();
+ let person = response.into_inner().person.unwrap();
+ assert_eq!(person.version, 2);
+ let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap();
+ assert_eq!(props["name"], "Recovered");
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Dirty-index recovery failure: when the changelog fetch cannot
+// complete, the person is unavailable — not silently stale
+// ============================================================
+
+#[tokio::test]
+async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {
+ const PERSON_ID: i64 = 2;
+ let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+
+ let cache = Arc::new(PartitionedCache::new(100));
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
+ );
+
+ cache.create_partition(routing_partition);
+ let person = CachedPerson {
+ id: PERSON_ID,
+ ..test_cached_person()
+ };
+ seed_person(&cache, routing_partition, person);
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let mut client = create_leader_client(addr).await;
+
+ client
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Pending"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap();
+
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: PERSON_ID,
+ };
+ // Point the mark past the HWM so the recovery fetch cannot complete
+ // (mark only accepts newer offsets, so bump well beyond the record's).
+ let mark = dirty_index.get(&key).unwrap();
+ dirty_index.mark(
+ key.clone(),
+ DirtyMark {
+ version: mark.version,
+ offset: mark.offset + 1_000,
+ partition: mark.partition,
+ },
+ );
+ cache.remove(routing_partition, &key);
+
+ let status = client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ read_options: None,
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(status.code(), tonic::Code::Unavailable);
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Dirty-index bound: a full index sheds writes for new persons
+// rather than acking writes it cannot track
+// ============================================================
+
+#[tokio::test]
+async fn writes_shed_when_dirty_index_is_full() {
+ let partition: u32 = 2;
+ let person_a = person_id_for_partition(1, partition);
+ let person_b = (person_a + 1..)
+ .find(|pid| partition_for_person(1, *pid, NUM_PARTITIONS) == partition)
+ .expect("a second person maps to the same partition");
+
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+ let cache = Arc::new(PartitionedCache::new(100));
+ // Capacity 1: the first person's mark fills the index.
+ let dirty_index = Arc::new(DirtyIndex::new(1));
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ test_recovery(&mock_cluster.bootstrap_servers()),
+ );
+
+ cache.create_partition(partition);
+ seed_person(
+ &cache,
+ partition,
+ CachedPerson {
+ id: person_a,
+ ..test_cached_person()
+ },
+ );
+ seed_person(
+ &cache,
+ partition,
+ CachedPerson {
+ id: person_b,
+ ..test_cached_person()
+ },
+ );
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let mut client = create_leader_client(addr).await;
+
+ let update_for = |person_id: i64, value: &str| UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({ "k": value })).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ };
+
+ // First person fills the index.
+ client
+ .update_person_properties(with_partition(update_for(person_a, "v1"), partition))
+ .await
+ .expect("first person's write is admitted");
+
+ // The same person stays admitted at capacity — updating its mark does
+ // not grow the index.
+ client
+ .update_person_properties(with_partition(update_for(person_a, "v2"), partition))
+ .await
+ .expect("marked person's writes stay admitted at capacity");
+
+ // A new person cannot be tracked: the write sheds instead of acking.
+ let status = client
+ .update_person_properties(with_partition(update_for(person_b, "v1"), partition))
+ .await
+ .unwrap_err();
+ assert_eq!(status.code(), tonic::Code::ResourceExhausted);
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Recovery version tripwire: a record whose version disagrees
+// with the acked mark must fail the read, never be served
+// ============================================================
+
+#[tokio::test]
+async fn recovery_fails_when_record_version_disagrees_with_the_mark() {
+ const PERSON_ID: i64 = 2;
+ let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+
+ let cache = Arc::new(PartitionedCache::new(100));
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
+ );
+
+ cache.create_partition(routing_partition);
+ let person = CachedPerson {
+ id: PERSON_ID,
+ ..test_cached_person()
+ };
+ seed_person(&cache, routing_partition, person);
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let mut client = create_leader_client(addr).await;
+
+ client
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Tripwire"}))
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap();
+
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: PERSON_ID,
+ };
+ // Corrupt the mark's version while keeping the true offset — `mark`
+ // only replaces newer offsets, so clear the partition and re-insert.
+ // The seek now lands on the right record, but its version disagrees.
+ let mark = dirty_index.get(&key).unwrap();
+ dirty_index.clear_partition(routing_partition);
+ dirty_index.mark(
+ key.clone(),
+ DirtyMark {
+ version: mark.version + 1,
+ ..mark
+ },
+ );
+ cache.remove(routing_partition, &key);
+
+ let status = client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: PERSON_ID,
+ read_options: None,
+ },
+ routing_partition,
+ ))
+ .await
+ .unwrap_err();
+ assert_eq!(status.code(), tonic::Code::Unavailable);
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Recovery consumer pooling: repeated recoveries on a partition
+// reuse one consumer, repositioning forward and backward
+// ============================================================
+
+#[tokio::test]
+async fn recovery_reuses_the_partition_consumer_across_fetches() {
+ let partition: u32 = 2;
+ let person_a = person_id_for_partition(1, partition);
+ let person_b = (person_a + 1..)
+ .find(|pid| partition_for_person(1, *pid, NUM_PARTITIONS) == partition)
+ .expect("a second person maps to the same partition");
+
+ let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
+ let cache = Arc::new(PartitionedCache::new(100));
+ let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
+ let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::clone(&dirty_index),
+ Arc::clone(&recovery),
+ );
+
+ cache.create_partition(partition);
+ for person_id in [person_a, person_b] {
+ seed_person(
+ &cache,
+ partition,
+ CachedPerson {
+ id: person_id,
+ ..test_cached_person()
+ },
+ );
+ }
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let client = create_leader_client(addr).await;
+
+ let update_for = |person_id: i64, value: &str| UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({ "who": value })).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ };
+ // A's record lands at offset 0, B's at offset 1.
+ for (person_id, value) in [(person_a, "a"), (person_b, "b")] {
+ client
+ .clone()
+ .update_person_properties(with_partition(update_for(person_id, value), partition))
+ .await
+ .unwrap();
+ }
+
+ let recover = |person_id: i64| {
+ let mut client = client.clone();
+ async move {
+ let response = client
+ .get_person(with_partition(
+ GetPersonRequest {
+ team_id: 1,
+ person_id,
+ read_options: None,
+ },
+ partition,
+ ))
+ .await
+ .unwrap();
+ let person = response.into_inner().person.unwrap();
+ let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap();
+ props["who"].as_str().unwrap().to_string()
+ }
+ };
+ let evict = |person_id: i64| {
+ cache.remove(
+ partition,
+ &PersonCacheKey {
+ team_id: 1,
+ person_id,
+ },
+ )
+ };
+
+ // All three recoveries share the partition's pooled consumer: the
+ // first fetches at offset 0, the second repositions forward, and the
+ // third repositions backward past a record the consumer already read.
+ // A consumer that fails to reposition serves the wrong record (key
+ // mismatch) or times out — either fails the unwraps above.
+ evict(person_a);
+ assert_eq!(recover(person_a).await, "a");
+ evict(person_b);
+ assert_eq!(recover(person_b).await, "b");
+ evict(person_a);
+ assert_eq!(recover(person_a).await, "a");
+
+ cancel.cancel();
+}
+
+/// A client disconnect mid-recovery drops the request future at an await
+/// point. Checkout is an RAII guard, so the cancelled fetch's consumer
+/// must come home: without Drop-based return, every cancellation leaked
+/// the consumer while freeing its permit, and pool_size cancellations
+/// left permits pointing at an empty pool — a panic under the pool mutex
+/// that poisoned it and disabled recovery until restart.
+#[tokio::test]
+async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
+ use common::test_kafka_config;
+ use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
+ use rdkafka::producer::FutureRecord;
+
+ let (mock_cluster, producer) = create_test_kafka().await;
+ let mut kafka = test_kafka_config();
+ kafka.kafka_hosts = mock_cluster.bootstrap_servers();
+ // pool_size 1: a single leaked consumer exhausts the pool.
+ let recovery = ChangelogRecovery::new(RecoveryConfig {
+ kafka,
+ topic: CHANGELOG_TOPIC.to_string(),
+ pod_name: "cancel-pod".to_string(),
+ recv_timeout: Duration::from_secs(2),
+ pool_size: 1,
+ })
+ .unwrap();
+
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: 7,
+ };
+ let mark = DirtyMark {
+ version: 1,
+ offset: 0,
+ partition: 0,
+ };
+
+ // Nothing is produced yet, so each fetch parks awaiting the record;
+ // cancel it mid-park, more times than the pool holds consumers.
+ for _ in 0..3 {
+ let cancelled = tokio::time::timeout(
+ Duration::from_millis(50),
+ recovery.fetch_person_at(&mark, &key),
+ )
+ .await;
+ assert!(
+ cancelled.is_err(),
+ "the fetch must still be parked when cancelled"
+ );
+ }
+
+ // The pool must still function end to end: produce the sought record
+ // and the next fetch — checkout included — succeeds.
+ let person = Person {
+ id: 7,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id: 1,
+ properties: serde_json::to_vec(&serde_json::json!({"k": "v"})).unwrap(),
+ properties_last_updated_at: Vec::new(),
+ properties_last_operation: Vec::new(),
+ created_at: 1_700_000_000,
+ version: 1,
+ is_identified: false,
+ is_user_id: None,
+ last_seen_at: None,
+ };
+ let payload = person.encode_to_vec();
+ producer
+ .send(
+ FutureRecord::to(CHANGELOG_TOPIC)
+ .key("1:7")
+ .partition(0)
+ .payload(&payload),
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("produce");
+
+ let recovered = recovery
+ .fetch_person_at(&mark, &key)
+ .await
+ .expect("the pool must survive cancellations");
+ assert_eq!(recovered.id, 7);
+}
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 9fccf223b299..bf35543e1173 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -8,7 +8,7 @@ use std::sync::Arc;
use std::time::Duration;
use common::{create_test_kafka, test_warming_config, CHANGELOG_TOPIC, NUM_PARTITIONS};
-use personhog_leader::cache::{CacheLookup, PartitionedCache, PersonCacheKey};
+use personhog_leader::cache::{CacheLookup, DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::warming::{warm_from_kafka, WarmingConfig};
use personhog_proto::personhog::types::v1::Person;
use prost::Message as ProtoMessage;
@@ -103,7 +103,7 @@ async fn warming_populates_cache_from_kafka() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-0", &cluster);
- warm_from_kafka(&cfg, &cache, 0)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -135,7 +135,7 @@ async fn warming_handles_empty_partition() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-empty", &cluster);
- warm_from_kafka(&cfg, &cache, 0)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming an empty partition should succeed");
@@ -167,7 +167,7 @@ async fn warming_only_populates_target_partition() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-iso", &cluster);
- warm_from_kafka(&cfg, &cache, 0)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming partition 0 should succeed");
@@ -203,7 +203,7 @@ async fn warming_fails_loudly_on_decode_error_and_leaves_cache_clean() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-decode", &cluster);
- let result = warm_from_kafka(&cfg, &cache, 0).await;
+ let result = warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0).await;
assert!(
result.is_err(),
"a malformed message must fail the entire warm"
@@ -233,7 +233,7 @@ async fn warming_works_across_all_partitions() {
let cfg = warming_config_for("warmer-all", &cluster);
for partition in 0..NUM_PARTITIONS {
- warm_from_kafka(&cfg, &cache, partition)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), partition)
.await
.unwrap_or_else(|e| panic!("warming partition {partition} failed: {e}"));
}
@@ -304,7 +304,7 @@ async fn warming_starts_from_writer_committed_offset() {
// records, defeating the point of this assertion.
cfg.lookback_offsets = 0;
- warm_from_kafka(&cfg, &cache, 0)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -367,7 +367,7 @@ async fn warming_fails_loudly_on_properties_json_error() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-bad-props", &cluster);
- let result = warm_from_kafka(&cfg, &cache, 0).await;
+ let result = warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0).await;
assert!(
result.is_err(),
"invalid JSON in properties must fail the entire warm"
@@ -409,7 +409,7 @@ async fn warming_preserves_last_write_for_same_key() {
let cache = PartitionedCache::new(100);
let cfg = warming_config_for("warmer-lww", &cluster);
- warm_from_kafka(&cfg, &cache, 0)
+ warm_from_kafka(&cfg, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("warming should succeed");
@@ -431,3 +431,84 @@ async fn warming_preserves_last_write_for_same_key() {
other => panic!("expected Found, got {:?}", std::mem::discriminant(&other)),
}
}
+
+/// When the warm range spans the writer's committed offset, only the
+/// records at or past it may be marked: marking applied ones would send
+/// their misses to the changelog for state PG already has, and skipping
+/// unapplied ones would reopen the stale-fallback hole.
+#[tokio::test]
+async fn warming_seeds_dirty_index_only_at_or_past_the_committed_offset() {
+ let (cluster, producer) = create_test_kafka().await;
+
+ // Offset N → person_id N+1.
+ for i in 0..8 {
+ let person = make_person(1, i + 1);
+ produce_person_to_partition(&producer, 0, &person).await;
+ }
+
+ // Records at offsets 0..4 are applied to PG; 5..7 are not.
+ commit_writer_offset_at(&cluster, "personhog-writer", 0, 5);
+
+ let cache = PartitionedCache::new(100);
+ let dirty_index = DirtyIndex::new(1_000_000);
+ let mut cfg = warming_config_for("warmer-seed-committed", &cluster);
+ // Rewind the warm range below the committed offset so it spans the
+ // boundary and both seeding arms are exercised.
+ cfg.lookback_offsets = 8;
+
+ warm_from_kafka(&cfg, &cache, &dirty_index, 0)
+ .await
+ .expect("warming should succeed");
+
+ assert_eq!(dirty_index.len(), 3);
+ for person_id in 1..=8 {
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id,
+ };
+ assert!(matches!(cache.get(0, &key), CacheLookup::Found(_)));
+ match dirty_index.get(&key) {
+ None => assert!(
+ person_id <= 5,
+ "person {person_id} is unapplied, must be marked"
+ ),
+ Some(mark) => {
+ assert!(
+ person_id > 5,
+ "person {person_id} is applied, must not be marked"
+ );
+ assert_eq!(mark.offset, person_id - 1);
+ }
+ }
+ }
+}
+
+/// 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
+/// trusting a PG row the writer never wrote.
+#[tokio::test]
+async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
+ let (cluster, producer) = create_test_kafka().await;
+
+ for person_id in 1..=3 {
+ let person = make_person(1, person_id);
+ produce_person_to_partition(&producer, 0, &person).await;
+ }
+
+ let cache = PartitionedCache::new(100);
+ let dirty_index = DirtyIndex::new(1_000_000);
+ let cfg = warming_config_for("warmer-seed", &cluster);
+
+ warm_from_kafka(&cfg, &cache, &dirty_index, 0)
+ .await
+ .expect("warming should succeed");
+
+ assert_eq!(
+ dirty_index.len(),
+ 3,
+ "every warmed record must be marked dirty when the writer has no commits"
+ );
+ // Marks carry the record offsets: 3 records at offsets 0..=2.
+ assert_eq!(dirty_index.max_offset(0), Some(2));
+}
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 2c7e063847e3..1aecf9ce3b40 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -90,20 +90,19 @@ target/debug/personhog-test-harness gate --leaders 3 --duration 20s \
### Known defects these scenarios reproduce
-Four real leader-path bugs surface under specific gate configurations.
+Four real leader-path bugs surfaced under specific gate configurations; two are fixed and gated, one is mostly fixed, one remains open.
They are documented here so red or noisy runs read as signal, not harness flakiness.
-**Cache eviction under writer lag loses acked writes — the gate goes RED.**
+**Cache eviction under writer lag loses acked writes — FIXED, now a CI regression gate.**
`--cache-capacity` sets the leader cache size in entries; below `--persons` it forces eviction of dirty entries whose writes the writer has not yet flushed.
-The next operation reloads the stale Postgres row, later merges build on the stale base, and acked writes disappear — exactly what the journal catches:
+Every operation used to reload the stale Postgres row on the next miss, later merges built on the stale base, and acked writes disappeared (this exact configuration once produced 4,886 violations).
+The leader now marks every acked produce in a dirty index and recovers evicted marked persons from their changelog record instead of trusting PG; the scenario runs in CI (with a writer pause to guarantee the lag) and must stay green:
```bash
-# Expect thousands of violations until the eviction hazard is fixed
-target/debug/personhog-test-harness gate --persons 50 --cache-capacity 10 --duration 10s
+target/debug/personhog-test-harness gate --leaders 3 --partitions 8 --persons 50 \
+ --cache-capacity 10 --duration 15s --writer-pause-after 3s --writer-pause-duration 8s
```
-Fix direction: pin dirty entries until the writer's committed offset passes their produce offset (see the TODO in `personhog-leader/src/cache/persons.rs`).
-
**Graceful shutdown black-holes the leader's partitions — FIXED via lifecycle shutdown phases.**
The leader's lifecycle manager used to signal every component at SIGTERM simultaneously, so the gRPC server and Kafka producer finished shutting down (~160ms) long before the coordination drain handed partitions off, leaving the pod a registered owner with a dead server for the whole drain (~1% failed writes per drain).
The lifecycle crate now supports ordered shutdown phases (`ComponentOptions::with_shutdown_phase`): coordination drains in phase 0 while the server keeps serving and the producer keeps delivering, and both stop in phase 1 once the partitions are handed off.
@@ -146,6 +145,18 @@ target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 18s
Verification still waits for convergence (bounded at 90s) before asserting strong reads; red here means convergence itself failed.
Remaining scope: draining pods should be excluded as rebalance targets (now mere churn rather than a black hole — a mid-drain rebalance can hand partitions to a pod that immediately re-drains them), and one stuck handoff should not defer all rebalancing.
+**Follow-up: coalesce changelog recovery fetches if the pool ever queues.**
+Recoveries check out one pooled consumer per person, so N concurrent misses on genuinely-behind persons cost N sequential Kafka point-reads once the pool saturates.
+The changelog is offset-ordered, so a batch executor could assign one consumer at the lowest pending offset per partition and satisfy every waiter it passes in a single sweep (group-commit shape; bound the sweep span so sparse marks don't degenerate into scanning the gap between them).
+Build this only when `personhog_leader_recovery_pool_wait_ms` shows sustained queuing.
+Considered and rejected instead: a PG-first version check on marked misses (serve PG when its row version reaches the mark's).
+Routing it off the prune loop's committed-offset snapshot is circular — every mark below the snapshot was already pruned by the same tick that produced it — and an unconditional PG-first probe taxes exactly the writer-lag bursts it can't help, while the 1s prune interval already shrinks its target window (applied-but-unpruned marks) to about a second.
+
+**Follow-up: partition ownership should be invisible to clients.**
+A leader refuses requests it cannot safely serve — a write against a fenced partition, or a read that races a release (both refuse *before* any state changes, so a redirect cannot double-apply) — and today those refusals propagate to the client as `FAILED_PRECONDITION`.
+The router should absorb them instead: detect the not-owned refusal in the raw-proxy response (a typed header from the leader, not status-code matching), and re-stash the request if a handoff is in flight for the partition, else re-resolve the owner and retry once.
+Most of the gate's residual failed writes during handoff scenarios are these refusals; with the redirect in place those counts become hard zero-failure invariants.
+
## `seed` / `cleanup` — manage traffic targets
```bash
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index cfcbfb856e50..982720d52232 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -246,6 +246,11 @@ pub struct GateArgs {
#[arg(long, default_value_t = 100_000)]
pub cache_capacity: usize,
+ /// Recovery consumer pool size for spawned leaders
+ /// (RECOVERY_POOL_SIZE) — bounds concurrent changelog recoveries.
+ #[arg(long, default_value_t = 16)]
+ pub recovery_pool_size: usize,
+
/// etcd lease TTL for spawned leaders, in seconds. The production
/// default is 30; lower it (5s works) so a TTL-expiry kill
/// (--kill-fast false) doesn't need a 30s+ outage window mid-run.
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index e6060ccb1484..e2781a3e0b4b 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -160,6 +160,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
writer_flush_interval_ms: 1000,
pg_target_table: args.pg_target_table.clone(),
cache_memory_capacity: args.cache_capacity,
+ recovery_pool_size: args.recovery_pool_size,
leader_lease_ttl: args.leader_lease_ttl,
})
.await?,
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 7be31652c4b2..3d41b81573c9 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -53,6 +53,7 @@ pub struct StackConfig {
/// Leader in-memory cache capacity (entries). Lower it below the seeded
/// person count to put the cache under eviction pressure.
pub cache_memory_capacity: usize,
+ pub recovery_pool_size: usize,
/// etcd lease TTL for leaders, in seconds. Bounds how long a crashed
/// (unrevoked) leader stays the registered owner.
pub leader_lease_ttl: i64,
@@ -254,6 +255,10 @@ impl Stack {
"CACHE_MEMORY_CAPACITY",
self.config.cache_memory_capacity.to_string(),
),
+ (
+ "RECOVERY_POOL_SIZE",
+ self.config.recovery_pool_size.to_string(),
+ ),
("ETCD_ENDPOINTS", self.config.etcd_endpoints.clone()),
("ETCD_PREFIX", ETCD_PREFIX.to_string()),
("KAFKA_HOSTS", self.config.kafka_hosts.clone()),