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.

fix(capture): seed server-assigned event UUIDv7 from event timestamp (#65754)

Robbie886aa466fd7a
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 1f299d43f1ab..47ba2fd363e1 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -23,7 +23,7 @@ use crate::{
global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter},
prometheus::{report_clock_skew, report_dropped_events},
router, sinks,
- utils::uuid_v7,
+ utils::uuid_v7_from_datetime,
v0_request::{
DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata, ProcessingContext,
},
@@ -93,7 +93,8 @@ fn create_heatmap_redirect(
let heatmap_event = RawEvent {
token: event.token.clone(),
distinct_id: Some(serde_json::Value::String(distinct_id)),
- uuid: Some(uuid_v7()),
+ // Leave unset so process_single_event seeds the UUID from the event timestamp.
+ uuid: None,
event: "$$heatmap".to_string(),
properties,
timestamp: event.timestamp.clone(),
@@ -180,7 +181,10 @@ pub fn process_single_event(
}
let event = CapturedEvent {
- uuid: event.uuid.unwrap_or_else(uuid_v7),
+ // Seed the UUIDv7 from the event timestamp, not ingestion time, so its embedded time tracks events.timestamp.
+ uuid: event
+ .uuid
+ .unwrap_or_else(|| uuid_v7_from_datetime(parsed_timestamp.timestamp)),
distinct_id: event
.extract_distinct_id()
.ok_or(CaptureError::MissingDistinctId)?,
@@ -401,6 +405,7 @@ pub async fn process_events(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{OverflowReason, ProcessingContext};
use chrono::{DateTime, TimeZone, Utc};
use common_types::RawEvent;
@@ -449,7 +454,7 @@ mod tests {
properties.insert("distinct_id".to_string(), json!("test_user"));
RawEvent {
- uuid: Some(uuid_v7()),
+ uuid: None,
distinct_id: None,
event: event_name.to_string(),
properties,
@@ -461,6 +466,79 @@ mod tests {
}
}
+ #[test]
+ fn test_server_assigned_uuid_encodes_event_timestamp() {
+ // Ingestion clock is in 2023, but the event's own timestamp is back in 2020.
+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ let context = create_test_context(now, None);
+
+ let mut properties = HashMap::new();
+ properties.insert("distinct_id".to_string(), json!("test_user"));
+ let event = RawEvent {
+ uuid: None,
+ distinct_id: None,
+ event: "$pageview".to_string(),
+ properties,
+ timestamp: Some("2020-06-15T00:00:00Z".to_string()),
+ offset: None,
+ set: None,
+ set_once: None,
+ token: Some("test_token".to_string()),
+ };
+
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+ let processed = process_single_event(&event, historical_cfg, &context).unwrap();
+
+ let expected_millis = processed
+ .metadata
+ .computed_timestamp
+ .unwrap()
+ .timestamp_millis() as u128;
+ // The high 48 bits of a UUIDv7 hold the Unix-millisecond timestamp.
+ let uuid_millis = processed.event.uuid.as_u128() >> 80;
+ assert_eq!(uuid_millis, expected_millis);
+ assert!(now.timestamp_millis() as u128 - uuid_millis > 60_000_000_000);
+ }
+
+ #[test]
+ fn test_server_assigned_uuid_floors_pre_epoch_event() {
+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ let context = create_test_context(now, None);
+
+ let mut properties = HashMap::new();
+ properties.insert("distinct_id".to_string(), json!("test_user"));
+ // A pre-1970 timestamp has negative Unix millis, which can't fit the unsigned UUIDv7 time field.
+ let event = RawEvent {
+ uuid: None,
+ distinct_id: None,
+ event: "$pageview".to_string(),
+ properties,
+ timestamp: Some("1969-06-15T00:00:00Z".to_string()),
+ offset: None,
+ set: None,
+ set_once: None,
+ token: Some("test_token".to_string()),
+ };
+
+ let historical_cfg = router::HistoricalConfig::new(false, 1);
+ let processed = process_single_event(&event, historical_cfg, &context).unwrap();
+
+ // The event keeps its pre-epoch timestamp, but the uuid floors to the epoch rather than wrapping to garbage.
+ assert!(
+ processed
+ .metadata
+ .computed_timestamp
+ .unwrap()
+ .timestamp_millis()
+ < 0
+ );
+ assert_eq!(processed.event.uuid.as_u128() >> 80, 0);
+ }
+
#[test]
fn test_process_single_event_with_invalid_sent_at() {
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
@@ -1936,12 +2014,15 @@ mod tests {
}
}
+ let timestamp = "2023-01-01T11:00:00Z";
RawEvent {
- uuid: Some(uuid_v7()),
+ uuid: Some(uuid_v7_from_datetime(
+ DateTime::parse_from_rfc3339(timestamp).unwrap(),
+ )),
distinct_id: None,
event: "$pageview".to_string(),
properties,
- timestamp: Some("2023-01-01T11:00:00Z".to_string()),
+ timestamp: Some(timestamp.to_string()),
offset: None,
set: None,
set_once: None,
@@ -1967,7 +2048,7 @@ mod tests {
}
let event = RawEvent {
- uuid: Some(uuid_v7()),
+ uuid: None,
distinct_id: None,
event: "$pageview".to_string(),
properties,
diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rs
index 90b5132c83b9..4fae22ea2c3c 100644
--- a/rust/capture/src/events/overflow_stamping.rs
+++ b/rust/capture/src/events/overflow_stamping.rs
@@ -105,7 +105,7 @@ pub fn stamp_overflow_reason(
#[cfg(test)]
mod tests {
use super::*;
- use crate::utils::uuid_v7;
+ use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{ProcessedEvent, ProcessedEventMetadata};
use common_types::CapturedEvent;
use std::num::NonZeroU32;
@@ -116,8 +116,9 @@ mod tests {
distinct_id: &str,
force_overflow: bool,
) -> ProcessedEvent {
+ let timestamp = chrono::Utc::now();
let event = CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: distinct_id.to_string(),
session_id: None,
ip: "127.0.0.1".to_string(),
@@ -126,7 +127,7 @@ mod tests {
sent_at: None,
token: token.to_string(),
event: "test".to_string(),
- timestamp: chrono::Utc::now(),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
};
diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rs
index 1eb0c1499b8c..df9747e9deab 100644
--- a/rust/capture/src/events/recordings.rs
+++ b/rust/capture/src/events/recordings.rs
@@ -31,7 +31,7 @@ use crate::{
},
prometheus::report_dropped_events,
sinks,
- utils::uuid_v7,
+ utils::uuid_v7_from_datetime,
v0_request::{
DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata, ProcessingContext,
},
@@ -209,7 +209,9 @@ pub async fn process_replay_events(
let mut events_iter = events.into_iter();
let mut first_event = events_iter.next().ok_or(CaptureError::EmptyBatch)?;
- let uuid = first_event.uuid.unwrap_or_else(uuid_v7);
+ let uuid = first_event
+ .uuid
+ .unwrap_or_else(|| uuid_v7_from_datetime(computed_timestamp));
let distinct_id = first_event
.extract_distinct_id()
.ok_or(CaptureError::MissingDistinctId)?;
diff --git a/rust/capture/src/sinks/fallback.rs b/rust/capture/src/sinks/fallback.rs
index c2684a3f6a00..507ec2c9d9b6 100644
--- a/rust/capture/src/sinks/fallback.rs
+++ b/rust/capture/src/sinks/fallback.rs
@@ -108,7 +108,7 @@ impl Event for FallbackSink {
mod tests {
use super::*;
use crate::sinks::print::PrintSink;
- use crate::utils::uuid_v7;
+ use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{DataType, ProcessedEventMetadata};
use common_types::CapturedEvent;
use std::time::Duration;
@@ -134,9 +134,12 @@ mod tests {
let fallback_sink = FallbackSink::new(fail_sink, print_sink);
// Create test event
+ let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
let event = ProcessedEvent {
event: CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "test_id".to_string(),
session_id: None,
ip: "127.0.0.1".to_string(),
@@ -145,9 +148,7 @@ mod tests {
sent_at: None,
token: "test_token".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&chrono::Utc),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
},
@@ -185,9 +186,12 @@ mod tests {
let fallback_sink = FallbackSink::new(fail_sink.clone(), fail_sink);
// Create test event
+ let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
let event = ProcessedEvent {
event: CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "test_id".to_string(),
session_id: None,
ip: "127.0.0.1".to_string(),
@@ -196,9 +200,7 @@ mod tests {
sent_at: None,
token: "test_token".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&chrono::Utc),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
},
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index b32e4ed44ae7..1b2e6ca13859 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -794,7 +794,7 @@ mod tests {
use crate::config::{self, EnvelopeCompression};
use crate::sinks::kafka::KafkaSink;
use crate::sinks::Event;
- use crate::utils::uuid_v7;
+ use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};
use common_types::CapturedEvent;
use rand::distributions::Alphanumeric;
@@ -895,8 +895,9 @@ mod tests {
let (cluster, sink) = start_on_mocked_sink(Some(3000000)).await;
let distinct_id = "test_distinct_id_123".to_string();
+ let timestamp = chrono::Utc::now();
let event: CapturedEvent = CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: distinct_id.clone(),
session_id: None,
ip: "".to_string(),
@@ -905,7 +906,7 @@ mod tests {
sent_at: None,
token: "token1".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::Utc::now(),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
};
@@ -949,8 +950,9 @@ mod tests {
.take(2_000_000)
.map(char::from)
.collect();
+ let timestamp = chrono::Utc::now();
let captured = CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "id1".to_string(),
session_id: None,
ip: "".to_string(),
@@ -959,7 +961,7 @@ mod tests {
sent_at: None,
token: "token1".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::Utc::now(),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
};
@@ -980,9 +982,10 @@ mod tests {
.map(char::from)
.collect();
+ let timestamp = chrono::Utc::now();
let big_event = ProcessedEvent {
event: CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "id1".to_string(),
session_id: None,
ip: "".to_string(),
@@ -991,7 +994,7 @@ mod tests {
sent_at: None,
token: "token1".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::Utc::now(),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
},
@@ -1210,8 +1213,9 @@ mod tests {
}
fn create_test_event(input: &EventInput) -> ProcessedEvent {
+ let timestamp = chrono::Utc::now();
let event = CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "test_user".to_string(),
session_id: Some("session123".to_string()),
ip: "127.0.0.1".to_string(),
@@ -1220,7 +1224,7 @@ mod tests {
sent_at: None,
token: "test_token".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::Utc::now(),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
};
diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rs
index c18215a9b888..11cd03655dc6 100644
--- a/rust/capture/src/sinks/s3.rs
+++ b/rust/capture/src/sinks/s3.rs
@@ -303,7 +303,7 @@ impl Event for S3Sink {
#[cfg(test)]
mod tests {
use super::*;
- use crate::utils::uuid_v7;
+ use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{DataType, ProcessedEventMetadata};
use common_types::CapturedEvent;
use tokio_util::sync::CancellationToken;
@@ -336,9 +336,12 @@ mod tests {
}
fn create_test_event() -> ProcessedEvent {
+ let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
ProcessedEvent {
event: CapturedEvent {
- uuid: uuid_v7(),
+ uuid: uuid_v7_from_datetime(timestamp),
distinct_id: "test_id".to_string(),
session_id: None,
ip: "127.0.0.1".to_string(),
@@ -347,9 +350,7 @@ mod tests {
sent_at: None,
token: "test_token".to_string(),
event: "test_event".to_string(),
- timestamp: chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
- .unwrap()
- .with_timezone(&chrono::Utc),
+ timestamp,
is_cookieless_mode: false,
historical_migration: false,
},
diff --git a/rust/capture/src/utils.rs b/rust/capture/src/utils.rs
index dc9e4a2ee79e..e29ffe3f1de7 100644
--- a/rust/capture/src/utils.rs
+++ b/rust/capture/src/utils.rs
@@ -1,5 +1,6 @@
use axum::http::HeaderMap;
use base64::Engine;
+use chrono::{DateTime, TimeZone};
use common_types::RawEvent;
use rand::RngCore;
use std::collections::HashSet;
@@ -58,12 +59,15 @@ const fn encode_unix_timestamp_millis(millis: u64, random_bytes: &[u8; 10]) -> U
Uuid::from_fields(millis_high, millis_low, random_and_version, &d4)
}
-pub fn uuid_v7() -> Uuid {
+/// Builds a UUIDv7 whose time component is the given Unix-ms timestamp.
+pub fn uuid_v7(unix_millis: u64) -> Uuid {
let bytes = random_bytes();
- let now = time::OffsetDateTime::now_utc();
- let now_millis: u64 = now.unix_timestamp() as u64 * 1_000 + now.millisecond() as u64;
+ encode_unix_timestamp_millis(unix_millis, &bytes)
+}
- encode_unix_timestamp_millis(now_millis, &bytes)
+/// Builds a UUIDv7 whose time component is the given instant. Pre-epoch datetimes are floored to the epoch, since the unsigned time field can't represent negatives.
+pub fn uuid_v7_from_datetime<Tz: TimeZone>(datetime: DateTime<Tz>) -> Uuid {
+ uuid_v7(datetime.timestamp_millis().max(0) as u64)
}
pub fn extract_lib_version(form: &EventFormData, params: &EventQuery) -> Option<String> {
@@ -259,3 +263,28 @@ pub fn extract_token(events: &[RawEvent]) -> Result<String, CaptureError> {
_ => Err(CaptureError::MultipleTokensError),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // The high 48 bits of a UUIDv7 hold the Unix-millisecond timestamp.
+ fn uuid_time_millis(uuid: Uuid) -> u128 {
+ uuid.as_u128() >> 80
+ }
+
+ #[test]
+ fn uuid_v7_from_datetime_encodes_the_instant() {
+ // A non-UTC offset still yields the same absolute instant in the UUID.
+ let ts = DateTime::parse_from_rfc3339("2020-06-15T00:00:00Z").unwrap();
+ let uuid = uuid_v7_from_datetime(ts);
+ assert_eq!(uuid_time_millis(uuid), ts.timestamp_millis() as u128);
+ assert_eq!(uuid.get_version_num(), 7);
+ }
+
+ #[test]
+ fn uuid_v7_from_datetime_floors_pre_epoch_to_zero() {
+ let ts = DateTime::parse_from_rfc3339("1969-06-15T00:00:00Z").unwrap();
+ assert_eq!(uuid_time_millis(uuid_v7_from_datetime(ts)), 0);
+ }
+}