: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
feat(propdefs): filter batches against a reader before writing (#94914)
José Sequeira5475f6cc2397
diff --git a/rust/property-defs-rs/src/app_context.rs b/rust/property-defs-rs/src/app_context.rsindex 9ba4e0aa5656..e101bb43ce9d 100644--- a/rust/property-defs-rs/src/app_context.rs+++ b/rust/property-defs-rs/src/app_context.rs@@ -12,6 +12,10 @@ pub struct AppContext {// this points to the original (shared) CLOUD DB instance in prod deploymentspub pool: PgPool,+ // Reader pool for the read-before-write filter; None when the feature is off.+ // No writer guard: these connections only ever read.+ pub read_pool: Option<PgPool>,+pub query_manager: Manager,pub skip_reads: bool,@@ -22,10 +26,27 @@ impl AppContext {pub async fn new(config: &Config, qmgr: Manager) -> Result<Self, sqlx::Error> {let pool = build_write_pool(config).await?;+ let read_pool = if config.read_before_write_enabled {+ let read_url = if config.database_read_url.is_empty() {+ &config.database_url+ } else {+ &config.database_read_url+ };+ Some(+ PgPoolOptions::new()+ .max_connections(config.max_pg_connections)+ .max_lifetime(jittered_max_lifetime(config.pg_max_lifetime_secs))+ .connect_lazy(read_url)?,+ )+ } else {+ None+ };+let group_type_resolver = GroupTypeResolver::new(config);Ok(Self {pool,+ read_pool,query_manager: qmgr,skip_reads: config.skip_reads,group_type_resolver,diff --git a/rust/property-defs-rs/src/batch_ingestion.rs b/rust/property-defs-rs/src/batch_ingestion.rsindex fe9e28672b1a..deb804ec4545 100644--- a/rust/property-defs-rs/src/batch_ingestion.rs+++ b/rust/property-defs-rs/src/batch_ingestion.rs@@ -123,6 +123,20 @@ impl EventPropertiesBatch {// were removed. Their `cached` entries are removed too, so a later uncache_batch can't// evict them from the shared dedup cache: staying cached is what stops the dead// tenant's events from re-issuing the same failing write.+ // Keeps only the rows whose mask entry is true; returns how many were dropped.+ pub fn retain_rows(&mut self, keep: &[bool]) -> usize {+ let removed = keep.iter().filter(|k| !**k).count();+ if removed == 0 {+ return 0;+ }+ retain_by_mask(&mut self.team_ids, keep);+ retain_by_mask(&mut self.project_ids, keep);+ retain_by_mask(&mut self.event_names, keep);+ retain_by_mask(&mut self.property_names, keep);+ retain_by_mask(&mut self.cached, keep);+ removed+ }+pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {let keep: Vec<bool> = match column {"team_id" => self@@ -368,15 +382,25 @@ impl PropertyDefinitionsBatch {if removed == 0 {return 0;}- retain_by_mask(&mut self.ids, &keep);- retain_by_mask(&mut self.team_ids, &keep);- retain_by_mask(&mut self.project_ids, &keep);- retain_by_mask(&mut self.names, &keep);- retain_by_mask(&mut self.are_numerical, &keep);- retain_by_mask(&mut self.event_types, &keep);- retain_by_mask(&mut self.property_types, &keep);- retain_by_mask(&mut self.group_type_indices, &keep);- retain_by_mask(&mut self.cached, &keep);+ self.retain_rows(&keep);+ removed+ }++ // Keeps only the rows whose mask entry is true; returns how many were dropped.+ pub fn retain_rows(&mut self, keep: &[bool]) -> usize {+ let removed = keep.iter().filter(|k| !**k).count();+ if removed == 0 {+ return 0;+ }+ retain_by_mask(&mut self.ids, keep);+ retain_by_mask(&mut self.team_ids, keep);+ retain_by_mask(&mut self.project_ids, keep);+ retain_by_mask(&mut self.names, keep);+ retain_by_mask(&mut self.are_numerical, keep);+ retain_by_mask(&mut self.event_types, keep);+ retain_by_mask(&mut self.property_types, keep);+ retain_by_mask(&mut self.group_type_indices, keep);+ retain_by_mask(&mut self.cached, keep);removed}}@@ -386,9 +410,11 @@ pub async fn process_batch(config: &Config,cache: Arc<Cache>,pool: &PgPool,+ read_pool: Option<PgPool>,batch: Vec<Update>,handle: &lifecycle::Handle,) {+ let read_budget = std::time::Duration::from_millis(config.read_before_write_timeout_ms);// prep reshaped, isolated data batch bufffers and async join handleslet mut event_defs = EventDefinitionsBatch::new(config.write_batch_size);let mut event_props = EventPropertiesBatch::new(config.write_batch_size);@@ -416,9 +442,21 @@ pub async fn process_batch(if event_props.should_flush_batch() {let pool = pool.clone();let cache = cache.clone();- let outbound = event_props;+ let mut outbound = event_props;event_props = EventPropertiesBatch::new(config.write_batch_size);+ let read_pool = read_pool.clone();handles.push(tokio::spawn(async move {+ if let Some(rp) = &read_pool {+ crate::read_filter::filter_event_properties(+ rp,+ &mut outbound,+ read_budget,+ )+ .await;+ }+ if outbound.is_empty() {+ return Ok(());+ }write_event_properties_batch(cache, outbound, &pool).await}));}@@ -428,9 +466,22 @@ pub async fn process_batch(if prop_defs.should_flush_batch() {let pool = pool.clone();let cache = cache.clone();- let outbound = prop_defs;+ let mut outbound = prop_defs;prop_defs = PropertyDefinitionsBatch::new(config.write_batch_size);+ let read_pool = read_pool.clone();handles.push(tokio::spawn(async move {+ if let Some(rp) = &read_pool {+ crate::read_filter::filter_property_definitions(+ rp,+ &cache,+ &mut outbound,+ read_budget,+ )+ .await;+ }+ if outbound.is_empty() {+ return Ok(());+ }write_property_definitions_batch(cache, outbound, &pool).await}));}@@ -449,14 +500,37 @@ pub async fn process_batch(if !prop_defs.is_empty() {let pool = pool.clone();let cache = cache.clone();+ let read_pool = read_pool.clone();handles.push(tokio::spawn(async move {+ let mut prop_defs = prop_defs;+ if let Some(rp) = &read_pool {+ crate::read_filter::filter_property_definitions(+ rp,+ &cache,+ &mut prop_defs,+ read_budget,+ )+ .await;+ }+ if prop_defs.is_empty() {+ return Ok(());+ }write_property_definitions_batch(cache, prop_defs, &pool).await}));}if !event_props.is_empty() {let pool = pool.clone();let cache = cache.clone();+ let read_pool = read_pool.clone();handles.push(tokio::spawn(async move {+ let mut event_props = event_props;+ if let Some(rp) = &read_pool {+ crate::read_filter::filter_event_properties(rp, &mut event_props, read_budget)+ .await;+ }+ if event_props.is_empty() {+ return Ok(());+ }write_event_properties_batch(cache, event_props, &pool).await}));}diff --git a/rust/property-defs-rs/src/config.rs b/rust/property-defs-rs/src/config.rsindex be1b35afdfea..b74228f18e92 100644--- a/rust/property-defs-rs/src/config.rs+++ b/rust/property-defs-rs/src/config.rs@@ -23,6 +23,24 @@ pub struct Config {#[envconfig(default = "300")]pub pg_max_lifetime_secs: u64,+ // === Read-before-write ===+ // Reader connection string, e.g. an Aurora reader endpoint. Empty falls back to+ // database_url. Filter reads get their own pool either way, so they never compete+ // with batch writes for the writer pool.+ #[envconfig(default = "")]+ pub database_read_url: String,++ // Check each write batch against the Postgres reader first and drop rows the+ // database already covers, so no-op upserts become cheap reader probes instead+ // of writer traffic.+ #[envconfig(default = "false")]+ pub read_before_write_enabled: bool,++ // Budget per probe query. A probe that exceeds it is abandoned and the batch is+ // written unfiltered, so a slow reader can never stall the write path.+ #[envconfig(default = "2000")]+ pub read_before_write_timeout_ms: u64,+#[envconfig(nested = true)]pub kafka: KafkaConfig,diff --git a/rust/property-defs-rs/src/lib.rs b/rust/property-defs-rs/src/lib.rsindex cff466981559..764b437b4348 100644--- a/rust/property-defs-rs/src/lib.rs+++ b/rust/property-defs-rs/src/lib.rs@@ -30,6 +30,7 @@ pub mod group_type_resolver;pub mod measuring_channel;pub mod metrics_buckets;pub mod metrics_consts;+pub mod read_filter;pub mod types;pub mod update_cache;@@ -139,7 +140,15 @@ pub async fn update_consumer_loop(});handle.report_healthy();- process_batch(&config, cache.clone(), &context.pool, batch, &handle).await;+ process_batch(+ &config,+ cache.clone(),+ &context.pool,+ context.read_pool.clone(),+ batch,+ &handle,+ )+ .await;}}diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rsindex 2469d5860003..0cad2f8d0b7a 100644--- a/rust/property-defs-rs/src/metrics_consts.rs+++ b/rust/property-defs-rs/src/metrics_consts.rs@@ -84,3 +84,9 @@ pub const V2_PROP_DEFS_DROPPED_UNCACHED: &str = "propdefs_v2_propdefs_dropped_un// target table. Stripped rows stay in the shared dedup cache on purpose, so the dead// tenant's events stop re-issuing the same failing write.pub const V2_BATCH_ROWS_DROPPED_FK: &str = "propdefs_v2_batch_rows_dropped_fk";++// Read-before-write: batches are checked against a Postgres reader before the+// upsert, and rows the database already covers are dropped from the write.+pub const READ_FILTER_ATTEMPT: &str = "propdefs_v2_read_filter_attempt";+pub const READ_FILTER_ROWS_DROPPED: &str = "propdefs_v2_read_filter_rows_dropped";+pub const READ_FILTER_TIME: &str = "propdefs_v2_read_filter_ms";diff --git a/rust/property-defs-rs/src/read_filter.rs b/rust/property-defs-rs/src/read_filter.rsnew file mode 100644index 000000000000..66d790e6287e--- /dev/null+++ b/rust/property-defs-rs/src/read_filter.rs@@ -0,0 +1,162 @@+use std::str::FromStr;+use std::time::Duration;++use sqlx::PgPool;+use tracing::warn;++use crate::{+ batch_ingestion::{EventPropertiesBatch, PropertyDefinitionsBatch},+ metrics_consts::{READ_FILTER_ATTEMPT, READ_FILTER_ROWS_DROPPED, READ_FILTER_TIME},+ types::{PropertyValueType, Update},+ update_cache::Cache,+};++// Read-before-write: probe the batch against a Postgres reader and drop the rows+// the database already covers, so no-op upserts become cheap reader index probes+// instead of writer traffic. Every failure path fails open - the unfiltered batch+// is written exactly as it would be without this feature - so the filter can only+// remove writes the upsert would have no-oped anyway.+//+// Reader lag is safe by the same argument in the other direction: a row committed+// moments ago may look absent on the replica, so it stays in the batch and the+// writer's ON CONFLICT no-ops it.++/// Drops event-property rows that already exist. The unique index covers the+/// probe (COALESCE project key, event, property), one index descent per row.+pub async fn filter_event_properties(+ pool: &PgPool,+ batch: &mut EventPropertiesBatch,+ budget: Duration,+) {+ if batch.is_empty() {+ return;+ }+ let timer = common_metrics::timing_guard(READ_FILTER_TIME, &[]);+ let query = sqlx::query_as(+ r#"SELECT u.ord+ FROM unnest($1::bigint[], $2::text[], $3::text[]) WITH ORDINALITY AS u(pk, event, property, ord)+ JOIN posthog_eventproperty ep+ ON COALESCE(ep.project_id, ep.team_id::bigint) = u.pk+ AND ep.event = u.event+ AND ep.property = u.property"#,+ )+ .bind(&batch.project_ids)+ .bind(&batch.event_names)+ .bind(&batch.property_names)+ .fetch_all(pool);+ let found: Vec<(i64,)> = match tokio::time::timeout(budget, query).await {+ Ok(Ok(found)) => found,+ Ok(Err(e)) => {+ timer.label("table", "eventprops").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "eventprops"), ("result", "failed")]+ )+ .increment(1);+ warn!("read filter failed for eventprops, writing unfiltered batch: {e}");+ return;+ }+ Err(_) => {+ timer.label("table", "eventprops").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "eventprops"), ("result", "timeout")]+ )+ .increment(1);+ return;+ }+ };+ timer.label("table", "eventprops").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "eventprops"), ("result", "success")]+ )+ .increment(1);++ let mut keep = vec![true; batch.len()];+ for (ord,) in found {+ keep[ord as usize - 1] = false;+ }+ let dropped = batch.retain_rows(&keep);+ metrics::counter!(READ_FILTER_ROWS_DROPPED, &[("table", "eventprops")])+ .increment(dropped as u64);+}++/// Drops property-definition rows the upsert could not change: the row exists+/// and either already has a type or the incoming update carries none. Rows kept+/// are new rows and NULL-to-typed upgrades, mirroring the DO UPDATE guard.+pub async fn filter_property_definitions(+ pool: &PgPool,+ cache: &Cache,+ batch: &mut PropertyDefinitionsBatch,+ budget: Duration,+) {+ if batch.is_empty() {+ return;+ }+ let timer = common_metrics::timing_guard(READ_FILTER_TIME, &[]);+ let query = sqlx::query_as(+ r#"SELECT u.ord, pd.property_type+ FROM unnest($1::bigint[], $2::text[], $3::int2[], $4::int2[]) WITH ORDINALITY+ AS u(pk, name, etype, gidx, ord)+ JOIN posthog_propertydefinition pd+ ON COALESCE(pd.project_id, pd.team_id::bigint) = u.pk+ AND pd.name = u.name+ AND pd.type = u.etype+ AND COALESCE(pd.group_type_index, -1) = COALESCE(u.gidx::int4, -1)"#,+ )+ .bind(&batch.project_ids)+ .bind(&batch.names)+ .bind(&batch.event_types)+ .bind(&batch.group_type_indices)+ .fetch_all(pool);+ let found: Vec<(i64, Option<String>)> = match tokio::time::timeout(budget, query).await {+ Ok(Ok(found)) => found,+ Ok(Err(e)) => {+ timer.label("table", "propdefs").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "propdefs"), ("result", "failed")]+ )+ .increment(1);+ warn!("read filter failed for propdefs, writing unfiltered batch: {e}");+ return;+ }+ Err(_) => {+ timer.label("table", "propdefs").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "propdefs"), ("result", "timeout")]+ )+ .increment(1);+ return;+ }+ };+ timer.label("table", "propdefs").fin();+ metrics::counter!(+ READ_FILTER_ATTEMPT,+ &[("table", "propdefs"), ("result", "success")]+ )+ .increment(1);++ let mut keep = vec![true; batch.len()];+ for (ord, stored_type) in found {+ let idx = ord as usize - 1;+ let upgrade = stored_type.is_none() && batch.property_types[idx].is_some();+ if upgrade {+ continue;+ }+ keep[idx] = false;+ // Refresh the dedup cache with the stored type, so future typed sightings+ // of this row hit in memory instead of re-probing the reader.+ if let Some(stored) = stored_type.and_then(|s| PropertyValueType::from_str(&s).ok()) {+ if let Update::Property(pd) = &batch.cached[idx] {+ let mut refreshed = pd.clone();+ refreshed.property_type = Some(stored);+ cache.insert(Update::Property(refreshed));+ }+ }+ }+ let dropped = batch.retain_rows(&keep);+ metrics::counter!(READ_FILTER_ROWS_DROPPED, &[("table", "propdefs")]).increment(dropped as u64);+}diff --git a/rust/property-defs-rs/src/types.rs b/rust/property-defs-rs/src/types.rsindex ec0745f56036..f4f251ae8df6 100644--- a/rust/property-defs-rs/src/types.rs+++ b/rust/property-defs-rs/src/types.rs@@ -130,6 +130,24 @@ impl fmt::Display for PropertyValueType {}}+// Inverse of the Display impl above, which is the form batch writes store in+// posthog_propertydefinition.property_type. Unknown strings are an error; the+// caller decides whether to treat the row as untyped.+impl FromStr for PropertyValueType {+ type Err = ();++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "DateTime" => Ok(PropertyValueType::DateTime),+ "String" => Ok(PropertyValueType::String),+ "Numeric" => Ok(PropertyValueType::Numeric),+ "Boolean" => Ok(PropertyValueType::Boolean),+ "Duration" => Ok(PropertyValueType::Duration),+ _ => Err(()),+ }+ }+}+// The grouptypemapping table uses i32's, but we get group types by name, so we have to resolve them before DB writes, sigh#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize, Serialize)]pub enum GroupType {diff --git a/rust/property-defs-rs/src/update_cache.rs b/rust/property-defs-rs/src/update_cache.rsindex f8de12607184..ea02e4e7de42 100644--- a/rust/property-defs-rs/src/update_cache.rs+++ b/rust/property-defs-rs/src/update_cache.rs@@ -192,11 +192,14 @@ impl Cache {/// True when the cached state already covers this update, meaning the write/// it stands for would change nothing in Postgres.///- /// Lookups go through quick_cache `get`, which marks the entry referenced;- /// S3-FIFO eviction uses that to keep the working set resident. The- /// `contains_key` of quick_cache skips that marking, so every entry looks- /// cold at eviction time and the cache degrades to FIFO: live keys cycle- /// out and each cycle costs a useless definition upsert against Postgres.+ /// Lookups go through quick_cache `peek`, which does not mark the entry+ /// referenced. Identity keys keep the working set within capacity and the+ /// reader-side batch filter drops rows Postgres already has, so eviction+ /// recency cannot change outcomes and a cache miss costs a filtered probe,+ /// not a useless write. Marking every probe only adds S3-FIFO promotion+ /// work under the shard locks on the hottest path in the service. If a+ /// subcache pins at full again with an eroding hit rate, grow its capacity+ /// instead of re-adding per-probe marking.pub fn contains_key(&self, key: &Update) -> bool {let (covered, hits, misses) = match key {Update::Event(def) => {@@ -209,16 +212,15 @@ impl Cache {// Producers interleave, so an update from the previous bucket// can be checked after a rollover was cached; the newer write// already refreshed the row, so the older update stays covered.- // The get refreshes the entry's recency either way.let covered = self.eventdefs.cache- .get(&lookup)+ .peek(&lookup).is_some_and(|bucket| bucket >= def.last_seen_at);(covered, &self.eventdefs.hits, &self.eventdefs.misses)}Update::EventProperty(ep) => (- self.eventprops.cache.get(ep).is_some(),+ self.eventprops.cache.peek(ep).is_some(),&self.eventprops.hits,&self.eventprops.misses,),@@ -230,7 +232,7 @@ impl Cache {event_type: def.event_type,group_name: def.group_type_index.as_ref().map(group_name),};- let covered = match self.propdefs.cache.get(&lookup) {+ let covered = match self.propdefs.cache.peek(&lookup) {// An untyped cached row upgrades once when a typed sighting// arrives; every other combination cannot change the row.Some(cached) => !(cached.is_none() && def.property_type.is_some()),@@ -251,7 +253,7 @@ impl Cache {// None to Some type upgrade. Concurrent producers interleave their// contains_key/insert pairs, so an insert can arrive after another producer// cached fresher state; replacing that state would make the next sighting- // miss and re-issue a write Postgres treats as a no-op. The get-then-insert+ // miss and re-issue a write Postgres treats as a no-op. The peek-then-insert// pairs below race too, but losing that race costs one redundant upsert.pub fn insert(&self, key: Update) {match key {@@ -264,7 +266,7 @@ impl Cache {if self.eventdefs.cache- .get(&lookup)+ .peek(&lookup).is_some_and(|bucket| bucket >= def.last_seen_at){return;@@ -289,7 +291,7 @@ impl Cache {&& self.propdefs.cache- .get(&lookup)+ .peek(&lookup).is_some_and(|cached| cached.is_some()){return;diff --git a/rust/property-defs-rs/tests/batch_ingestion.rs b/rust/property-defs-rs/tests/batch_ingestion.rsindex 7ddcae8f74eb..e832728cd5a1 100644--- a/rust/property-defs-rs/tests/batch_ingestion.rs+++ b/rust/property-defs-rs/tests/batch_ingestion.rs@@ -35,7 +35,7 @@ async fn test_simple_batch_write(db: PgPool) {// should decompose into 1 event def, 100 event props, 100 prop defs (of event type)assert_eq!(updates.len(), 201);- process_batch(&config, cache, &db, updates, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, updates, &test_lifecycle_handle()).await;// fetch results and ensure they landed correctlylet event_def_name: String = sqlx::query_scalar!(r#"SELECT name from posthog_eventdefinition"#)@@ -103,7 +103,7 @@ async fn test_group_batch_write(db: PgPool) {}}});- process_batch(&config, cache, &db, updates, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, updates, &test_lifecycle_handle()).await;// fetch results and ensure they landed correctlylet event_def_name: String = sqlx::query_scalar!(r#"SELECT name from posthog_eventdefinition"#)@@ -140,7 +140,7 @@ async fn test_person_batch_write(db: PgPool) {// should decompose into 1 event def, 0 event props, 100 prop defs (50 $set, 50 $set_once props)assert_eq!(updates.len(), 101);- process_batch(&config, cache, &db, updates, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, updates, &test_lifecycle_handle()).await;// fetch results and ensure they landed correctlylet event_def_name: String = sqlx::query_scalar!(r#"SELECT name from posthog_eventdefinition"#)@@ -281,6 +281,7 @@ async fn test_property_definitions_conflict_update(db: PgPool) {&config,cache.clone(),&db,+ None,initial_updates,&test_lifecycle_handle(),)@@ -313,6 +314,7 @@ async fn test_property_definitions_conflict_update(db: PgPool) {&config,cache,&db,+ None,updated_updates,&test_lifecycle_handle(),)@@ -393,7 +395,7 @@ async fn test_property_definitions_dedupe_within_batch(db: PgPool) {),prop("current_page", None, false, PropertyParentType::Event),];- process_batch(&config, cache, &db, batch, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, batch, &test_lifecycle_handle()).await;let count: Option<i64> = sqlx::query_scalar!(r#"SELECT COUNT(*) FROM posthog_propertydefinition WHERE name IN ('brand', 'current_page')"#@@ -441,7 +443,7 @@ async fn test_property_definitions_typed_row_wins_regardless_of_order(db: PgPoolPropertyParentType::Event,),];- process_batch(&config, cache, &db, batch, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, batch, &test_lifecycle_handle()).await;for name in ["rev_a", "rev_b"] {let row = sqlx::query!(@@ -478,7 +480,7 @@ async fn test_property_definitions_keeps_rows_that_differ_on_conflict_key(db: Pgprop("shared", None, false, PropertyParentType::Event),prop("shared", None, false, PropertyParentType::Person),];- process_batch(&config, cache, &db, batch, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, batch, &test_lifecycle_handle()).await;let count: Option<i64> = sqlx::query_scalar!(r#"SELECT COUNT(*) FROM posthog_propertydefinition WHERE name = 'shared'"#@@ -532,6 +534,7 @@ async fn test_property_definitions_rewrite_the_row_only_when_a_type_is_resolved(&config,cache.clone(),&db,+ None,vec![prop(name,stored.clone(),@@ -553,6 +556,7 @@ async fn test_property_definitions_rewrite_the_row_only_when_a_type_is_resolved(&config,cache,&db,+ None,vec![prop(name,incoming.clone(),@@ -600,7 +604,7 @@ async fn test_event_definitions_dedupe_within_batch(db: PgPool) {evt("$pageview", now),evt("$autocapture", now),];- process_batch(&config, cache, &db, batch, &test_lifecycle_handle()).await;+ process_batch(&config, cache, &db, None, batch, &test_lifecycle_handle()).await;let count: Option<i64> = sqlx::query_scalar!(r#"SELECT COUNT(*) FROM posthog_eventdefinition WHERE name IN ('$pageview', '$autocapture')"#@@ -684,6 +688,7 @@ async fn test_fk_violation_strips_dead_team_rows_and_keeps_them_cached(db: PgPoo&config,cache.clone(),&db,+ None,updates.clone(),&test_lifecycle_handle(),)@@ -748,6 +753,7 @@ async fn test_unparseable_fk_falls_back_to_retry_and_uncache(db: PgPool) {&config,cache.clone(),&db,+ None,updates.clone(),&test_lifecycle_handle(),)diff --git a/rust/property-defs-rs/tests/group_type_resolver.rs b/rust/property-defs-rs/tests/group_type_resolver.rsindex de4b0a05e6a5..10a15b665903 100644--- a/rust/property-defs-rs/tests/group_type_resolver.rs+++ b/rust/property-defs-rs/tests/group_type_resolver.rs@@ -915,6 +915,7 @@ async fn test_end_to_end_poisoned_group_def_recovers_and_persists(db: PgPool) {&config,cache.clone(),&db,+ None,round1,&test_lifecycle_handle(),)@@ -945,6 +946,7 @@ async fn test_end_to_end_poisoned_group_def_recovers_and_persists(db: PgPool) {&config,cache.clone(),&db,+ None,round2,&test_lifecycle_handle(),)diff --git a/rust/property-defs-rs/tests/read_filter.rs b/rust/property-defs-rs/tests/read_filter.rsnew file mode 100644index 000000000000..6f35416f21c6--- /dev/null+++ b/rust/property-defs-rs/tests/read_filter.rs@@ -0,0 +1,142 @@+use std::sync::Arc;+use std::time::Duration;++use sqlx::PgPool;++use property_defs_rs::{+ batch_ingestion::{process_batch, EventPropertiesBatch, PropertyDefinitionsBatch},+ config::Config,+ read_filter::{filter_event_properties, filter_property_definitions},+ types::{EventProperty, PropertyDefinition, PropertyParentType, PropertyValueType, Update},+ update_cache::Cache,+};++fn test_lifecycle_handle() -> lifecycle::Handle {+ let mut manager = lifecycle::Manager::builder("test").build();+ manager.register("consumer", lifecycle::ComponentOptions::new())+}++const TEAM: i32 = 111;+const PROJECT: i64 = 111;+const BUDGET: Duration = Duration::from_secs(5);++fn event_prop(property: &str) -> EventProperty {+ EventProperty {+ team_id: TEAM,+ project_id: PROJECT,+ event: "$pageview".to_string(),+ property: property.to_string(),+ }+}++fn prop_def(name: &str, property_type: Option<PropertyValueType>) -> PropertyDefinition {+ PropertyDefinition {+ team_id: TEAM,+ project_id: PROJECT,+ name: name.to_string(),+ is_numerical: matches!(property_type, Some(PropertyValueType::Numeric)),+ property_type,+ event_type: PropertyParentType::Event,+ group_type_index: None,+ }+}++async fn seed(db: &PgPool, batch: Vec<Update>) {+ let config = Config::init_with_defaults().unwrap();+ let cache = Arc::new(Cache::new(1000, 1000, 1000));+ process_batch(&config, cache, db, None, batch, &test_lifecycle_handle()).await;+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_filter_drops_existing_event_properties(db: PgPool) {+ seed(+ &db,+ vec![+ Update::EventProperty(event_prop("plan")),+ Update::EventProperty(event_prop("browser")),+ ],+ )+ .await;++ let mut batch = EventPropertiesBatch::new(10);+ batch.append(event_prop("plan"));+ batch.append(event_prop("fresh"));+ batch.append(event_prop("browser"));++ filter_event_properties(&db, &mut batch, BUDGET).await;++ assert_eq!(batch.len(), 1, "only the unknown row survives the filter");+ assert_eq!(batch.property_names, vec!["fresh".to_string()]);+}++// The filter mirrors the upsert's DO UPDATE guard: an existing row is dropped+// unless it is untyped and the incoming update carries a type.+#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_filter_keeps_new_rows_and_type_upgrades(db: PgPool) {+ seed(+ &db,+ vec![+ Update::Property(prop_def("plan", Some(PropertyValueType::String))),+ Update::Property(prop_def("misc", None)),+ ],+ )+ .await;++ let cache = Cache::new(1000, 1000, 1000);+ let mut batch = PropertyDefinitionsBatch::new(10);+ batch.append(prop_def("plan", Some(PropertyValueType::String)));+ batch.append(prop_def("plan", Some(PropertyValueType::DateTime)));+ batch.append(prop_def("misc", None));+ batch.append(prop_def("misc", Some(PropertyValueType::Boolean)));+ batch.append(prop_def("fresh", None));++ filter_property_definitions(&db, &cache, &mut batch, BUDGET).await;++ assert_eq!(+ batch.names,+ vec!["misc".to_string(), "fresh".to_string()],+ "kept: the untyped-to-typed upgrade and the unknown row"+ );++ // Dropped typed rows refresh the cache with the stored type, so both+ // variants of "plan" now hit in memory instead of re-probing the reader.+ assert!(cache.contains_key(&Update::Property(prop_def(+ "plan",+ Some(PropertyValueType::DateTime)+ ))));+ assert!(cache.contains_key(&Update::Property(prop_def("plan", None))));+}++// End to end through process_batch: with the read pool set, a repeated batch+// still lands its genuinely new row.+#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_process_batch_with_read_pool_writes_new_rows(db: PgPool) {+ seed(&db, vec![Update::EventProperty(event_prop("plan"))]).await;++ let config = Config::init_with_defaults().unwrap();+ let cache = Arc::new(Cache::new(1000, 1000, 1000));+ let batch = vec![+ Update::EventProperty(event_prop("plan")),+ Update::EventProperty(event_prop("fresh")),+ ];+ process_batch(+ &config,+ cache,+ &db,+ Some(db.clone()),+ batch,+ &test_lifecycle_handle(),+ )+ .await;++ let count: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM posthog_eventproperty WHERE property IN ('plan', 'fresh')",+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(+ count, 2,+ "the new row must persist alongside the seeded one"+ );+}diff --git a/rust/property-defs-rs/tests/update_cache.rs b/rust/property-defs-rs/tests/update_cache.rsindex 593607befa30..57151461acca 100644--- a/rust/property-defs-rs/tests/update_cache.rs+++ b/rust/property-defs-rs/tests/update_cache.rs@@ -322,40 +322,6 @@ fn test_eventdef_bucket_rollover_replaces_entry() {);}-// Guards the recency contract of `Cache::contains_key`: a lookup must mark the-// entry referenced (quick_cache `get`), so a key that was checked survives the-// next eviction pass by promotion into the protected segment. quick_cache's-// own `contains_key` skips that marking, which degrades S3-FIFO to FIFO; in-// production that evicts the working set on a fixed schedule and re-issues a-// useless Postgres upsert per cycle.-//-// The filler prelude matters: a nearly-empty cache admits inserts straight-// into the protected (hot) segment, where eviction pressure never reaches-// them and the assertion would pass with or without recency marking. Filling-// the cache first forces the probe key into the probationary (cold) segment,-// where only a referenced entry survives.-#[test]-fn test_checked_key_survives_eviction_pressure() {- let cache = Cache::new(2, 2, 2);-- for i in 0..40 {- cache.insert(make_event_def(&format!("recency_fill_{i}")));- }-- let probe = make_event_def("recency_probe");- cache.insert(probe.clone());- assert!(cache.contains_key(&probe), "probe should be resident");-- for i in 0..100 {- cache.insert(make_event_def(&format!("recency_flood_{i}")));- }-- assert!(- cache.contains_key(&probe),- "checked key was evicted instead of promoted"- );-}-// quick_cache enforces a minimum of 32 items per shard (`sync.rs` ~134:// `while shard_items_cap < 32 && num_shards > 1 { num_shards /= 2; ... }`),// so even with `Cache::new(2, 2, 2)` we get a single 32-slot shard per