: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
chore(batch-import-worker): handle null fields (#61714)
Zach Brown522368a19e76
diff --git a/rust/batch-import-worker/src/parse/content/amplitude.rs b/rust/batch-import-worker/src/parse/content/amplitude.rsindex 3fc052a7e28b..9c6fe69c508c 100644--- a/rust/batch-import-worker/src/parse/content/amplitude.rs+++ b/rust/batch-import-worker/src/parse/content/amplitude.rs@@ -30,9 +30,21 @@ pub struct AmplitudeData {deserialize_with = "crate::parse::serialization::deserialize_flexible_bool")]pub user_properties_updated: bool,- #[serde(rename = "group_first_event", default)]+ // Amplitude emits `null` (rather than omitting the field) for absent+ // object-typed columns; `deserialize_null_as_default` lets us accept+ // both shapes — missing and explicit-`null` — into the empty default.+ // Same reasoning applies to every map-typed field on `AmplitudeEvent`.+ #[serde(+ rename = "group_first_event",+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub group_first_event: HashMap<String, Value>,- #[serde(rename = "group_ids", default)]+ #[serde(+ rename = "group_ids",+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub group_ids: HashMap<String, Value>,}@@ -55,7 +67,10 @@ pub struct AmplitudeEvent {pub client_event_time: Option<String>,pub client_upload_time: Option<String>,pub country: Option<String>,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub data: AmplitudeData,pub data_type: Option<String>,pub device_brand: Option<String>,@@ -68,14 +83,23 @@ pub struct AmplitudeEvent {pub dma: Option<String>,#[serde(default)]pub event_id: i64,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub event_properties: HashMap<String, Value>,pub event_time: Option<String>,pub event_type: Option<String>,pub global_user_properties: Option<Value>,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub group_properties: HashMap<String, HashMap<String, HashMap<String, Value>>>,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub groups: HashMap<String, Vec<String>>,pub idfa: Option<String>,pub ip_address: Option<String>,@@ -96,7 +120,10 @@ pub struct AmplitudeEvent {deserialize_with = "crate::parse::serialization::deserialize_flexible_option_bool")]pub paying: Option<bool>,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub plan: HashMap<String, Value>,pub platform: Option<String>,pub processed_time: Option<String>,@@ -110,7 +137,10 @@ pub struct AmplitudeEvent {pub start_version: Option<String>,pub user_creation_time: Option<String>,pub user_id: Option<String>,- #[serde(default)]+ #[serde(+ default,+ deserialize_with = "crate::parse::serialization::deserialize_null_as_default"+ )]pub user_properties: HashMap<String, Value>,pub uuid: Option<String>,pub version_name: Option<String>,@@ -2170,4 +2200,67 @@ mod tests {"now must be a string in serialized output");}++ /// Amplitude exports the full column set on every row, emitting `null`+ /// for absent object-typed fields like `plan`, `event_properties`,+ /// `user_properties`, `group_properties`, `groups`, and `data`. Bare+ /// `#[serde(default)]` only covers the missing-field case — this pins+ /// the present-and-null case that `deserialize_null_as_default` handles.+ #[test]+ fn test_amplitude_event_with_null_map_fields_parses() {+ let json = r#"{+ "$insert_id": "abc",+ "event_type": "Test Event",+ "user_id": "user-1",+ "event_time": "2023-10-15 14:30:00",+ "data": null,+ "event_properties": null,+ "user_properties": null,+ "group_properties": null,+ "groups": null,+ "plan": null,+ "global_user_properties": null+ }"#;++ let event: AmplitudeEvent = serde_json::from_str(json)+ .expect("null map-typed fields must deserialize as empty defaults");++ assert!(event.event_properties.is_empty());+ assert!(event.user_properties.is_empty());+ assert!(event.group_properties.is_empty());+ assert!(event.groups.is_empty());+ assert!(event.plan.is_empty());+ assert!(event.data.group_first_event.is_empty());+ assert!(event.data.group_ids.is_empty());+ assert_eq!(event.event_type.as_deref(), Some("Test Event"));+ }++ /// The same fields with real values must still deserialize normally —+ /// the null-tolerance must not regress the happy path.+ #[test]+ fn test_amplitude_event_with_populated_map_fields_parses() {+ let json = r#"{+ "event_type": "Test Event",+ "user_id": "user-1",+ "event_properties": {"action": "click"},+ "user_properties": {"plan_tier": "pro"},+ "groups": {"customer": ["880"]},+ "plan": {"branch": "main"},+ "data": {"path": "/checkout", "group_first_event": {"customer": true}, "group_ids": {"customer": 1}}+ }"#;++ let event: AmplitudeEvent =+ serde_json::from_str(json).expect("populated map fields must deserialize");++ assert_eq!(event.event_properties.get("action"), Some(&json!("click")));+ assert_eq!(event.user_properties.get("plan_tier"), Some(&json!("pro")));+ assert_eq!(event.groups.get("customer"), Some(&vec!["880".to_string()]));+ assert_eq!(event.plan.get("branch"), Some(&json!("main")));+ assert_eq!(event.data.path.as_deref(), Some("/checkout"));+ assert_eq!(+ event.data.group_first_event.get("customer"),+ Some(&json!(true))+ );+ assert_eq!(event.data.group_ids.get("customer"), Some(&json!(1)));+ }}diff --git a/rust/batch-import-worker/src/parse/serialization.rs b/rust/batch-import-worker/src/parse/serialization.rsindex 59629e54787b..e7ec41d97fe6 100644--- a/rust/batch-import-worker/src/parse/serialization.rs+++ b/rust/batch-import-worker/src/parse/serialization.rs@@ -1,6 +1,29 @@-use serde::{de, Deserializer};+use serde::{de, Deserialize, Deserializer};use std::fmt;+/// Deserialize a value of type `T: Default + Deserialize`, treating JSON+/// `null` as `T::default()`.+///+/// Use this on fields where the upstream source emits `null` (rather than+/// omitting the field) when a value is absent — Amplitude exports, for+/// example, include every column on every row and emit `null` for absent+/// object-typed fields like `plan`, `event_properties`, `user_properties`,+/// `group_properties`, `groups`. Bare `#[serde(default)]` only fires when+/// the field is **missing**; if the field is present-and-`null`, serde+/// tries to deserialize `null` into the target type and fails for+/// `HashMap`, structs, and other non-Option types.+///+/// Pair with `#[serde(default, deserialize_with = "deserialize_null_as_default")]`+/// so both shapes — missing **and** explicit-`null` — produce `T::default()`,+/// while real values deserialize normally.+pub fn deserialize_null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>+where+ D: Deserializer<'de>,+ T: Default + Deserialize<'de>,+{+ Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())+}+fn parse_bool_from_str<E: de::Error>(value: &str, empty_as_false: bool) -> Result<bool, E> {if value.is_empty() {return if empty_as_false {@@ -335,4 +358,49 @@ mod tests {let result: Result<TestOptionalStruct, _> = serde_json::from_str(json);assert!(result.is_err());}++ #[derive(Deserialize, Debug, PartialEq, Default)]+ struct TestNullableMapStruct {+ #[serde(default, deserialize_with = "deserialize_null_as_default")]+ bag: std::collections::HashMap<String, serde_json::Value>,+ }++ #[test]+ fn test_deserialize_null_as_default_with_real_object() {+ let json = r#"{"bag": {"a": 1, "b": "two"}}"#;+ let result: TestNullableMapStruct = serde_json::from_str(json).unwrap();+ assert_eq!(result.bag.len(), 2);+ assert_eq!(result.bag.get("a"), Some(&serde_json::json!(1)));+ assert_eq!(result.bag.get("b"), Some(&serde_json::json!("two")));+ }++ #[test]+ fn test_deserialize_null_as_default_with_explicit_null() {+ // The whole point of this helper: present-and-null must produce+ // the default value rather than failing. Bare #[serde(default)] alone+ // would fail here because null can't deserialize into a HashMap.+ let json = r#"{"bag": null}"#;+ let result: TestNullableMapStruct = serde_json::from_str(json).unwrap();+ assert!(result.bag.is_empty());+ }++ #[test]+ fn test_deserialize_null_as_default_with_missing_field() {+ let json = r#"{}"#;+ let result: TestNullableMapStruct = serde_json::from_str(json).unwrap();+ assert!(result.bag.is_empty());+ }++ #[test]+ fn test_deserialize_null_as_default_propagates_non_null_type_errors() {+ // Defaulting only kicks in for null; other invalid shapes still fail+ // so we don't silently swallow real schema breakage.+ let json = r#"{"bag": "not-an-object"}"#;+ let result: Result<TestNullableMapStruct, _> = serde_json::from_str(json);+ assert!(result.is_err());++ let json = r#"{"bag": [1, 2, 3]}"#;+ let result: Result<TestNullableMapStruct, _> = serde_json::from_str(json);+ assert!(result.is_err());+ }}