: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(personhog): stream warms into a budget-bounded cache (#82260)
Zach Brown5a9b46ae7267
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rsindex f53a1c4e05f5..97fc9013a9cd 100644--- a/rust/personhog-leader/src/cache/partitioned.rs+++ b/rust/personhog-leader/src/cache/partitioned.rs@@ -18,6 +18,13 @@ pub enum CacheLookup {/// Foyer cache so that releasing a partition drops all its entries cleanly.pub struct PartitionedCache {partitions: DashMap<u32, PersonCache>,+ /// Partitions mid-warm: built here record by record — evicting under+ /// the same per-partition byte budget as a serving cache — and moved+ /// to `partitions` in a single insert when the warm's range+ /// completes. Entirely invisible to readers: `get`/`has_partition`+ /// consult `partitions` only, so a partition under construction+ /// answers `PartitionNotOwned` on every path.+ warming: DashMap<u32, PersonCache>,per_partition_capacity: usize,}@@ -25,6 +32,7 @@ impl PartitionedCache {pub fn new(per_partition_capacity: usize) -> Self {Self {partitions: DashMap::new(),+ warming: DashMap::new(),per_partition_capacity,}}@@ -49,21 +57,74 @@ impl PartitionedCache {partition: u32,records: impl IntoIterator<Item = (PersonCacheKey, CachedPerson)>,) {- let cache = PersonCache::new(self.per_partition_capacity);+ self.begin_warm_partition(partition);for (key, person) in records {- cache.put(key, person);+ self.warm_put(partition, key, person);}+ self.publish_warmed_partition(partition);+ }++ /// Start building a partition's cache without publishing it. The+ /// warm inserts record by record with `warm_put` — bounded by the+ /// per-partition budget, evicting as it goes — and publishes the+ /// finished cache with `publish_warmed_partition`. Re-entrant: a+ /// retried warm begins fresh, replacing any half-built predecessor.+ pub fn begin_warm_partition(&self, partition: u32) {+ self.warming+ .insert(partition, PersonCache::new(self.per_partition_capacity));+ }++ /// Insert one record into a partition cache under construction.+ pub fn warm_put(&self, partition: u32, key: PersonCacheKey, person: CachedPerson) {+ self.warming+ .get(&partition)+ .expect("warm_put before begin_warm_partition")+ .put(key, person);+ }++ /// Publish a fully-built partition cache: one `DashMap` insert flips+ /// the partition from invisible to fully observable, preserving the+ /// no-partial-window property `install_warmed_partition` documents.+ pub fn publish_warmed_partition(&self, partition: u32) {+ let (_, cache) = self+ .warming+ .remove(&partition)+ .expect("publish_warmed_partition before begin_warm_partition");self.partitions.insert(partition, cache);}- /// Drop the cache for the given partition, evicting all entries.+ /// Discard a partition cache under construction (a warm that failed+ /// mid-range). Nothing was ever observable.+ pub fn abort_warm_partition(&self, partition: u32) {+ self.warming.remove(&partition);+ }++ /// Resident weight of a build in flight — what the warm retained of+ /// its range under the budget.+ pub fn warm_usage_bytes(&self, partition: u32) -> usize {+ self.warming+ .get(&partition)+ .map(|c| c.usage_bytes())+ .unwrap_or(0)+ }++ /// Drop the cache for the given partition, evicting all entries —+ /// including a build in flight, so a release racing a warm leaves+ /// nothing behind.pub fn drop_partition(&self, partition: u32) {self.partitions.remove(&partition);+ self.warming.remove(&partition);}- /// Total resident weight in bytes across all owned partitions.+ /// Total resident weight in bytes across all owned partitions,+ /// builds in flight included — the gauge tells the truth during+ /// warms rather than hiding the construction cost.pub fn usage_bytes(&self) -> usize {- self.partitions.iter().map(|c| c.usage_bytes()).sum()+ self.partitions+ .iter()+ .map(|c| c.usage_bytes())+ .sum::<usize>()+ + self.warming.iter().map(|c| c.usage_bytes()).sum::<usize>()}/// Check if a partition cache exists (i.e., the partition is owned).diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rsindex 23d177bbbc0f..73e80edb641e 100644--- a/rust/personhog-leader/src/warming.rs+++ b/rust/personhog-leader/src/warming.rs@@ -385,6 +385,29 @@ fn record_warm_span(span: &'static str, start: Instant) {.record(start.elapsed().as_secs_f64() * 1000.0);}+/// Cancellation-safe cleanup for a warm in flight. The coordination loop+/// drops warms on lease loss and shutdown, and a dropped future never+/// reaches code after its await points — so the abort of the unpublished+/// build and the clearing of this partition's seeded dirty marks live in+/// `Drop`, which runs on every exit: error, panic, and cancellation.+/// Disarmed immediately before the publish, when the state stops being+/// residue and becomes the partition's serving truth.+struct WarmCleanup<'a> {+ cache: &'a PartitionedCache,+ dirty_index: &'a DirtyIndex,+ partition: u32,+ armed: bool,+}++impl Drop for WarmCleanup<'_> {+ fn drop(&mut self) {+ if self.armed {+ self.cache.abort_warm_partition(self.partition);+ self.dirty_index.clear_partition(self.partition);+ }+ }+}+/// Populate the cache from Kafka for a single partition.////// Invariants at call time (enforced by the handoff protocol). The@@ -513,11 +536,31 @@ pub async fn warm_from_kafka(.assign(&assign_tpl).map_err(|e| CoordError::invalid_state(format!("consumer assign: {e}")))?;- // Buffer records locally and only commit them to the cache after the- // 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, i64)> = Vec::new();+ // Stream records straight into an unpublished partition cache: the+ // build evicts under the same per-partition byte budget as a serving+ // cache, so the warm's peak memory is bounded no matter how large+ // the range is. Each record writes its dirty mark BEFORE its insert,+ // so at every instant an evicted unapplied person is already+ // recoverable from the changelog — the same miss path a serving+ // partition relies on. Nothing is observable until the publish at+ // the end.+ cache.begin_warm_partition(partition);+ // Every non-published exit — an error, a panic, or the coordination+ // loop dropping this future on lease loss or shutdown (the+ // cancellation `HandoffHandler::warm_partition`'s contract names) —+ // must leave no trace: the guard aborts the build and clears the+ // partition's seeded marks on drop. A stale mark surviving into a+ // later acquisition would redirect a miss to a superseded changelog+ // offset; the re-warm only overwrites marks for records past the+ // writer's *new* committed offset, so it cannot heal one.+ let mut cleanup = WarmCleanup {+ cache,+ dirty_index,+ partition,+ armed: true,+ };+ let mut consumed: u64 = 0;+ let mut seeded = 0u64;let mut last_offset: i64 = -1;// A transactionally-produced range can end in control records@@ -529,7 +572,10 @@ pub async fn warm_from_kafka(let poll_slice = Duration::from_millis(100).min(cfg.recv_timeout);let mut quiet_since = Instant::now();- loop {+ // `return` inside this block exits the block, not the function: a+ // failure propagates through `?` below and the guard cleans up.+ let consume_result: CoordResult<()> = async {+ loop {let msg = match timeout(poll_slice, consumer.recv()).await {Ok(Ok(m)) => m,// A non-fatal consumer error means librdkafka is handling it:@@ -566,8 +612,7 @@ pub async fn warm_from_kafka(if quiet_since.elapsed() >= cfg.recv_timeout {return Err(CoordError::invalid_state(format!("warm stalled on repeated consumer errors (last: {code:?}); \- consumed {count} msgs, last_offset={last_offset}, hwm={hwm}",- count = buffered.len()+ consumed {consumed} msgs, last_offset={last_offset}, hwm={hwm}",)));}counter!(@@ -602,8 +647,7 @@ pub async fn warm_from_kafka(}if quiet_since.elapsed() >= cfg.recv_timeout {return Err(CoordError::invalid_state(format!(- "warm timeout; consumed {count} msgs, last_offset={last_offset}, hwm={hwm}",- count = buffered.len()+ "warm timeout; consumed {consumed} msgs, last_offset={last_offset}, hwm={hwm}",)));}continue;@@ -627,7 +671,23 @@ pub async fn warm_from_kafka(team_id: cached.team_id,person_id: cached.id,};- buffered.push((key, cached, offset));+ consumed += 1;+ // Records at or past the writer's committed offset are not+ // yet in PG: mark before insert, so if the build evicts this+ // person a later miss recovers from the changelog instead of+ // trusting a stale PG row.+ if committed_offset.is_none_or(|committed| offset >= committed) {+ dirty_index.mark(+ key.clone(),+ DirtyMark {+ version: cached.version,+ offset,+ partition,+ },+ );+ seeded += 1;+ }+ cache.warm_put(partition, key, cached);} else {// The writer never produces null-payload (tombstone) records// to `personhog_updates` today. If one ever appears it would@@ -647,50 +707,36 @@ pub async fn warm_from_kafka(if offset + 1 >= hwm {break;}+ }+ Ok(())}+ .await;+ consume_result?;record_warm_span("consume", span_start);- // 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+ // Atomic publish: one `DashMap` insert flips the fully-built cache+ // from invisible to observable. The previous pattern// (`create_partition` + per-record `put` loop) created a window// where readers could observe `has_partition == true` while the// cache was still being populated, and then fall through to PG —// potentially returning stale values for records the writer hasn't- // yet persisted. Atomicity here removes the dependency on the+ // yet persisted. Publishing at the end 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.into_iter().map(|(key, cached, _)| (key, cached)),- );+ let resident_bytes = cache.warm_usage_bytes(partition) as u64;+ // Disarm before the publish: from here the marks and the cache are+ // the partition's serving state, not warm residue. No await sits+ // between the disarm and the publish, so no cancellation can land+ // in between.+ cleanup.armed = false;+ cache.publish_warmed_partition(partition);let elapsed = start.elapsed();tracing::info!(pod = cfg.pod_name,partition,- messages = count,+ messages = consumed,+ resident_bytes,dirty_seeded = seeded,hwm,start_offset,@@ -698,7 +744,7 @@ pub async fn warm_from_kafka("warmed partition from kafka");histogram!("personhog_leader_warm_duration_ms").record(elapsed.as_secs_f64() * 1000.0);- counter!("personhog_leader_warmed_messages_total").increment(count);+ counter!("personhog_leader_warmed_messages_total").increment(consumed);// Every error path above dropped the consumer instead of returning// it — a client that just failed is not pool material. Failing to@@ -722,6 +768,112 @@ mod tests {max_backoff: Duration::from_secs(5),};+ fn warm_test_person() -> CachedPerson {+ CachedPerson {+ id: 42,+ uuid: "00000000-0000-0000-0000-000000000042".to_string(),+ team_id: 1,+ properties: b"{}".to_vec(),+ created_at: 0,+ version: 1,+ is_identified: false,+ is_deleted: false,+ last_seen_at: None,+ approx_bytes: crate::cache::approx_person_bytes(2),+ }+ }++ /// The coordination loop cancels a warm by dropping its future, which+ /// never reaches code after an await point — so the cleanup lives in+ /// `WarmCleanup::drop`, and this pins that it runs. A surviving build+ /// pins memory for a partition this pod never serves; a surviving mark+ /// outlives re-acquisition, because the next warm only overwrites+ /// marks past the writer's committed offset by then, and redirects a+ /// later cache miss to a superseded changelog offset.+ #[test]+ fn dropping_an_armed_cleanup_clears_the_build_and_its_marks() {+ let cache = PartitionedCache::new(1 << 20);+ let dirty_index = DirtyIndex::new(1_000);+ let key = PersonCacheKey {+ team_id: 1,+ person_id: 42,+ };++ cache.begin_warm_partition(0);+ {+ let _cleanup = WarmCleanup {+ cache: &cache,+ dirty_index: &dirty_index,+ partition: 0,+ armed: true,+ };+ dirty_index.mark(+ key.clone(),+ DirtyMark {+ version: 1,+ offset: 7,+ partition: 0,+ },+ );+ cache.warm_put(0, key.clone(), warm_test_person());+ }++ assert!(+ dirty_index.get(&key).is_none(),+ "a cancelled warm must clear the marks it seeded"+ );+ assert_eq!(+ cache.usage_bytes(),+ 0,+ "a cancelled warm must leave no build in flight"+ );+ assert!(!cache.has_partition(0), "nothing may have published");+ }++ /// The mirror: once the warm publishes, the marks and the cache are+ /// the partition's serving state rather than warm residue, so the+ /// disarmed guard must leave both alone.+ #[test]+ fn dropping_a_disarmed_cleanup_leaves_the_published_partition_alone() {+ let cache = PartitionedCache::new(1 << 20);+ let dirty_index = DirtyIndex::new(1_000);+ let key = PersonCacheKey {+ team_id: 1,+ person_id: 42,+ };++ cache.begin_warm_partition(0);+ {+ let mut cleanup = WarmCleanup {+ cache: &cache,+ dirty_index: &dirty_index,+ partition: 0,+ armed: true,+ };+ dirty_index.mark(+ key.clone(),+ DirtyMark {+ version: 1,+ offset: 7,+ partition: 0,+ },+ );+ cache.warm_put(0, key.clone(), warm_test_person());+ cleanup.armed = false;+ cache.publish_warmed_partition(0);+ }++ assert!(+ dirty_index.get(&key).is_some(),+ "a published partition keeps its marks"+ );+ assert!(cache.has_partition(0), "the partition stays published");+ assert!(matches!(+ cache.get(0, &key),+ crate::cache::CacheLookup::Found(_)+ ));+ }+#[test]fn resolve_uses_committed_minus_lookback() {assert_eq!(resolve_start_offset(Some(500), 0, 100), 400);diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rsindex eecb5de9c587..b6674ca433f3 100644--- a/rust/personhog-leader/tests/warming_integration.rs+++ b/rust/personhog-leader/tests/warming_integration.rs@@ -384,7 +384,8 @@ async fn warming_fails_loudly_on_properties_json_error() {let cache = PartitionedCache::new(1 << 20);let (cfg, pools) = warming_config_for("warmer-bad-props", &cluster);- let result = warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0).await;+ let dirty_index = DirtyIndex::new(1_000_000);+ let result = warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0).await;assert!(result.is_err(),"invalid JSON in properties must fail the entire warm"@@ -398,6 +399,17 @@ async fn warming_fails_loudly_on_properties_json_error() {!cache.has_partition(0),"atomic commit: cache must not have been touched on JSON failure");+ // Marks are written per record as the range streams; a failed warm+ // must clear them — orphaned marks for a partition this pod never+ // serves would pin memory and mislead a later owner's bookkeeping.+ assert_eq!(+ dirty_index.get(&PersonCacheKey {+ team_id: 1,+ person_id: 1,+ }),+ None,+ "a failed warm must leave no dirty marks behind"+ );}/// Last-write-wins: the changelog can contain multiple updates for the@@ -426,7 +438,8 @@ async fn warming_preserves_last_write_for_same_key() {let cache = PartitionedCache::new(1 << 20);let (cfg, pools) = warming_config_for("warmer-lww", &cluster);- warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)+ let dirty_index = DirtyIndex::new(1_000_000);+ warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0).await.expect("warming should succeed");@@ -448,6 +461,11 @@ async fn warming_preserves_last_write_for_same_key() {}other => panic!("expected Found, got {:?}", std::mem::discriminant(&other)),}+ // The dirty mark must carry the latest version too: the buffer keys+ // by person, and a wrong-version-wins regression would surface here+ // as a stale mark even while the cache looks right.+ let mark = dirty_index.get(&key).expect("person must be marked dirty");+ assert_eq!(mark.version, 3, "dirty mark must carry the latest version");}/// When the warm range spans the writer's committed offset, only the@@ -668,3 +686,59 @@ async fn warming_still_fails_on_a_persistent_stop_class_error() {"a failed warm must install nothing");}++/// The warm's memory contract: the build evicts under the partition's+/// byte budget, so a range larger than the budget still warms — with a+/// partial cache — while EVERY unapplied person gets a dirty mark. The+/// marks are what make the evictions safe: a miss on a marked person+/// recovers from the changelog instead of trusting a stale PG row, so+/// full mark coverage under eviction is the invariant that lets the+/// warm survive a backlog-sized range without holding it in memory.+#[tokio::test]+async fn warming_a_range_larger_than_the_budget_marks_every_person() {+ let (cluster, producer) = create_test_kafka().await;++ // Forty persons with ~4KB of properties each — far past the tiny+ // budget below — with no writer committed offset, so every record+ // counts as unapplied.+ let persons = 40i64;+ for person_id in 1..=persons {+ let mut person = make_person(1, person_id);+ person.properties = serde_json::to_vec(&serde_json::json!({+ "email": format!("p{person_id}@example.com"),+ "padding": "x".repeat(4096),+ }))+ .unwrap();+ produce_person_to_partition(&producer, 0, &person).await;+ }++ let budget_bytes = 16 * 1024;+ let cache = PartitionedCache::new(budget_bytes);+ let (cfg, pools) = warming_config_for("warmer-bounded", &cluster);+ let dirty_index = DirtyIndex::new(1_000_000);++ warm_from_kafka(&cfg, &pools, &cache, &dirty_index, 0)+ .await+ .expect("a range larger than the budget must still warm");++ assert!(cache.has_partition(0), "the partition must publish");+ let mut resident = 0;+ for person_id in 1..=persons {+ let key = PersonCacheKey {+ team_id: 1,+ person_id,+ };+ if matches!(cache.get(0, &key), CacheLookup::Found(_)) {+ resident += 1;+ }+ assert!(+ dirty_index.get(&key).is_some(),+ "person {person_id} must be marked dirty even if evicted"+ );+ }+ assert!(+ resident < persons,+ "the budget must have evicted something ({resident}/{persons} resident) — \+ if everything fit, this test no longer exercises eviction"+ );+}