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): zstd dictionary compression for the leader cache (#114391)

José Sequeira2b85bc84f1fb
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 00ecab6eeb46..f279c300e451 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -750,11 +750,12 @@ jobs:
--leaders 3 --partitions 8 --persons 50 --concurrency 10 --duration 15s \
--cache-capacity 4096 --writer-pause-after 3s --writer-pause-duration 8s
- - name: Run the e2e gate under chaos (kill + scale-up)
+ - name: Run the e2e gate under chaos (kill + scale-up) with cache compression
run: |
./target/debug/personhog-test-harness gate \
--leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 15s \
- --kill-after 5s --scale-up-after 8s
+ --kill-after 5s --scale-up-after 8s \
+ --leader-env CACHE_PROPERTIES_COMPRESSION_ENABLED=true
- name: Run the e2e gate under chaos (drain + zombie + writer lag)
run: |
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index bd6fa7ec4d9b..f61452a6e2a3 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8993,6 +8993,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
+ "zstd 0.13.3",
]
[[package]]
diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.toml
index 20937bec5f95..0a56b2e97398 100644
--- a/rust/personhog-leader/Cargo.toml
+++ b/rust/personhog-leader/Cargo.toml
@@ -41,6 +41,7 @@ tonic = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
uuid = { workspace = true }
+zstd = { workspace = true }
[features]
# Adversarial states the integration tests need to construct but that no
diff --git a/rust/personhog-leader/src/cache/codec.rs b/rust/personhog-leader/src/cache/codec.rs
new file mode 100644
index 000000000000..c4f899bd9330
--- /dev/null
+++ b/rust/personhog-leader/src/cache/codec.rs
@@ -0,0 +1,354 @@
+use std::cell::RefCell;
+use std::io;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock, PoisonError};
+use std::thread::JoinHandle;
+use std::time::Instant;
+
+use metrics::counter;
+use zstd::zstd_safe::{get_error_name, CCtx, CDict, CParameter, DCtx, DDict, ResetDirective};
+
+/// Below this, zstd frame headers cost more than the dictionary saves.
+const MIN_COMPRESSIBLE_BYTES: usize = 64;
+
+/// Larger documents would fill the sample budget with outliers.
+const MAX_SAMPLE_BYTES: usize = 16 * 1024;
+
+/// zstd recommends samples of about 100 times the dictionary size.
+const SAMPLE_BUDGET_BYTES: usize = 4 * 1024 * 1024;
+const MIN_SAMPLES: usize = 1_000;
+
+const DICTIONARY_MAX_BYTES: usize = 32 * 1024;
+
+const COMPRESSION_LEVEL: i32 = 3;
+
+pub(super) enum StoredProperties {
+ Raw(Box<[u8]>),
+ /// The frame omits the content size, so `raw_len` sizes the output buffer.
+ ZstdDict {
+ compressed: Box<[u8]>,
+ raw_len: u32,
+ },
+}
+
+impl StoredProperties {
+ pub(super) fn raw_len(&self) -> usize {
+ match self {
+ Self::Raw(bytes) => bytes.len(),
+ Self::ZstdDict { raw_len, .. } => *raw_len as usize,
+ }
+ }
+
+ pub(super) fn stored_len(&self) -> usize {
+ match self {
+ Self::Raw(bytes) => bytes.len(),
+ Self::ZstdDict { compressed, .. } => compressed.len(),
+ }
+ }
+}
+
+/// Enabled, it samples the first documents it encodes, trains one
+/// dictionary from them, and compresses later documents with it.
+/// Documents encoded before that, or after a failed training, stay raw.
+pub(super) struct PropertiesCodec {
+ /// Checked before the sample lock, so puts after the hand-off skip it.
+ sampling: AtomicBool,
+ samples: Mutex<Samples>,
+ dictionary: Arc<OnceLock<Dictionary>>,
+ training: Mutex<Option<JoinHandle<()>>>,
+}
+
+impl PropertiesCodec {
+ pub(super) fn disabled() -> Self {
+ Self::new(false)
+ }
+
+ pub(super) fn enabled() -> Self {
+ Self::new(true)
+ }
+
+ fn new(sampling: bool) -> Self {
+ Self {
+ sampling: AtomicBool::new(sampling),
+ samples: Mutex::new(Samples::default()),
+ dictionary: Arc::new(OnceLock::new()),
+ training: Mutex::new(None),
+ }
+ }
+
+ pub(super) fn encode(&self, raw: Vec<u8>) -> StoredProperties {
+ if raw.len() >= MIN_COMPRESSIBLE_BYTES {
+ if let Some(dictionary) = self.dictionary.get() {
+ if let Some(stored) = dictionary.compress(&raw) {
+ return stored;
+ }
+ } else if self.sampling.load(Ordering::Relaxed) {
+ self.sample(&raw);
+ }
+ }
+ StoredProperties::Raw(raw.into_boxed_slice())
+ }
+
+ pub(super) fn decode(&self, stored: &StoredProperties) -> Result<Vec<u8>, &'static str> {
+ match stored {
+ StoredProperties::Raw(bytes) => Ok(bytes.to_vec()),
+ StoredProperties::ZstdDict {
+ compressed,
+ raw_len,
+ } => self
+ .dictionary
+ .get()
+ .ok_or("entry is compressed but the codec has no dictionary")?
+ .decompress(compressed, *raw_len as usize),
+ }
+ }
+
+ fn sample(&self, raw: &[u8]) {
+ if raw.len() > MAX_SAMPLE_BYTES {
+ return;
+ }
+ let mut samples = self.samples.lock().unwrap_or_else(PoisonError::into_inner);
+ // Another put may have handed the samples off since the caller checked.
+ if !self.sampling.load(Ordering::Relaxed) {
+ return;
+ }
+ samples.data.extend_from_slice(raw);
+ samples.sizes.push(raw.len());
+ if samples.data.len() < SAMPLE_BUDGET_BYTES || samples.sizes.len() < MIN_SAMPLES {
+ return;
+ }
+ self.sampling.store(false, Ordering::Relaxed);
+ let samples = std::mem::take(&mut *samples);
+ let dictionary = Arc::clone(&self.dictionary);
+ // Training would stall an async worker for its whole run.
+ let spawned = std::thread::Builder::new()
+ .name("personhog-cache-dictionary".to_string())
+ .spawn(move || train_and_install(samples, &dictionary));
+ match spawned {
+ Ok(handle) => {
+ *self.training.lock().unwrap_or_else(PoisonError::into_inner) = Some(handle);
+ }
+ Err(e) => record_training_failure(&e),
+ }
+ }
+
+ #[cfg(test)]
+ fn with_dictionary(dictionary: Dictionary) -> Self {
+ let codec = Self::disabled();
+ assert!(codec.dictionary.set(dictionary).is_ok());
+ codec
+ }
+
+ #[cfg(test)]
+ fn wait_for_training(&self) -> bool {
+ if let Some(handle) = self.training.lock().unwrap().take() {
+ handle.join().expect("training thread panicked");
+ }
+ self.dictionary.get().is_some()
+ }
+}
+
+#[derive(Default)]
+struct Samples {
+ data: Vec<u8>,
+ sizes: Vec<usize>,
+}
+
+fn train_and_install(samples: Samples, slot: &OnceLock<Dictionary>) {
+ let started = Instant::now();
+ match Dictionary::train(&samples) {
+ Ok(dictionary) => {
+ let dictionary_bytes = dictionary.content_len;
+ slot.get_or_init(|| dictionary);
+ counter!("personhog_leader_cache_dictionary_trainings_total", "outcome" => "ok")
+ .increment(1);
+ tracing::info!(
+ samples = samples.sizes.len(),
+ sample_bytes = samples.data.len(),
+ dictionary_bytes,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "trained person properties compression dictionary"
+ );
+ }
+ Err(e) => record_training_failure(&e),
+ }
+}
+
+fn record_training_failure(error: &io::Error) {
+ counter!("personhog_leader_cache_dictionary_trainings_total", "outcome" => "error")
+ .increment(1);
+ tracing::warn!(
+ error = %error,
+ "person properties dictionary training failed; cache entries stay uncompressed"
+ );
+}
+
+struct Dictionary {
+ cdict: CDict<'static>,
+ ddict: DDict<'static>,
+ content_len: usize,
+}
+
+impl Dictionary {
+ fn train(samples: &Samples) -> io::Result<Self> {
+ let content =
+ zstd::dict::from_continuous(&samples.data, &samples.sizes, DICTIONARY_MAX_BYTES)?;
+ let cdict = CDict::try_create(&content, COMPRESSION_LEVEL)
+ .ok_or_else(|| io::Error::other("zstd could not prepare the compression dictionary"))?;
+ let ddict = DDict::try_create(&content).ok_or_else(|| {
+ io::Error::other("zstd could not prepare the decompression dictionary")
+ })?;
+ Ok(Self {
+ cdict,
+ ddict,
+ content_len: content.len(),
+ })
+ }
+
+ /// `None` when the output would not be smaller than the input.
+ fn compress(&self, raw: &[u8]) -> Option<StoredProperties> {
+ let raw_len = u32::try_from(raw.len()).ok()?;
+ COMPRESSOR.with_borrow_mut(|cctx| {
+ // Sized to the input, so zstd fails rather than write output that does not shrink.
+ let mut compressed = Vec::with_capacity(raw.len());
+ let written = cctx
+ .ref_cdict(&self.cdict)
+ .and_then(|_| cctx.compress2(&mut compressed, raw));
+ // A failed frame leaves the context mid-session, where it refuses any dictionary change.
+ cctx.reset(ResetDirective::SessionOnly)
+ .expect("zstd documents that a session reset never fails");
+ // The thread-local context outlives the dictionary, so it must not keep a pointer to it.
+ cctx.disable_dictionary()
+ .expect("a context in its init stage accepts a dictionary change");
+ written.ok()?;
+ (compressed.len() < raw.len()).then(|| StoredProperties::ZstdDict {
+ compressed: compressed.into_boxed_slice(),
+ raw_len,
+ })
+ })
+ }
+
+ fn decompress(&self, compressed: &[u8], raw_len: usize) -> Result<Vec<u8>, &'static str> {
+ DECOMPRESSOR.with_borrow_mut(|dctx| {
+ let mut raw = Vec::with_capacity(raw_len);
+ dctx.decompress_using_ddict(&mut raw, compressed, &self.ddict)
+ .map_err(get_error_name)?;
+ if raw.len() != raw_len {
+ return Err("decompressed length differs from the recorded length");
+ }
+ Ok(raw)
+ })
+ }
+}
+
+thread_local! {
+ static COMPRESSOR: RefCell<CCtx<'static>> = RefCell::new(new_compressor());
+ static DECOMPRESSOR: RefCell<DCtx<'static>> = RefCell::new(DCtx::create());
+}
+
+fn new_compressor() -> CCtx<'static> {
+ let mut cctx = CCtx::create();
+ // The entry stores the raw length, and the codec has one dictionary.
+ cctx.set_parameter(CParameter::ContentSizeFlag(false))
+ .expect("content size flag is a valid zstd parameter");
+ cctx.set_parameter(CParameter::DictIdFlag(false))
+ .expect("dictionary id flag is a valid zstd parameter");
+ cctx
+}
+
+#[cfg(test)]
+pub(super) mod tests {
+ use super::*;
+
+ pub(in crate::cache) fn person_properties(seed: usize) -> Vec<u8> {
+ let browsers = ["Chrome", "Safari", "Firefox", "Microsoft Edge"];
+ let systems = ["Mac OS X", "Windows", "iOS", "Android", "Linux"];
+ let countries = [("US", "United States"), ("DE", "Germany"), ("BR", "Brazil")];
+ let browser = browsers[seed % browsers.len()];
+ let os = systems[seed % systems.len()];
+ let (country_code, country) = countries[seed % countries.len()];
+ let url = format!("https://example.com/docs/page-{}?ref={}", seed % 211, seed);
+ serde_json::to_vec(&serde_json::json!({
+ "$browser": browser,
+ "$browser_version": 100 + seed % 30,
+ "$current_url": url,
+ "$device_type": if seed.is_multiple_of(3) { "Mobile" } else { "Desktop" },
+ "$geoip_country_code": country_code,
+ "$geoip_country_name": country,
+ "$geoip_city_name": format!("City {}", seed % 53),
+ "$geoip_latitude": 40.0 + (seed % 100) as f64 / 7.0,
+ "$geoip_longitude": -70.0 - (seed % 100) as f64 / 9.0,
+ "$initial_browser": browser,
+ "$initial_current_url": url,
+ "$initial_os": os,
+ "$initial_referring_domain": "$direct",
+ "$initial_utm_source": format!("campaign-{}", seed % 17),
+ "$os": os,
+ "$pathname": format!("/docs/page-{}", seed % 211),
+ "$referring_domain": "$direct",
+ "email": format!("user{seed}@example.com"),
+ "name": format!("User {seed}"),
+ "plan": if seed.is_multiple_of(5) { "free" } else { "paid" },
+ }))
+ .unwrap()
+ }
+
+ pub(in crate::cache) fn trained_codec() -> PropertiesCodec {
+ let mut samples = Samples::default();
+ for seed in 0..4_000 {
+ let document = person_properties(seed);
+ samples.sizes.push(document.len());
+ samples.data.extend_from_slice(&document);
+ }
+ PropertiesCodec::with_dictionary(Dictionary::train(&samples).unwrap())
+ }
+
+ #[test]
+ fn documents_round_trip_and_only_shrinking_ones_are_compressed() {
+ let codec = trained_codec();
+ let mut state: u32 = 7;
+ let incompressible: Vec<u8> = (0..512)
+ .map(|_| {
+ state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
+ (state >> 16) as u8
+ })
+ .collect();
+ // Incompressible first: a failed frame must not stop later documents from compressing.
+ for (document, expect_compressed) in [
+ (incompressible, false),
+ (person_properties(10_001), true),
+ (br#"{"email":"[email protected]"}"#.to_vec(), false),
+ ] {
+ let stored = codec.encode(document.clone());
+ assert_eq!(
+ matches!(stored, StoredProperties::ZstdDict { .. }),
+ expect_compressed
+ );
+ assert!(stored.stored_len() <= document.len());
+ assert_eq!(stored.raw_len(), document.len());
+ assert_eq!(codec.decode(&stored).unwrap(), document);
+ }
+ }
+
+ #[test]
+ fn only_an_enabled_codec_trains_from_the_documents_it_encodes() {
+ for (codec, expect_trained) in [
+ (PropertiesCodec::enabled(), true),
+ (PropertiesCodec::disabled(), false),
+ ] {
+ let (mut seed, mut fed_bytes) = (0, 0);
+ while seed < MIN_SAMPLES || fed_bytes < SAMPLE_BUDGET_BYTES {
+ let document = person_properties(seed);
+ fed_bytes += document.len();
+ codec.encode(document);
+ seed += 1;
+ }
+ assert_eq!(codec.wait_for_training(), expect_trained);
+ let after = codec.encode(person_properties(seed));
+ assert_eq!(
+ matches!(after, StoredProperties::ZstdDict { .. }),
+ expect_trained
+ );
+ }
+ }
+}
diff --git a/rust/personhog-leader/src/cache/mod.rs b/rust/personhog-leader/src/cache/mod.rs
index 5920501fe21e..76c605f8169b 100644
--- a/rust/personhog-leader/src/cache/mod.rs
+++ b/rust/personhog-leader/src/cache/mod.rs
@@ -1,7 +1,9 @@
+mod codec;
mod dirty_index;
mod partitioned;
mod persons;
+mod stored;
pub use dirty_index::{DirtyIndex, DirtyMark, PRUNE_CHUNK};
pub use partitioned::{CacheLookup, PartitionedCache};
-pub use persons::{approx_person_bytes, CachedPerson, PersonCache, PersonCacheKey};
+pub use persons::{CachedPerson, CachedVersion, PersonCache, PersonCacheKey};
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index 49e20c23ee9f..c8c4090e700c 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -3,13 +3,12 @@ use std::sync::Arc;
use dashmap::DashMap;
use metrics::counter;
-#[cfg(test)]
-use super::persons::approx_person_bytes;
-use super::persons::{CachedPerson, PersonCache, PersonCacheKey};
+use super::codec::PropertiesCodec;
+use super::persons::{CachedPerson, CachedVersion, PersonCache, PersonCacheKey};
/// Result of a cache lookup that distinguishes partition ownership from person existence.
pub enum CacheLookup {
- Found(Arc<CachedPerson>),
+ Found(CachedPerson),
PersonNotFound,
PartitionNotOwned,
}
@@ -26,6 +25,7 @@ pub struct PartitionedCache {
/// answers `PartitionNotOwned` on every path.
warming: DashMap<u32, PersonCache>,
per_partition_capacity: usize,
+ codec: Arc<PropertiesCodec>,
}
impl PartitionedCache {
@@ -34,13 +34,24 @@ impl PartitionedCache {
partitions: DashMap::new(),
warming: DashMap::new(),
per_partition_capacity,
+ codec: Arc::new(PropertiesCodec::disabled()),
+ }
+ }
+
+ /// Call before any partition exists.
+ pub fn with_properties_compression(mut self, enabled: bool) -> Self {
+ if enabled {
+ self.codec = Arc::new(PropertiesCodec::enabled());
}
+ self
}
/// Create a new cache for the given partition. Called during warm-up.
pub fn create_partition(&self, partition: u32) {
- self.partitions
- .insert(partition, PersonCache::new(self.per_partition_capacity));
+ self.partitions.insert(
+ partition,
+ PersonCache::new(self.per_partition_capacity, Arc::clone(&self.codec)),
+ );
}
/// Atomically install a fully-populated partition cache. The records
@@ -76,8 +87,10 @@ impl PartitionedCache {
!self.partitions.contains_key(&partition),
"warm began for published partition {partition}"
);
- self.warming
- .insert(partition, PersonCache::new(self.per_partition_capacity));
+ self.warming.insert(
+ partition,
+ PersonCache::new(self.per_partition_capacity, Arc::clone(&self.codec)),
+ );
}
/// Insert one record into a partition cache under construction.
@@ -175,7 +188,7 @@ impl PartitionedCache {
}
/// Counter-free read for bookkeeping passes; see [`PersonCache::peek`].
- pub fn peek(&self, partition: u32, key: &PersonCacheKey) -> Option<Arc<CachedPerson>> {
+ pub fn peek(&self, partition: u32, key: &PersonCacheKey) -> Option<CachedVersion> {
self.partitions
.get(&partition)
.and_then(|cache| cache.peek(key))
@@ -214,7 +227,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: approx_person_bytes(64),
}
}
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index cf3236232d8a..03a7a2b81d90 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -5,6 +5,9 @@ use foyer::{Cache, CacheBuilder, Event, EventListener};
use metrics::counter;
use personhog_proto::personhog::types::v1::Person;
+use super::codec::PropertiesCodec;
+use super::stored::StoredPerson;
+
/// Key for person cache lookups: (team_id, person_id).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PersonCacheKey {
@@ -12,20 +15,6 @@ pub struct PersonCacheKey {
pub person_id: i64,
}
-/// Fixed per-entry overhead charged on top of the stored properties
-/// bytes: the struct's scalar fields, the uuid, the key, and foyer's
-/// record bookkeeping.
-const PERSON_ENTRY_OVERHEAD_BYTES: usize = 256;
-
-/// The weight an entry contributes to the cache's byte capacity. The
-/// cache stores properties in serialized form, so this is the real
-/// allocation, not an estimate: entries held as parsed JSON trees cost
-/// a small multiple of their serialized size, and weighing those by
-/// serialized length let a "16MiB" cache hold ~2.7x that in heap.
-pub fn approx_person_bytes(properties_serialized_len: usize) -> usize {
- PERSON_ENTRY_OVERHEAD_BYTES + properties_serialized_len
-}
-
/// Cached person state, with properties held in serialized JSON form.
///
/// Serialized rather than parsed for memory accounting: the cache weighs
@@ -53,9 +42,6 @@ pub struct CachedPerson {
/// known (matching `created_at`'s unit). Max-merged on update — the
/// value only ever advances — and deliberately not a change by itself.
pub last_seen_at: Option<i64>,
- /// Byte weight charged against the cache capacity; see
- /// [`approx_person_bytes`].
- pub approx_bytes: usize,
// TODO: Add properties_last_updated_at and properties_last_operation
}
@@ -81,7 +67,6 @@ impl TryFrom<Person> for CachedPerson {
if !person.properties.is_empty() {
serde_json::from_slice::<serde::de::IgnoredAny>(&person.properties)?;
}
- let approx_bytes = approx_person_bytes(person.properties.len());
Ok(Self {
id: person.id,
uuid: person.uuid,
@@ -92,11 +77,16 @@ impl TryFrom<Person> for CachedPerson {
is_identified: person.is_identified,
is_deleted: person.is_deleted,
last_seen_at: person.last_seen_at,
- approx_bytes,
})
}
}
+#[derive(Debug, Clone, Copy)]
+pub struct CachedVersion {
+ pub version: i64,
+ pub is_deleted: bool,
+}
+
/// 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,
@@ -106,7 +96,7 @@ struct CacheEventMetrics;
impl EventListener for CacheEventMetrics {
type Key = PersonCacheKey;
- type Value = Arc<CachedPerson>;
+ type Value = StoredPerson;
fn on_leave(&self, reason: Event, _key: &Self::Key, _value: &Self::Value) {
let reason = match reason {
@@ -131,52 +121,81 @@ impl EventListener for CacheEventMetrics {
/// A hybrid (disk+memory) tier remains a possible capacity optimization
/// by switching to `HybridCache`.
pub struct PersonCache {
- inner: Cache<PersonCacheKey, Arc<CachedPerson>>,
+ inner: Cache<PersonCacheKey, StoredPerson>,
+ codec: Arc<PropertiesCodec>,
}
impl PersonCache {
/// `capacity_bytes` bounds the cache by the entries' byte weights
- /// (see [`approx_person_bytes`]), not their count — person documents
+ /// (see `StoredPerson::weight`), not their count. Person documents
/// vary by orders of magnitude and grow in place across writes, so
/// an entry-count bound cannot bound memory.
- pub fn new(capacity_bytes: usize) -> Self {
+ pub(super) fn new(capacity_bytes: usize, codec: Arc<PropertiesCodec>) -> Self {
let cache = CacheBuilder::new(capacity_bytes)
- .with_weighter(|_key: &PersonCacheKey, value: &Arc<CachedPerson>| value.approx_bytes)
+ .with_weighter(|_key: &PersonCacheKey, value: &StoredPerson| value.weight())
.with_event_listener(Arc::new(CacheEventMetrics))
.build();
- Self { inner: cache }
+ Self {
+ inner: cache,
+ codec,
+ }
}
- pub fn get(&self, key: &PersonCacheKey) -> Option<Arc<CachedPerson>> {
- match self.inner.get(key) {
- Some(entry) => {
- counter!("personhog_leader_cache_hits_total").increment(1);
- Some(entry.value().clone())
- }
- None => {
- counter!("personhog_leader_cache_misses_total").increment(1);
- None
- }
+ pub fn get(&self, key: &PersonCacheKey) -> Option<CachedPerson> {
+ let person = self.lookup(key);
+ match person {
+ Some(_) => counter!("personhog_leader_cache_hits_total").increment(1),
+ None => counter!("personhog_leader_cache_misses_total").increment(1),
}
+ person
+ }
+
+ /// A read for bookkeeping passes such as the death-document settle.
+ /// It skips the hit/miss counters and does not copy or decompress the
+ /// properties. It still promotes the entry's recency, which is
+ /// harmless for those passes.
+ pub fn peek(&self, key: &PersonCacheKey) -> Option<CachedVersion> {
+ self.inner
+ .get(key)
+ .map(|entry| entry.value().cached_version())
}
- /// A read that skips the hit/miss counters — for bookkeeping passes
- /// (the death-document settle), not serving. It still promotes the
- /// entry's recency, which is harmless for those passes.
- pub fn peek(&self, key: &PersonCacheKey) -> Option<Arc<CachedPerson>> {
- self.inner.get(key).map(|entry| entry.value().clone())
+ /// An entry that fails to decode is dropped and reads as absent.
+ fn lookup(&self, key: &PersonCacheKey) -> Option<CachedPerson> {
+ let entry = self.inner.get(key)?;
+ match entry.value().to_cached(&self.codec) {
+ Ok(person) => Some(person),
+ Err(reason) => {
+ // Safe to drop: the miss path recovers from the changelog or Postgres.
+ counter!("personhog_leader_cache_decode_failures_total").increment(1);
+ tracing::error!(
+ team_id = key.team_id,
+ person_id = key.person_id,
+ reason,
+ "dropping cache entry whose properties failed to decode"
+ );
+ self.inner.remove(key);
+ None
+ }
+ }
}
pub fn put(&self, key: PersonCacheKey, person: CachedPerson) {
- self.inner.insert(key, Arc::new(person));
+ let stored = StoredPerson::new(person, &self.codec);
+ let properties = stored.properties();
+ counter!("personhog_leader_cache_properties_put_bytes_total", "form" => "raw")
+ .increment(properties.raw_len() as u64);
+ counter!("personhog_leader_cache_properties_put_bytes_total", "form" => "stored")
+ .increment(properties.stored_len() as u64);
+ self.inner.insert(key, stored);
}
pub fn remove(&self, key: &PersonCacheKey) {
self.inner.remove(key);
}
- /// Resident weight in bytes — the sum of entries' `approx_bytes` as
- /// foyer accounts it against the capacity.
+ /// Resident weight in bytes: the sum of entries' weights as foyer
+ /// accounts it against the capacity.
pub fn usage_bytes(&self) -> usize {
self.inner.usage()
}
@@ -185,6 +204,7 @@ impl PersonCache {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::cache::codec::tests::{person_properties, trained_codec};
/// Proto3 encodes an absent bytes field as empty, and every leader
/// write path serializes at least `{}` — so empty properties can
@@ -219,7 +239,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: approx_person_bytes(64),
}
}
@@ -237,14 +256,13 @@ mod tests {
// 64 KiB capacity → ~8 KiB per shard; ~2 KiB entries fit a
// shard several times over, and 128 of them (~224 KiB) overrun
// the total capacity by more than 3x.
- let cache = PersonCache::new(64 * 1024);
+ let cache = PersonCache::new(64 * 1024, Arc::new(PropertiesCodec::disabled()));
let blob = "x".repeat(1536);
for person_id in 0..128 {
let mut person = test_person();
person.id = person_id;
person.properties =
serde_json::to_vec(&serde_json::json!({ "blob": blob.clone() })).unwrap();
- person.approx_bytes = approx_person_bytes(1536);
cache.put(
PersonCacheKey {
team_id: 42,
@@ -276,7 +294,7 @@ mod tests {
#[test]
fn cache_put_get_roundtrip() {
- let cache = PersonCache::new(1 << 20);
+ let cache = PersonCache::new(1 << 20, Arc::new(PropertiesCodec::disabled()));
let key = PersonCacheKey {
team_id: 42,
person_id: 1,
@@ -296,9 +314,45 @@ mod tests {
);
}
+ #[test]
+ fn compressed_entries_read_back_whole_and_weigh_less() {
+ let key = PersonCacheKey {
+ team_id: 42,
+ person_id: 1,
+ };
+ let mut person = test_person();
+ person.properties = person_properties(10_001);
+ let raw = PersonCache::new(1 << 20, Arc::new(PropertiesCodec::disabled()));
+ let compressed = PersonCache::new(1 << 20, Arc::new(trained_codec()));
+
+ for cache in [&raw, &compressed] {
+ cache.put(key.clone(), person.clone());
+ assert_eq!(cache.get(&key).unwrap().properties, person.properties);
+ }
+ assert!(compressed.usage_bytes() < raw.usage_bytes());
+ }
+
+ #[test]
+ fn an_entry_that_fails_to_decode_reads_as_a_miss_and_leaves_the_cache() {
+ let cache = PersonCache::new(1 << 20, Arc::new(PropertiesCodec::disabled()));
+ let key = PersonCacheKey {
+ team_id: 42,
+ person_id: 1,
+ };
+ let mut person = test_person();
+ person.properties = person_properties(10_001);
+ // A codec without a dictionary cannot decode a compressed frame, which stands in for a corrupt entry.
+ cache
+ .inner
+ .insert(key.clone(), StoredPerson::new(person, &trained_codec()));
+
+ assert!(cache.get(&key).is_none());
+ assert!(cache.peek(&key).is_none());
+ }
+
#[test]
fn cache_remove() {
- let cache = PersonCache::new(1 << 20);
+ let cache = PersonCache::new(1 << 20, Arc::new(PropertiesCodec::disabled()));
let key = PersonCacheKey {
team_id: 42,
person_id: 1,
@@ -313,7 +367,7 @@ mod tests {
#[test]
fn cache_overwrite() {
- let cache = PersonCache::new(1 << 20);
+ let cache = PersonCache::new(1 << 20, Arc::new(PropertiesCodec::disabled()));
let key = PersonCacheKey {
team_id: 42,
person_id: 1,
diff --git a/rust/personhog-leader/src/cache/stored.rs b/rust/personhog-leader/src/cache/stored.rs
new file mode 100644
index 000000000000..37748c15d686
--- /dev/null
+++ b/rust/personhog-leader/src/cache/stored.rs
@@ -0,0 +1,122 @@
+use std::mem::size_of;
+
+use uuid::Uuid;
+
+use super::codec::{PropertiesCodec, StoredProperties};
+use super::persons::{CachedPerson, CachedVersion, PersonCacheKey};
+
+/// Foyer's per-record cost beyond key and value: the record's `Arc`
+/// header, hash, weight, LRU links, refcount, flags and hash-table slot.
+const FOYER_RECORD_BOOKKEEPING_BYTES: usize = 96;
+
+pub(super) struct StoredPerson {
+ id: i64,
+ team_id: i64,
+ uuid: StoredUuid,
+ properties: StoredProperties,
+ created_at: i64,
+ version: i64,
+ last_seen_at: Option<i64>,
+ is_identified: bool,
+ is_deleted: bool,
+}
+
+impl StoredPerson {
+ pub(super) fn new(person: CachedPerson, codec: &PropertiesCodec) -> Self {
+ Self {
+ id: person.id,
+ team_id: person.team_id,
+ uuid: StoredUuid::new(person.uuid),
+ properties: codec.encode(person.properties),
+ created_at: person.created_at,
+ version: person.version,
+ last_seen_at: person.last_seen_at,
+ is_identified: person.is_identified,
+ is_deleted: person.is_deleted,
+ }
+ }
+
+ pub(super) fn to_cached(&self, codec: &PropertiesCodec) -> Result<CachedPerson, &'static str> {
+ Ok(CachedPerson {
+ id: self.id,
+ uuid: self.uuid.to_owned_string(),
+ team_id: self.team_id,
+ properties: codec.decode(&self.properties)?,
+ created_at: self.created_at,
+ version: self.version,
+ is_identified: self.is_identified,
+ is_deleted: self.is_deleted,
+ last_seen_at: self.last_seen_at,
+ })
+ }
+
+ pub(super) fn cached_version(&self) -> CachedVersion {
+ CachedVersion {
+ version: self.version,
+ is_deleted: self.is_deleted,
+ }
+ }
+
+ pub(super) fn properties(&self) -> &StoredProperties {
+ &self.properties
+ }
+
+ pub(super) fn weight(&self) -> usize {
+ size_of::<PersonCacheKey>()
+ + size_of::<Self>()
+ + FOYER_RECORD_BOOKKEEPING_BYTES
+ + self.properties.stored_len()
+ + self.uuid.heap_len()
+ }
+}
+
+/// Non-canonical spellings stay verbatim, so reads return the exact uuid string written.
+enum StoredUuid {
+ Hyphenated(Uuid),
+ Verbatim(Box<str>),
+}
+
+impl StoredUuid {
+ fn new(uuid: String) -> Self {
+ if let Ok(parsed) = Uuid::try_parse(&uuid) {
+ if *parsed.hyphenated().encode_lower(&mut Uuid::encode_buffer()) == *uuid {
+ return Self::Hyphenated(parsed);
+ }
+ }
+ Self::Verbatim(uuid.into_boxed_str())
+ }
+
+ fn to_owned_string(&self) -> String {
+ match self {
+ Self::Hyphenated(uuid) => uuid.hyphenated().to_string(),
+ Self::Verbatim(uuid) => uuid.to_string(),
+ }
+ }
+
+ fn heap_len(&self) -> usize {
+ match self {
+ Self::Hyphenated(_) => 0,
+ Self::Verbatim(uuid) => uuid.len(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn uuid_spellings_survive_the_round_trip() {
+ for spelling in [
+ "0191c3a2-7b4e-7c4a-9f3e-2d1c0b9a8f7e",
+ "0191C3A2-7B4E-7C4A-9F3E-2D1C0B9A8F7E",
+ "0191c3a27b4e7c4a9f3e2d1c0b9a8f7e",
+ "not-a-uuid",
+ ] {
+ assert_eq!(
+ StoredUuid::new(spelling.to_string()).to_owned_string(),
+ spelling
+ );
+ }
+ }
+}
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index ed6af64986e2..8265a03f3655 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -16,15 +16,18 @@ pub struct Config {
pub grpc_address: SocketAddr,
/// Per-partition person-cache capacity in bytes. Entries are weighed
- /// by their approximate serialized size, so this bounds memory, not
+ /// by their stored size, so this bounds memory, not
/// entry count. Sized against full ownership: a lone survivor owns
/// every partition, so the worst-case cache footprint is this value
- /// times the partition count — 16 MiB × 16 partitions = 256 MiB —
- /// and in-memory size can run a small multiple of serialized weight
- /// for key-dense documents.
+ /// times the partition count (16 MiB × 16 partitions = 256 MiB).
#[envconfig(default = "16777216")]
pub cache_memory_capacity_bytes: usize,
+ /// Trades CPU on every cache read and write for more persons per byte.
+ /// The codec's samples, dictionary and per-thread contexts sit outside the capacity bound.
+ #[envconfig(default = "false")]
+ pub cache_properties_compression_enabled: bool,
+
/// How long a fencing transaction window admits joining writes
/// before committing, when it does not fill first (see
/// FENCING_WINDOW_MAX_WRITES). Amortizes the commit round trip
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 0bfa72467b27..462035c7ff7a 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -88,8 +88,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Starting personhog-leader service");
tracing::info!("gRPC address: {}", config.grpc_address);
tracing::info!(
- "Cache capacity: {} bytes per partition",
- config.cache_memory_capacity_bytes
+ "Cache capacity: {} bytes per partition, properties compression: {}",
+ config.cache_memory_capacity_bytes,
+ config.cache_properties_compression_enabled
);
tracing::info!("Metrics port: {}", config.metrics_port);
tracing::info!("etcd endpoints: {}", config.etcd_endpoints);
@@ -281,7 +282,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
// Initialize partitioned cache and Kafka producer
- let cache = Arc::new(PartitionedCache::new(config.cache_memory_capacity_bytes));
+ let cache = Arc::new(
+ PartitionedCache::new(config.cache_memory_capacity_bytes)
+ .with_properties_compression(config.cache_properties_compression_enabled),
+ );
let kafka_producer = match create_kafka_producer(&config.kafka, kafka_handle.clone()).await {
Ok(producer) => producer,
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index 5b378d21f32c..2bf79d3eafa4 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -6,7 +6,7 @@ use sqlx::pool::PoolConnection;
use sqlx::postgres::PgPool;
use sqlx::{Postgres, Row};
-use crate::cache::{approx_person_bytes, CachedPerson, PersonCacheKey};
+use crate::cache::{CachedPerson, PersonCacheKey};
/// A configured PG fallback: the pool and the table it reads. The table
/// must be the one the writer maintains (see FALLBACK_TABLE in
@@ -149,7 +149,6 @@ pub async fn load_person_from_pg(
id,
uuid,
team_id: team_id as i64,
- approx_bytes: approx_person_bytes(properties_bytes.len()),
properties: properties_bytes,
created_at: created_at.timestamp_millis(),
version: version.unwrap_or(0),
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 60e1a10ed55b..bc9b2297ed6e 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -19,8 +19,7 @@ use personhog_common::partitioning::partition_for_person;
use personhog_coordination::authority::AuthorityClock;
use crate::cache::{
- approx_person_bytes, CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache,
- PersonCacheKey,
+ CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey,
};
use crate::emitted::{EmittedVersionGuard, EmittedVersions};
use crate::fence::{
@@ -317,7 +316,7 @@ impl PersonHogLeaderService {
&self,
partition: u32,
key: &PersonCacheKey,
- ) -> Result<Arc<CachedPerson>, Status> {
+ ) -> Result<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
@@ -356,7 +355,7 @@ impl PersonHogLeaderService {
)
.increment(1);
self.cache.put(partition, key.clone(), person.clone());
- Ok(Arc::new(person))
+ Ok(person)
}
Err(e) => {
counter!(
@@ -384,7 +383,7 @@ impl PersonHogLeaderService {
&self,
partition: u32,
key: &PersonCacheKey,
- ) -> Result<Arc<CachedPerson>, Status> {
+ ) -> Result<CachedPerson, Status> {
let Some(fallback) = &self.fallback else {
// Without the pool a cache miss answers NotFound, which callers
// read as authoritative death; production always sets it.
@@ -406,7 +405,7 @@ impl PersonHogLeaderService {
)
.increment(1);
self.cache.put(partition, key.clone(), person.clone());
- Ok(Arc::new(person))
+ Ok(person)
}
Ok(None) => {
counter!(
@@ -443,7 +442,7 @@ impl PersonHogLeaderService {
&self,
partition: u32,
key: &PersonCacheKey,
- ) -> Result<Arc<CachedPerson>, Status> {
+ ) -> Result<CachedPerson, Status> {
// Fast path: cache hit (no lock needed)
match self.cache.get(partition, key) {
CacheLookup::Found(person) => {
@@ -478,7 +477,7 @@ impl PersonHogLeaderService {
&self,
partition: u32,
key: &PersonCacheKey,
- ) -> Result<Arc<CachedPerson>, Status> {
+ ) -> Result<CachedPerson, Status> {
match self.cache.get(partition, key) {
CacheLookup::Found(person) => {
Self::record_cache_hit();
@@ -520,7 +519,7 @@ impl PersonHogLeaderService {
)));
}
- let proto = cached_person_to_proto(&person);
+ let proto = cached_person_into_proto(person.clone());
// Re-check before producing, for the same reason the read path
// re-checks before answering: admission proves nothing about the
@@ -734,7 +733,7 @@ const MS_PER_HOUR: i64 = 3_600_000;
/// uuid must parse, team_id must fit the column's `integer`, and the
/// timestamps must sit inside a sanity range ([1970, 9999]) any
/// legitimate value satisfies. The legacy jsonb columns have no cache
-/// field and are unconditionally empty in `cached_person_to_proto`, so a
+/// field and are unconditionally empty in `cached_person_into_proto`, so a
/// record structurally cannot carry values the writer would refuse there.
fn assert_writeable(p: &CachedPerson) -> Result<(), String> {
if Uuid::parse_str(&p.uuid).is_err() {
@@ -760,13 +759,12 @@ fn assert_writeable(p: &CachedPerson) -> Result<(), String> {
Ok(())
}
-fn cached_person_to_proto(p: &CachedPerson) -> Person {
- let properties_bytes = p.properties.clone();
+fn cached_person_into_proto(p: CachedPerson) -> Person {
Person {
id: p.id,
- uuid: p.uuid.clone(),
+ uuid: p.uuid,
team_id: p.team_id,
- properties: properties_bytes,
+ properties: p.properties,
properties_last_updated_at: Vec::new(),
properties_last_operation: Vec::new(),
created_at: p.created_at,
@@ -919,7 +917,7 @@ impl PersonHogLeader for PersonHogLeaderService {
}
Ok(Response::new(GetPersonResponse {
- person: Some(cached_person_to_proto(&person)),
+ person: Some(cached_person_into_proto(person)),
}))
}
@@ -1115,7 +1113,7 @@ impl PersonHogLeader for PersonHogLeaderService {
if !updates.has_changes && !identity_changed && !last_seen_changed {
counter!("personhog_leader_updates_total", "outcome" => "no_change").increment(1);
return Ok(Response::new(UpdatePersonPropertiesResponse {
- person: Some(cached_person_to_proto(&person)),
+ person: Some(cached_person_into_proto(person)),
updated: false,
}));
}
@@ -1125,7 +1123,7 @@ impl PersonHogLeader for PersonHogLeaderService {
if !updates.has_non_filtered_changes && !identity_changed && !last_seen_changed {
counter!("personhog_leader_updates_total", "outcome" => "filtered_only").increment(1);
return Ok(Response::new(UpdatePersonPropertiesResponse {
- person: Some(cached_person_to_proto(&person)),
+ person: Some(cached_person_into_proto(person)),
updated: false,
}));
}
@@ -1138,7 +1136,7 @@ impl PersonHogLeader for PersonHogLeaderService {
if !actually_updated && !identity_changed && !last_seen_changed {
counter!("personhog_leader_updates_total", "outcome" => "no_change").increment(1);
return Ok(Response::new(UpdatePersonPropertiesResponse {
- person: Some(cached_person_to_proto(&person)),
+ person: Some(cached_person_into_proto(person)),
updated: false,
}));
}
@@ -1243,7 +1241,6 @@ impl PersonHogLeader for PersonHogLeaderService {
let properties_bytes = serde_json::to_vec(&new_properties)
.map_err(|e| Status::internal(format!("serialize updated properties: {e}")))?;
- let approx_bytes = approx_person_bytes(properties_bytes.len());
// A version this pod already put on the wire is spent even when
// it never learned the outcome, so the next one has to clear that
// floor as well as the state it derived from. Reusing it produces
@@ -1262,7 +1259,6 @@ impl PersonHogLeader for PersonHogLeaderService {
is_identified: identified_now,
is_deleted: false,
last_seen_at: merged_last_seen,
- approx_bytes,
};
let committed = self
@@ -1538,7 +1534,7 @@ impl PersonHogLeader for PersonHogLeaderService {
return self.authoritative_ok(
partition,
FoldPersonDocumentResponse {
- person: Some(cached_person_to_proto(&person)),
+ person: Some(cached_person_into_proto(person)),
},
);
}
@@ -1590,7 +1586,6 @@ impl PersonHogLeader for PersonHogLeaderService {
let folded_bytes = serde_json::to_vec(&folded)
.map_err(|e| Status::internal(format!("serialize folded properties: {e}")))?;
- let approx_bytes = approx_person_bytes(folded_bytes.len());
let folded_person = CachedPerson {
id: person.id,
uuid: person.uuid.clone(),
@@ -1601,7 +1596,6 @@ impl PersonHogLeader for PersonHogLeaderService {
is_identified: true,
is_deleted: false,
last_seen_at,
- approx_bytes,
};
let committed = self
@@ -1932,7 +1926,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -1990,7 +1983,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2093,7 +2085,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2341,7 +2332,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2413,7 +2403,6 @@ mod tests {
is_identified: false,
is_deleted: true,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2490,7 +2479,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2554,7 +2542,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
@@ -2657,7 +2644,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
drop(held);
@@ -2703,7 +2689,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: 64,
},
);
diff --git a/rust/personhog-leader/src/service/lifecycle.rs b/rust/personhog-leader/src/service/lifecycle.rs
index 5824de382c97..e4d69967c68f 100644
--- a/rust/personhog-leader/src/service/lifecycle.rs
+++ b/rust/personhog-leader/src/service/lifecycle.rs
@@ -16,13 +16,13 @@ use personhog_proto::personhog::types::v1::{
use tonic::{Request, Response, Status};
use uuid::Uuid;
-use crate::cache::{approx_person_bytes, CachedPerson, PersonCacheKey};
+use crate::cache::{CachedPerson, PersonCacheKey};
use crate::fence::{
fenced_status, mark_status, semantic_refusal, FenceState, MarkSnapshot, MarkVerifier,
};
use crate::pg::PgFallback;
-use super::{cached_person_to_proto, partition_from_metadata, PersonHogLeaderService};
+use super::{cached_person_into_proto, partition_from_metadata, PersonHogLeaderService};
/// The ceiling on persons per `FencePersons` or `ReleaseFences` call. The
/// lifecycle service splits its calls at this size, so a larger batch is a
@@ -272,7 +272,6 @@ impl PersonHogLeaderService {
is_identified: false,
is_deleted: true,
last_seen_at: None,
- approx_bytes: approx_person_bytes(2),
};
let produce_started = Instant::now();
// The RPC's own guard admitted the batch; this one rides the
@@ -348,10 +347,11 @@ impl PersonHogLeaderService {
return Err(Status::not_found("person is destroyed"));
}
- let mut sealed = cached_person_to_proto(&person);
+ let cached_version = person.version;
+ let mut sealed = cached_person_into_proto(person);
sealed.version = self
.emitted_versions
- .floor_for(partition, &cache_key, person.version);
+ .floor_for(partition, &cache_key, cached_version);
// A same-op re-fence leaves the fence alone: a fresh seal time would
// turn a takeover fence into one the op's snapshot may vouch for.
diff --git a/rust/personhog-leader/src/settle.rs b/rust/personhog-leader/src/settle.rs
index 175c17a49f46..4b42225b050e 100644
--- a/rust/personhog-leader/src/settle.rs
+++ b/rust/personhog-leader/src/settle.rs
@@ -9,7 +9,7 @@ use dashmap::DashMap;
use metrics::{counter, histogram};
use tokio::sync::Mutex;
-use crate::cache::{CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey};
+use crate::cache::{CachedVersion, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey};
use crate::warming::{fetch_writer_committed_offsets, ConsumerPool};
/// One prune pass: fetch committed offsets, prune applied marks of the
@@ -81,10 +81,9 @@ pub async fn drop_settled_death_documents(
// Skip lock-free only on a live or newer entry. An absent entry
// must take the lock: a recovery holding it may be about to
// install this very death document.
- let settled = |entry: &Arc<CachedPerson>| entry.is_deleted && entry.version == mark.version;
+ let settled = |entry: CachedVersion| entry.is_deleted && entry.version == mark.version;
if cache
.peek(mark.partition, key)
- .as_ref()
.is_some_and(|entry| !settled(entry))
{
continue;
@@ -94,11 +93,7 @@ pub async fn drop_settled_death_documents(
let _guard = mutex.lock().await;
// Re-proved under the lock so a concurrent commit's newer entry
// is never dropped.
- if cache
- .peek(mark.partition, key)
- .as_ref()
- .is_some_and(settled)
- {
+ if cache.peek(mark.partition, key).is_some_and(settled) {
cache.remove(mark.partition, key);
counter!("personhog_leader_death_documents_settled_total").increment(1);
}
@@ -112,7 +107,7 @@ pub async fn drop_settled_death_documents(
#[cfg(test)]
mod tests {
use super::*;
- use crate::cache::approx_person_bytes;
+ use crate::cache::CachedPerson;
fn death_person(version: i64) -> CachedPerson {
CachedPerson {
@@ -125,7 +120,6 @@ mod tests {
is_identified: true,
is_deleted: true,
last_seen_at: None,
- approx_bytes: approx_person_bytes(0),
}
}
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index b6a3d4236929..86da0e1adb36 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -787,7 +787,6 @@ mod tests {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: crate::cache::approx_person_bytes(2),
}
}
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index c8ebb7947f74..e76e2b139f01 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -30,9 +30,7 @@ use rdkafka::ClientConfig;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use personhog_common::partitioning::partition_for_person;
-use personhog_leader::cache::{
- approx_person_bytes, CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey,
-};
+use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
use personhog_leader::pg::{LifecycleTables, PgFallback};
@@ -691,7 +689,6 @@ pub fn test_cached_person() -> CachedPerson {
is_identified: false,
is_deleted: false,
last_seen_at: None,
- approx_bytes: approx_person_bytes(64),
}
}