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(propdefs): configurable dedup period + producer lull drain (#77926)

Eli Reisman6f7e89a6e567
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 052f4cd8106b..33086b1758da 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9251,6 +9251,7 @@ dependencies = [
"personhog-proto",
"quick_cache",
"rand 0.8.5",
+ "rdkafka",
"regex",
"rstest",
"serde",
diff --git a/rust/property-defs-rs/Cargo.toml b/rust/property-defs-rs/Cargo.toml
index aee2e1df41b0..a50e8045e713 100644
--- a/rust/property-defs-rs/Cargo.toml
+++ b/rust/property-defs-rs/Cargo.toml
@@ -36,6 +36,9 @@ regex.workspace = true
tokio-stream = { version = "0.1", features = ["net"] }
metrics-util = { workspace = true }
rstest = "0.26"
+# Drives common_kafka's MockCluster in tests/producer_loop.rs, so the producer loop can be
+# exercised end to end without a broker.
+rdkafka = { workspace = true }
[lints]
workspace = true
diff --git a/rust/property-defs-rs/src/config.rs b/rust/property-defs-rs/src/config.rs
index 2eaf41326b28..1db0488b2515 100644
--- a/rust/property-defs-rs/src/config.rs
+++ b/rust/property-defs-rs/src/config.rs
@@ -55,6 +55,11 @@ pub struct Config {
#[envconfig(default = "10000")]
pub compaction_batch_size: usize,
+ // How long a producer's compaction batch may sit before it is flushed regardless of size.
+ // Bounds how stale the tail of a partition's updates can get once its traffic stops.
+ #[envconfig(default = "10")]
+ pub producer_drain_interval_secs: u64,
+
// Workers send updates back to the main thread over a channel,
// which has a depth of this many slots. If the main thread slows,
// which usually means if postgres is slow, the workers will block
@@ -66,6 +71,17 @@ pub struct Config {
#[envconfig(default = "10000")]
pub update_count_skip_threshold: usize,
+ // Period an event definition's last_seen_at is floored to for dedup purposes, which bounds
+ // how often we re-issue its write: once per (team, name) per period, per pod. The stored
+ // value is generated fresh at write time, so a coarser period only means a staler
+ // last_seen_at in the DB. Its only consumers are staleness filters, so read them before
+ // raising this: `?exclude_stale=true` compares against 30 days, but the event-screenshots
+ // Temporal workflow shortlists event types on a 3 hour window. Must be in
+ // 1..=MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS: flooring is what bounds this table's write volume,
+ // so startup fails rather than run without it.
+ #[envconfig(from = "EVENTDEF_LAST_SEEN_FLOOR_SECS", default = "3600")]
+ pub eventdef_last_seen_floor_secs: i64,
+
// Do everything except actually write to the DB
#[envconfig(default = "true")]
pub skip_writes: bool,
diff --git a/rust/property-defs-rs/src/lib.rs b/rust/property-defs-rs/src/lib.rs
index 819f15493e06..defc72e5e465 100644
--- a/rust/property-defs-rs/src/lib.rs
+++ b/rust/property-defs-rs/src/lib.rs
@@ -152,70 +152,82 @@ pub async fn update_producer_loop(
let _guard = handle.process_scope();
let mut batch = AHashSet::with_capacity(config.compaction_batch_size);
let mut last_send = tokio::time::Instant::now();
+ let drain_interval = Duration::from_secs(config.producer_drain_interval_secs);
loop {
+ // The timer arm is what lets the flush check at the bottom of the loop run while no
+ // events are arriving. Without it the loop parks in json_recv(), so a partial compaction
+ // batch left behind when a partition goes quiet stays unwritten until traffic resumes.
+ // The tick period is deliberately independent of drain_interval; it only bounds how
+ // often the elapsed check is re-evaluated, not how long a batch may sit.
let recv_result = tokio::select! {
_ = handle.shutdown_recv() => {
info!("Producer loop shutting down");
return;
}
- r = consumer.json_recv() => r,
+ r = consumer.json_recv() => Some(r),
+ _ = tokio::time::sleep(Duration::from_secs(1)) => None,
};
- let (event, offset): (Event, _) = match recv_result {
- Ok(r) => r,
- Err(RecvErr::Empty) => {
- warn!("Received empty event");
- metrics::counter!(EMPTY_EVENTS).increment(1);
- continue;
- }
- Err(RecvErr::Serde(e)) => {
- metrics::counter!(EVENT_PARSE_ERROR).increment(1);
- warn!("Failed to parse event: {:?}", e);
- continue;
- }
- Err(RecvErr::Kafka(e)) => {
- handle.signal_failure(format!("Kafka error: {e:?}"));
- return;
- }
- };
+ if let Some(recv_result) = recv_result {
+ let (event, offset): (Event, _) = match recv_result {
+ Ok(r) => r,
+ Err(RecvErr::Empty) => {
+ warn!("Received empty event");
+ metrics::counter!(EMPTY_EVENTS).increment(1);
+ continue;
+ }
+ Err(RecvErr::Serde(e)) => {
+ metrics::counter!(EVENT_PARSE_ERROR).increment(1);
+ warn!("Failed to parse event: {:?}", e);
+ continue;
+ }
+ Err(RecvErr::Kafka(e)) => {
+ handle.signal_failure(format!("Kafka error: {e:?}"));
+ return;
+ }
+ };
- // NOTE: we extended the autocommit interval in production envs to 20 seconds
- // as a temporary remediation for events already buffered in a pod's internal
- // queue being skipped when the consumer group rebalances or the service is
- // redeployed. Long-term fix: start tracking max partition offsets in the
- // Update batches and commit them only when each batch succeeds. This will
- // not be perfect, as batch writes are async and can complete out of order,
- // but is better than what we're doing right now
- let curr_offset = offset.get_value();
- match offset.store() {
- Ok(_) => (),
- Err(e) => {
- metrics::counter!(UPDATE_PRODUCER_OFFSET, &[("op", "store_fail")]).increment(1);
- // TODO: consumer json_recv() should expose the source partition ID too
- error!("update_producer_loop: failed to store offset {curr_offset}, got: {e}");
+ // NOTE: we extended the autocommit interval in production envs to 20 seconds
+ // as a temporary remediation for events already buffered in a pod's internal
+ // queue being skipped when the consumer group rebalances or the service is
+ // redeployed. Long-term fix: start tracking max partition offsets in the
+ // Update batches and commit them only when each batch succeeds. This will
+ // not be perfect, as batch writes are async and can complete out of order,
+ // but is better than what we're doing right now
+ let curr_offset = offset.get_value();
+ match offset.store() {
+ Ok(_) => (),
+ Err(e) => {
+ metrics::counter!(UPDATE_PRODUCER_OFFSET, &[("op", "store_fail")]).increment(1);
+ // TODO: consumer json_recv() should expose the source partition ID too
+ error!("update_producer_loop: failed to store offset {curr_offset}, got: {e}");
+ }
}
- }
- if !config
- .filter_mode
- .should_process(&config.filtered_teams.teams, event.team_id)
- {
- metrics::counter!(SKIPPED_DUE_TO_TEAM_FILTER).increment(1);
- continue;
- }
+ if !config
+ .filter_mode
+ .should_process(&config.filtered_teams.teams, event.team_id)
+ {
+ metrics::counter!(SKIPPED_DUE_TO_TEAM_FILTER).increment(1);
+ continue;
+ }
- let updates = event.into_updates(config.update_count_skip_threshold);
+ let updates = event.into_updates_with(
+ config.update_count_skip_threshold,
+ config.eventdef_last_seen_floor_secs,
+ );
- metrics::counter!(EVENTS_RECEIVED).increment(1);
- metrics::counter!(UPDATES_SEEN).increment(updates.len() as u64);
- metrics::histogram!(UPDATES_PER_EVENT).record(updates.len() as f64);
+ metrics::counter!(EVENTS_RECEIVED).increment(1);
+ metrics::counter!(UPDATES_SEEN).increment(updates.len() as u64);
+ metrics::histogram!(UPDATES_PER_EVENT).record(updates.len() as f64);
- for update in updates {
- if batch.contains(&update) {
- metrics::counter!(COMPACTED_UPDATES).increment(1);
- continue;
+ for update in updates {
+ if batch.contains(&update) {
+ metrics::counter!(COMPACTED_UPDATES).increment(1);
+ continue;
+ }
+ batch.insert(update);
}
- batch.insert(update);
}
// We do the full batch insert before checking the time/batch size, because if we did this
@@ -224,9 +236,7 @@ pub async fn update_producer_loop(
// wait on the next event, which might come an arbitrary amount of time later. This bit me
// in testing, and while it's not a correctness problem and under normal load we'd never
// see it, we may as well just do the full batch insert first.
- if batch.len() >= config.compaction_batch_size
- || last_send.elapsed() > Duration::from_secs(10)
- {
+ if batch.len() >= config.compaction_batch_size || last_send.elapsed() > drain_interval {
last_send = tokio::time::Instant::now();
for update in batch.drain() {
if shared_cache.contains_key(&update) {
diff --git a/rust/property-defs-rs/src/main.rs b/rust/property-defs-rs/src/main.rs
index e8bbf16dd8e9..3bac3f42d7a7 100644
--- a/rust/property-defs-rs/src/main.rs
+++ b/rust/property-defs-rs/src/main.rs
@@ -9,6 +9,7 @@ use property_defs_rs::{
config::Config,
measuring_channel::measuring_channel,
metrics_consts::CHANNEL_CAPACITY,
+ types::MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
update_cache::Cache,
update_consumer_loop, update_producer_loop,
};
@@ -43,6 +44,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::init_with_defaults()?;
+ // Refuse the "0 disables it" convention: with flooring off, every event's last_seen_at is
+ // unique, dedup filters nothing, and the full event stream lands on posthog_eventdefinition
+ // as row updates. Failing the deploy is cheaper than that. The upper bound guards the same
+ // outcome from the other direction, where the jitter offset outruns the timestamp range.
+ if config.eventdef_last_seen_floor_secs <= 0
+ || config.eventdef_last_seen_floor_secs > MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS
+ {
+ return Err(format!(
+ "EVENTDEF_LAST_SEEN_FLOOR_SECS must be in 1..={MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS}, got {}: flooring bounds how often event-definition writes are re-issued and must not be disabled",
+ config.eventdef_last_seen_floor_secs
+ )
+ .into());
+ }
+
// Start continuous profiling if enabled (keep _agent alive for the duration of the program)
let _profiling_agent = match config.continuous_profiling.start_agent() {
Ok(agent) => agent,
diff --git a/rust/property-defs-rs/src/types.rs b/rust/property-defs-rs/src/types.rs
index cac71d9c5f13..aa20661ea896 100644
--- a/rust/property-defs-rs/src/types.rs
+++ b/rust/property-defs-rs/src/types.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt, hash::Hash, str::FromStr, sync::LazyLock};
-use chrono::{DateTime, Duration, DurationRound, RoundingError, Utc};
+use chrono::{DateTime, Utc};
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
@@ -227,17 +227,35 @@ pub struct Event {
impl From<&Event> for EventDefinition {
fn from(event: &Event) -> Self {
- EventDefinition {
- name: sanitize_string(&event.event),
- team_id: event.team_id,
- project_id: event.project_id,
- last_seen_at: get_floored_last_seen(),
- }
+ event.to_event_definition(DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS)
}
}
impl Event {
+ fn to_event_definition(&self, last_seen_floor_secs: i64) -> EventDefinition {
+ let name = sanitize_string(&self.event);
+ // Seed on the sanitized name because that is what ends up in the dedup key.
+ let jitter_seed = last_seen_jitter_seed(self.team_id, &name);
+
+ EventDefinition {
+ last_seen_at: floor_last_seen(Utc::now(), last_seen_floor_secs, jitter_seed),
+ name,
+ team_id: self.team_id,
+ project_id: self.project_id,
+ }
+ }
+
pub fn into_updates(self, skip_threshold: usize) -> Vec<Update> {
+ self.into_updates_with(skip_threshold, DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS)
+ }
+
+ /// As `into_updates`, but with an explicit flooring period for the event-definition dedup
+ /// key. See `floor_last_seen` for what the period controls.
+ pub fn into_updates_with(
+ self,
+ skip_threshold: usize,
+ last_seen_floor_secs: i64,
+ ) -> Vec<Update> {
if EVENTS_WITHOUT_PROPERTIES.contains(&self.event.as_str()) {
metrics::counter!(EVENTS_SKIPPED, &[("reason", "no_properties_event")]).increment(1);
return vec![];
@@ -252,7 +270,7 @@ impl Event {
let team_id = self.team_id;
let event = self.event.clone();
- let updates = self.into_updates_inner();
+ let updates = self.into_updates_inner(last_seen_floor_secs);
if updates.len() > skip_threshold {
warn!(
"Event {} for team {} has more than {} properties, skipping",
@@ -265,8 +283,10 @@ impl Event {
updates
}
- fn into_updates_inner(self) -> Vec<Update> {
- let mut updates = vec![Update::Event(EventDefinition::from(&self))];
+ fn into_updates_inner(self, last_seen_floor_secs: i64) -> Vec<Update> {
+ let mut updates = vec![Update::Event(
+ self.to_event_definition(last_seen_floor_secs),
+ )];
let Some(props) = &self.properties else {
return updates;
};
@@ -538,21 +558,69 @@ impl Hash for GroupType {
}
}
-// We round last seen to the nearest hour. Unwrap is safe here because
-// the duration is positive, non-zero, and smaller than time since epoch
-pub fn get_floored_last_seen() -> DateTime<Utc> {
- floor_datetime(Utc::now(), Duration::hours(1)).unwrap()
-}
+// An event definition's `last_seen_at` participates in its Hash and Eq, so flooring it is what
+// bounds how often we re-issue the definition's write: one per (team, name) per period, per pod.
+// The value itself never reaches Postgres — the write path binds a fresh Utc::now() per attempt —
+// so a coarser period trades a staler stored last_seen_at for proportionally fewer writes.
+pub const DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS: i64 = 3600;
+
+// Upper bound on the period, 30 days. Nothing operational wants a window this coarse — the cap
+// exists so the jitter offset stays small enough that the bucket arithmetic below cannot overflow
+// or leave chrono's representable range, which is what makes its fallback unreachable.
+pub const MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS: i64 = 30 * 24 * 3600;
+
+/// Start of the current `period_secs` window containing `now`, offset per identity by
+/// `jitter_seed` so that different identities roll over at different points in the period.
+///
+/// Without the offset every pod rotates every key at the same wall-clock instant, so each rollover
+/// makes the entire active keyspace writable at once. That is tolerable hourly and decidedly not
+/// at coarser periods, where a day's worth of definition writes would land in the minutes after
+/// the boundary, on a table that already struggles to keep autovacuum ahead of its dead tuples.
+///
+/// The result always falls in `(now - period, now]`, matching un-jittered flooring, so it can
+/// never produce a future timestamp.
+///
+/// The period is clamped into `1..=MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS`, with a non-positive value
+/// treated as `DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS`. Both ends of that clamp guard the same
+/// failure: an unfloored `last_seen_at` is unique per event, so the dedup cache filters nothing
+/// and the full event stream reaches `posthog_eventdefinition` as row updates. A non-positive
+/// period would produce that directly; an unbounded one would produce it via the fallback below,
+/// since a large enough offset pushes `bucket_start` outside chrono's range. Config validation at
+/// startup rejects out-of-range values loudly; this clamp backstops callers that bypass `Config`.
+///
+/// With the period capped, `offset` stays under a month of seconds, so `shifted` cannot overflow
+/// and `bucket_start` stays within a month of `now` — `from_timestamp` therefore cannot fail and
+/// the `unwrap_or` never fires.
+pub fn floor_last_seen(now: DateTime<Utc>, period_secs: i64, jitter_seed: u64) -> DateTime<Utc> {
+ let period_secs = if period_secs > 0 {
+ period_secs.min(MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS)
+ } else {
+ DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS
+ };
-fn floor_datetime(dt: DateTime<Utc>, duration: Duration) -> Result<DateTime<Utc>, RoundingError> {
- let rounded = dt.duration_round(duration)?;
+ let offset = (jitter_seed % period_secs as u64) as i64;
+ let shifted = now.timestamp() + offset;
+ let bucket_start = shifted.div_euclid(period_secs) * period_secs - offset;
- // If we rounded up
- if rounded > dt {
- Ok(rounded - duration)
- } else {
- Ok(rounded)
+ DateTime::from_timestamp(bucket_start, 0).unwrap_or(now)
+}
+
+/// Stable per-identity hash used to spread definition rollovers across the flooring period.
+///
+/// Hand-rolled FNV-1a rather than a standard library or `ahash` hasher because the offset has to
+/// be identical on every pod, across restarts, and across dependency upgrades. `DefaultHasher` and
+/// `ahash`'s default state are randomized per process, and any change to the hash shifts every
+/// key's boundary at once, which is the synchronized rewrite the offset exists to prevent.
+pub fn last_seen_jitter_seed(team_id: i32, name: &str) -> u64 {
+ const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
+ const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
+
+ let mut hash = FNV_OFFSET_BASIS;
+ for byte in team_id.to_le_bytes().iter().chain(name.as_bytes()) {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(FNV_PRIME);
}
+ hash
}
// We impose some limits on some fields for legacy reasons, and drop updates that don't conform to them
@@ -586,7 +654,9 @@ impl EventDefinition {
self.name,
self.team_id,
self.project_id,
- Utc::now() // We floor the update datetime to the nearest day for cache purposes, but can insert the exact time we see the event
+ // last_seen_at is floored only to bound how often we re-issue this write; the stored
+ // value is the real time we saw the event.
+ Utc::now()
).execute(executor).await.map(|_| ());
metrics::counter!(UPDATES_ISSUED, &[("type", "event_definition")]).increment(1);
diff --git a/rust/property-defs-rs/tests/producer_loop.rs b/rust/property-defs-rs/tests/producer_loop.rs
new file mode 100644
index 000000000000..04443a1da639
--- /dev/null
+++ b/rust/property-defs-rs/tests/producer_loop.rs
@@ -0,0 +1,119 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use rdkafka::producer::FutureRecord;
+use serde_json::json;
+
+use common_kafka::kafka_consumer::SingleTopicConsumer;
+use property_defs_rs::{
+ config::Config, measuring_channel::measuring_channel, types::Update, update_cache::Cache,
+ update_producer_loop,
+};
+
+const TOPIC: &str = "propdefs-lull-drain-topic";
+const DRAIN_SECS: u64 = 1;
+
+fn test_lifecycle_handle() -> lifecycle::Handle {
+ let mut manager = lifecycle::Manager::builder("test").build();
+ manager.register("producer", lifecycle::ComponentOptions::new())
+}
+
+// A partial compaction batch has to reach the channel once its partition goes quiet. The loop only
+// re-evaluates its flush condition when it wakes, so without the timer arm it parks in
+// json_recv() after consuming an event and the batch sits there until traffic resumes.
+//
+// Two details make this test actually exercise that path rather than passing by accident.
+// compaction_batch_size is far above one event's worth of updates, so size can never trigger the
+// flush. And the assertion is on a *second* event, produced after the first batch has drained:
+// the first event arrives while the consumer is still joining the group, several seconds after
+// `last_send` was initialised, so its flush check passes on elapsed time alone and proves nothing.
+// By the second event the consumer is warm and `last_send` was just reset, so elapsed is well
+// under the drain interval and only the timer can get that batch out.
+#[tokio::test]
+async fn test_producer_flushes_a_partial_batch_when_events_stop_arriving() {
+ let (cluster, producer) = common_kafka::test::create_mock_kafka().await;
+ cluster.create_topic(TOPIC, 1, 1).expect("create topic");
+
+ let mut config = Config::init_with_defaults().unwrap();
+ config.kafka.kafka_hosts = cluster.bootstrap_servers();
+ config.consumer.kafka_consumer_topic = TOPIC.to_string();
+ config.consumer.kafka_consumer_group = "propdefs-lull-drain-group".to_string();
+ config.consumer.kafka_consumer_offset_reset = "earliest".to_string();
+ config.compaction_batch_size = 10_000;
+ config.producer_drain_interval_secs = DRAIN_SECS;
+
+ let send = |event: &'static str| {
+ let payload = json!({
+ "team_id": 111,
+ "project_id": 111,
+ "event": event,
+ "properties": r#"{"$browser":"Chrome"}"#,
+ })
+ .to_string();
+ let producer = producer.clone();
+ async move {
+ producer
+ .send_result(FutureRecord::to(TOPIC).key("k").payload(&payload))
+ .expect("enqueue")
+ .await
+ .expect("delivery")
+ .expect("delivered");
+ }
+ };
+
+ let consumer = SingleTopicConsumer::new(config.kafka.clone(), config.consumer.clone()).unwrap();
+ let cache = Arc::new(Cache::new(1000, 1000, 1000));
+ let (tx, mut rx) = measuring_channel::<Update>(1000);
+
+ let handle = test_lifecycle_handle();
+ let loop_task = tokio::spawn(update_producer_loop(
+ config.clone(),
+ consumer,
+ cache,
+ tx,
+ handle.clone(),
+ ));
+
+ // First event: gets the consumer joined and the batch drained once, which resets `last_send`.
+ send("$pageview").await;
+ await_event_definition(&mut rx, "$pageview").await;
+
+ // Second event, on a warm consumer. Nothing else will arrive, so the timer is the only thing
+ // that can flush this one.
+ send("$identify").await;
+ await_event_definition(&mut rx, "$identify").await;
+
+ // Drop the consumer inside the task. Left running, its drop lands on runtime teardown, where
+ // librdkafka's synchronous close adds ~45s. Cancel the token directly rather than calling
+ // request_shutdown(): that routes through the lifecycle Manager, which this test doesn't run.
+ handle.shutdown_token().cancel();
+ tokio::time::timeout(Duration::from_secs(30), loop_task)
+ .await
+ .expect("producer loop did not observe the shutdown signal")
+ .expect("producer loop panicked");
+}
+
+// Reads until the named event's definition shows up. The compaction batch is an AHashSet, so a
+// flush delivers its updates in arbitrary order, and one event yields property rows alongside the
+// definition. The timeout is generous against mock-broker startup while staying far below the
+// point where a missing timer arm could be mistaken for slowness.
+async fn await_event_definition(
+ rx: &mut property_defs_rs::measuring_channel::MeasuringReceiver<Update>,
+ event: &str,
+) {
+ let deadline = Duration::from_secs(30);
+ let found = tokio::time::timeout(deadline, async {
+ loop {
+ let update = rx.recv().await.expect("producer channel closed");
+ if matches!(&update, Update::Event(ed) if ed.name == event && ed.team_id == 111) {
+ return;
+ }
+ }
+ })
+ .await;
+
+ assert!(
+ found.is_ok(),
+ "no event definition for {event} was flushed within {deadline:?}"
+ );
+}
diff --git a/rust/property-defs-rs/tests/types.rs b/rust/property-defs-rs/tests/types.rs
index 8d83baacb588..0ccb210ad8bc 100644
--- a/rust/property-defs-rs/tests/types.rs
+++ b/rust/property-defs-rs/tests/types.rs
@@ -1,25 +1,176 @@
use chrono::Utc;
use property_defs_rs::types::{
- detect_property_type, get_floored_last_seen, Event, PropertyValueType, Update,
+ detect_property_type, floor_last_seen, last_seen_jitter_seed, Event, PropertyValueType, Update,
+ DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS, MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
};
use rstest::rstest;
use serde_json::{json, Map, Number, Value};
+// The floored value is a dedup key, so what matters is which window it identifies, not that it
+// lands on a round clock boundary (per-identity jitter means it usually won't). It must stay in
+// (now - period, now]: a future value would defeat the write path's
+// `last_seen_at < EXCLUDED.last_seen_at` guard, and one a full period old would re-issue the
+// definition's write early.
+#[rstest]
+#[case(3600)]
+#[case(86400)]
+fn test_floor_last_seen_lands_in_the_current_window(#[case] period_secs: i64) {
+ let now = Utc::now();
+
+ for seed in [0, 1, 12345, u64::MAX] {
+ let floored = floor_last_seen(now, period_secs, seed);
+ assert!(floored <= now, "seed {seed} produced a future timestamp");
+ assert!(
+ now - floored < chrono::Duration::seconds(period_secs),
+ "seed {seed} produced a timestamp a full period old"
+ );
+ assert_eq!(floored.timestamp_subsec_nanos(), 0);
+ }
+}
+
+// The whole point of the period is that it reaches the dedup key: EventDefinition's Hash and Eq
+// both cover last_seen_at. Asserting hourly != daily keys here would be wrong, because the daily
+// window start is always also an hourly window start (3600 divides 86400 and both offsets are the
+// seed mod 3600), so the two keys legitimately coincide for one hour of every day. Instead,
+// compute the expected window independently and bracket Utc::now(): this can never false-fail,
+// and if the period stops reaching floor_last_seen it fails whenever the default and requested
+// windows differ, which is 23 of every 24 hours.
#[test]
-fn test_date_flooring() {
- use chrono::Timelike;
+fn test_flooring_period_reaches_the_event_definition_dedup_key() {
+ const DAILY: i64 = 86400;
+ let event = || Event {
+ team_id: 111,
+ project_id: 111,
+ event: "$pageview".to_string(),
+ properties: None,
+ };
+
+ let def_of = |updates: Vec<Update>| match updates.into_iter().next().unwrap() {
+ Update::Event(ed) => ed,
+ other => panic!("expected an event definition first, got {other:?}"),
+ };
+
+ let before = Utc::now();
+ let daily = def_of(event().into_updates_with(10_000, DAILY));
+ let defaulted = def_of(event().into_updates(10_000));
+ let after = Utc::now();
+
+ let seed = last_seen_jitter_seed(111, "$pageview");
+ assert!(
+ daily.last_seen_at == floor_last_seen(before, DAILY, seed)
+ || daily.last_seen_at == floor_last_seen(after, DAILY, seed),
+ "the explicit period must reach floor_last_seen, got {}",
+ daily.last_seen_at
+ );
+ assert!(
+ defaulted.last_seen_at
+ == floor_last_seen(before, DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS, seed)
+ || defaulted.last_seen_at
+ == floor_last_seen(after, DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS, seed),
+ "into_updates must floor at the documented default period, got {}",
+ defaulted.last_seen_at
+ );
+}
+
+// Jitter has to be a pure function of the identity: every pod computes it independently, and if
+// they disagree the same definition gets written once per pod per period instead of once.
+#[test]
+fn test_jitter_seed_is_stable_and_identity_scoped() {
+ assert_eq!(
+ last_seen_jitter_seed(111, "$pageview"),
+ last_seen_jitter_seed(111, "$pageview")
+ );
+ assert_ne!(
+ last_seen_jitter_seed(111, "$pageview"),
+ last_seen_jitter_seed(112, "$pageview")
+ );
+ assert_ne!(
+ last_seen_jitter_seed(111, "$pageview"),
+ last_seen_jitter_seed(111, "$identify")
+ );
+}
+
+// This is the test that guards the reason jitter exists. Un-jittered, every key in the fleet rolls
+// over at the same instant, so a coarse period dumps a period's worth of definition writes into
+// the moments after the boundary. Spreading window starts across the period turns that burst into
+// a steady trickle.
+#[test]
+fn test_jitter_spreads_window_starts_across_the_period() {
+ const PERIOD: i64 = 86400;
+ const BUCKETS: i64 = 24;
+
+ let now = Utc::now();
+ let mut occupied = std::collections::HashSet::new();
+ for team_id in 0..2000 {
+ let seed = last_seen_jitter_seed(team_id, "$pageview");
+ let age = now.timestamp() - floor_last_seen(now, PERIOD, seed).timestamp();
+ occupied.insert(age / (PERIOD / BUCKETS));
+ }
+
+ assert_eq!(
+ occupied.len() as i64,
+ BUCKETS,
+ "expected window starts in all {BUCKETS} sub-ranges of the period, got {occupied:?}"
+ );
+}
+
+// Advancing by exactly one period must advance the window by exactly one period, for every
+// identity. An off-by-one here re-issues writes twice per period, or skips one entirely.
+#[test]
+fn test_window_advances_by_exactly_one_period() {
+ const PERIOD: i64 = 86400;
+ let now = Utc::now();
+
+ for team_id in 0..50 {
+ let seed = last_seen_jitter_seed(team_id, "$pageview");
+ let first = floor_last_seen(now, PERIOD, seed);
+ let next = floor_last_seen(now + chrono::Duration::seconds(PERIOD), PERIOD, seed);
+ assert_eq!(
+ (next - first).num_seconds(),
+ PERIOD,
+ "team {team_id} did not advance by exactly one period"
+ );
+ }
+}
+
+// "No flooring" must not be expressible: an unfloored last_seen_at makes every event a unique
+// dedup key, so the cache filters nothing and the full event stream reaches
+// posthog_eventdefinition as row updates. Startup validation rejects a non-positive config
+// value loudly; this pins the function-level backstop that clamps to the default instead of
+// dividing by zero or passing the value through.
+#[rstest]
+#[case(0)]
+#[case(-1)]
+fn test_non_positive_period_floors_at_the_default(#[case] period_secs: i64) {
let now = Utc::now();
- let rounded = get_floored_last_seen();
+ assert_eq!(
+ floor_last_seen(now, period_secs, 12345),
+ floor_last_seen(now, DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS, 12345)
+ );
+}
- // Time should be rounded to the nearest hour
- assert_eq!(rounded.minute(), 0);
- assert_eq!(rounded.second(), 0);
- assert_eq!(rounded.nanosecond(), 0);
- assert!(rounded <= now);
+// The same hazard from the other end. An uncapped period lets the jitter offset push bucket_start
+// outside chrono's representable range, and the resulting fallback hands back an unfloored `now` —
+// a unique dedup key per event, which is exactly the write amplification flooring exists to stop.
+#[rstest]
+#[case(MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS + 1)]
+#[case(i64::MAX)]
+fn test_oversized_period_floors_at_the_maximum(#[case] period_secs: i64) {
+ let now = Utc::now();
- // The difference between now and rounded should be less than 1 hour
- assert!(now - rounded < chrono::Duration::hours(1));
+ for seed in [0, 12345, u64::MAX] {
+ let floored = floor_last_seen(now, period_secs, seed);
+ assert_eq!(
+ floored,
+ floor_last_seen(now, MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS, seed),
+ "seed {seed} did not clamp to the maximum period"
+ );
+ assert!(
+ floored <= now && (now - floored).num_seconds() < MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
+ "seed {seed} floored outside the current window"
+ );
+ }
}
#[test]