From ece306fd57054bb806cca3fb08d568011f31cc35 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 30 Nov 2026 00:16:55 +0000 Subject: [PATCH] Verify FixedSizeBinary FlatBuffers DType and align Serde deserializers Fixes a regression from #12192 where files containing FixedSizeBinary columns could not be opened because the DType FlatBuffers verifier rejected FixedSizeBinary as an unknown variant. Also aligns DTypeSerde variant indices, tuple/newtype deserialization, positional record decoding, and StructFields length validation with Serialize, and extends draw_dtype to generate nested FixedSizeBinary and arbitrary non-nullable map keys. Co-Authored-By: Antigravity Signed-off-by: Will Manning --- vortex-array/src/dtype/generate.rs | 30 +- vortex-array/src/dtype/serde/flatbuffers.rs | 58 -- .../src/dtype/serde/flatbuffers/verify.rs | 3 + vortex-array/src/dtype/serde/mod.rs | 515 +++++++++++++--- vortex-array/src/dtype/serde/serde.rs | 559 ++++++++++-------- 5 files changed, 748 insertions(+), 417 deletions(-) diff --git a/vortex-array/src/dtype/generate.rs b/vortex-array/src/dtype/generate.rs index a9af4e131db..71207b12874 100644 --- a/vortex-array/src/dtype/generate.rs +++ b/vortex-array/src/dtype/generate.rs @@ -36,10 +36,10 @@ pub(crate) fn draw_ptype(tc: &TestCase) -> PType { /// Draws a [`DType`] with at most `depth` levels of nested containers. /// -/// Structs and unions have one to three children. Map keys are non-nullable primitives. +/// Structs and unions have one to three children. Map keys are non-nullable child dtypes. /// Extension dtypes are not drawn, because they need a registered extension. pub(crate) fn draw_dtype(tc: &TestCase, depth: u8) -> DType { - let kinds = if depth == 0 { 7 } else { 12 }; + let kinds = if depth == 0 { 8 } else { 13 }; let nullability = Nullability::from(tc.draw(gs::booleans())); let child = || draw_dtype(tc, depth - 1); let width = || tc.draw(gs::integers::().min_value(1).max_value(3)); @@ -55,24 +55,28 @@ pub(crate) fn draw_dtype(tc: &TestCase, depth: u8) -> DType { } 4 => DType::Utf8(nullability), 5 => DType::Binary(nullability), - 6 => DType::Variant(nullability), - 7 => DType::List(Arc::new(child()), nullability), - 8 => DType::FixedSizeList( + 6 => DType::FixedSizeBinary(tc.draw(gs::integers::()), nullability), + 7 => DType::Variant(nullability), + 8 => DType::List(Arc::new(child()), nullability), + 9 => DType::FixedSizeList( Arc::new(child()), tc.draw(gs::integers::()), nullability, ), - 9 => DType::struct_( + 10 => DType::struct_( (0..width()).map(|i| (format!("f{i}"), child())), nullability, ), - 10 => DType::map( - DType::Primitive(draw_ptype(tc), Nullability::NonNullable), - child(), - tc.draw(gs::booleans()), - nullability, - ) - .vortex_expect("map keys are non-nullable"), + 11 => { + let raw_key = child(); + let key = if matches!(raw_key, DType::Null) { + DType::Bool(Nullability::NonNullable) + } else { + raw_key.as_nonnullable() + }; + DType::map(key, child(), tc.draw(gs::booleans()), nullability) + .vortex_expect("map keys are non-nullable") + } _ => { let n = width(); DType::Union( diff --git a/vortex-array/src/dtype/serde/flatbuffers.rs b/vortex-array/src/dtype/serde/flatbuffers.rs index c0299a964f1..0bee42e165f 100644 --- a/vortex-array/src/dtype/serde/flatbuffers.rs +++ b/vortex-array/src/dtype/serde/flatbuffers.rs @@ -753,8 +753,6 @@ impl TryFrom for PType { #[cfg(test)] mod test { - use std::sync::Arc; - use flatbuffers::FlatBufferBuilder; use flatbuffers::WIPOffset; use flatbuffers::root; @@ -792,62 +790,6 @@ mod test { assert_eq!(dtype, deserialized); } - #[test] - fn roundtrip() { - roundtrip_dtype(DType::Null); - roundtrip_dtype(DType::Bool(Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::U8, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::U16, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::U32, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::U64, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::I8, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::I16, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::I32, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::I64, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::F16, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::F32, Nullability::NonNullable)); - roundtrip_dtype(DType::Primitive(PType::F64, Nullability::NonNullable)); - roundtrip_dtype(DType::Binary(Nullability::NonNullable)); - roundtrip_dtype(DType::FixedSizeBinary(16, Nullability::NonNullable)); - roundtrip_dtype(DType::FixedSizeBinary(0, Nullability::Nullable)); - roundtrip_dtype(DType::Utf8(Nullability::NonNullable)); - roundtrip_dtype(DType::List( - Arc::new(DType::Primitive(PType::F32, Nullability::Nullable)), - Nullability::NonNullable, - )); - roundtrip_dtype(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::F32, Nullability::Nullable)), - 2, - Nullability::NonNullable, - )); - roundtrip_dtype(DType::Struct( - StructFields::new( - ["strings", "ints"].into(), - vec![ - DType::Utf8(Nullability::NonNullable), - DType::Primitive(PType::U16, Nullability::Nullable), - ], - ), - Nullability::NonNullable, - )); - let inner_map = DType::map( - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::Nullable), - true, - Nullability::NonNullable, - ) - .unwrap(); - let map = DType::map( - inner_map, - DType::Utf8(Nullability::Nullable), - false, - Nullability::Nullable, - ) - .unwrap(); - roundtrip_dtype(DType::struct_([("map", map)], Nullability::NonNullable)); - roundtrip_dtype(DType::Variant(Nullability::Nullable)); - } - #[test] fn equal_subtrees_are_written_once() -> VortexResult<()> { let leaf = DType::Primitive(PType::I64, Nullability::NonNullable); diff --git a/vortex-array/src/dtype/serde/flatbuffers/verify.rs b/vortex-array/src/dtype/serde/flatbuffers/verify.rs index ca271e908a3..ca8640c1717 100644 --- a/vortex-array/src/dtype/serde/flatbuffers/verify.rs +++ b/vortex-array/src/dtype/serde/flatbuffers/verify.rs @@ -65,6 +65,9 @@ impl DTypeVerifier<'_> { fb::Type::Binary => { required(dtype.type__as_binary(), "binary")?; } + fb::Type::FixedSizeBinary => { + required(dtype.type__as_fixed_size_binary(), "fixed-size binary")?; + } fb::Type::Variant => { required(dtype.type__as_variant(), "variant")?; } diff --git a/vortex-array/src/dtype/serde/mod.rs b/vortex-array/src/dtype/serde/mod.rs index ffd5f336bd0..5a971a027e3 100644 --- a/vortex-array/src/dtype/serde/mod.rs +++ b/vortex-array/src/dtype/serde/mod.rs @@ -15,23 +15,170 @@ mod serde; pub use serde::*; #[cfg(test)] -#[cfg(feature = "serde")] -mod test { - use std::io; +mod coherence_tests { + use hegel::TestCase; + use hegel::generators as gs; + #[cfg(feature = "serde")] + use serde::de::DeserializeSeed; + use vortex_error::VortexExpect; + + use crate::dtype::DType; + use crate::dtype::Nullability; + use crate::dtype::generate::draw_dtype; + use crate::dtype::proto::dtype as pb; + #[cfg(feature = "serde")] + use crate::dtype::serde::DTypeSerde; + use crate::dtype::test::SESSION; + use crate::extension::datetime::Date; + use crate::extension::datetime::Duration; + use crate::extension::datetime::Time; + use crate::extension::datetime::TimeUnit; + use crate::extension::datetime::Timestamp; + use crate::flatbuffers::FlatBuffer; + use crate::flatbuffers::WriteFlatBufferExt; + + fn draw_extended_dtype(tc: &TestCase) -> DType { + const UNITS: [TimeUnit; 4] = [ + TimeUnit::Nanoseconds, + TimeUnit::Microseconds, + TimeUnit::Milliseconds, + TimeUnit::Seconds, + ]; + let nullability = Nullability::from(tc.draw(gs::booleans())); + match tc.draw(gs::integers::().max_value(7)) { + 0 => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + DType::Extension(Duration::new(unit, nullability).erased()) + } + 1 => { + let unit = if tc.draw(gs::booleans()) { + TimeUnit::Days + } else { + TimeUnit::Milliseconds + }; + DType::Extension(Date::new(unit, nullability).erased()) + } + 2 => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + let tz = tc.draw(gs::booleans()).then(|| "UTC".into()); + DType::Extension(Timestamp::new_with_tz(unit, tz, nullability).erased()) + } + 3 => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + DType::Extension(Time::new(unit, nullability).erased()) + } + _ => draw_dtype(tc, 2), + } + } + + fn assert_roundtrip_coherence(dtype: &DType) { + let fb_bytes = dtype + .write_flatbuffer_bytes() + .vortex_expect("serialize DType to FlatBuffers"); + let from_fb = DType::from_flatbuffer(FlatBuffer::from(fb_bytes), &SESSION) + .vortex_expect("deserialize DType from FlatBuffers"); + + let pb_dtype = pb::DType::try_from(dtype).vortex_expect("serialize DType to Proto"); + let from_pb = + DType::from_proto(&pb_dtype, &SESSION).vortex_expect("deserialize DType from Proto"); + + assert_eq!(&from_fb, dtype); + assert_eq!(&from_pb, dtype); + + #[cfg(feature = "serde")] + { + let json = serde_json::to_string(dtype).expect("serialize DType to JSON"); + let mut deserializer = serde_json::Deserializer::from_str(&json); + let from_json = DTypeSerde::::new(&SESSION) + .deserialize(&mut deserializer) + .expect("deserialize DType from JSON"); + assert_eq!(&from_json, dtype); + } + } + + /// Every generated DType must roundtrip identically across FlatBuffers, Proto, and JSON. + #[hegel::test(test_cases = 200)] + fn dtype_serde_roundtrip_coherence(tc: TestCase) { + let dtype = draw_extended_dtype(&tc); + assert_roundtrip_coherence(&dtype); + } + + #[test] + fn test_dtype_serde_roundtrip_corner_cases() { + assert_roundtrip_coherence(&DType::FixedSizeBinary(0, Nullability::Nullable)); + + let inner_map = DType::map( + DType::Utf8(Nullability::NonNullable), + DType::Utf8(Nullability::Nullable), + true, + Nullability::NonNullable, + ) + .vortex_expect("non-nullable map key"); + let nested_map = DType::map( + inner_map, + DType::Utf8(Nullability::Nullable), + false, + Nullability::Nullable, + ) + .vortex_expect("non-nullable map key"); + assert_roundtrip_coherence(&nested_map); + } +} +#[cfg(test)] +#[cfg(feature = "serde")] +mod tests { use rstest::rstest; + use serde::Deserialize; + use serde::Deserializer; + use serde::Serialize; + use serde::Serializer; use serde::de::DeserializeSeed; + use serde::de::IntoDeserializer; use serde_test::Token; + use serde_test::assert_de_tokens; use serde_test::assert_tokens; use vortex_error::VortexResult; + use vortex_session::VortexSession; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; + use crate::dtype::StructFields; use crate::dtype::UnionVariants; + use crate::dtype::extension::ExtDTypeRef; + use crate::dtype::extension::ExtId; + use crate::dtype::extension::ForeignExtDType; use crate::dtype::serde::DTypeSerde; use crate::dtype::test::SESSION; + use crate::extension::datetime::Duration; + use crate::extension::datetime::TimeUnit; + + #[derive(Debug, PartialEq)] + struct SessionDType(DType); + + impl Serialize for SessionDType { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } + } + + impl<'de> Deserialize<'de> for SessionDType { + fn deserialize>(deserializer: D) -> Result { + DTypeSerde::::new(&SESSION) + .deserialize(deserializer) + .map(Self) + } + } + + fn roundtrip_json(dtype: &DType, session: &VortexSession) -> DType { + let json = serde_json::to_string(dtype).expect("serialize DType to JSON"); + let mut deserializer = serde_json::Deserializer::from_str(&json); + DTypeSerde::::new(session) + .deserialize(&mut deserializer) + .expect("deserialize DType from JSON") + } #[test] fn test_serde_decimal_roundtrip() { @@ -86,12 +233,9 @@ mod test { } #[test] - fn test_serde_dtype() { - // Test that DType serializes correctly (we only test serialization since - // deserialization with serde_test has borrowing issues with enum variants) - use serde_test::assert_ser_tokens; - assert_ser_tokens( - &DType::from(PType::U8), + fn test_serde_dtype_tokens_roundtrip() { + assert_tokens( + &SessionDType(DType::from(PType::U8)), &[ Token::TupleVariant { name: "DType", @@ -106,14 +250,9 @@ mod test { Token::TupleVariantEnd, ], ); - } - #[test] - fn test_serde_variant_dtype() { - use serde_test::assert_ser_tokens; - - assert_ser_tokens( - &DType::Variant(Nullability::NonNullable), + assert_tokens( + &SessionDType(DType::Variant(Nullability::NonNullable)), &[ Token::NewtypeVariant { name: "DType", @@ -122,6 +261,232 @@ mod test { Token::Bool(false), ], ); + + // Verify variant indices match `Serialize` order: Extension = 9, Variant = 10, Union = 11. + let ext = + DType::Extension(Duration::new(TimeUnit::Seconds, Nullability::Nullable).erased()); + assert_tokens( + &SessionDType(ext.clone()), + &[ + Token::NewtypeVariant { + name: "DType", + variant: "Extension", + }, + Token::Struct { + name: "ExtDType", + len: 3, + }, + Token::Str("id"), + Token::Str("vortex.duration"), + Token::Str("storage_dtype"), + Token::TupleVariant { + name: "DType", + variant: "Primitive", + len: 2, + }, + Token::UnitVariant { + name: "PType", + variant: "i64", + }, + Token::Bool(true), + Token::TupleVariantEnd, + Token::Str("metadata"), + Token::Seq { len: Some(1) }, + Token::U8(u8::from(TimeUnit::Seconds)), + Token::SeqEnd, + Token::StructEnd, + ], + ); + // Deserialize Extension (9), Variant (10), and Union (11) by numeric variant index. + assert_de_tokens( + &SessionDType(ext), + &[ + Token::Enum { name: "DType" }, + Token::U64(9), + Token::Struct { + name: "ExtDType", + len: 3, + }, + Token::Str("id"), + Token::Str("vortex.duration"), + Token::Str("storage_dtype"), + Token::TupleVariant { + name: "DType", + variant: "Primitive", + len: 2, + }, + Token::UnitVariant { + name: "PType", + variant: "i64", + }, + Token::Bool(true), + Token::TupleVariantEnd, + Token::Str("metadata"), + Token::Seq { len: Some(1) }, + Token::U8(u8::from(TimeUnit::Seconds)), + Token::SeqEnd, + Token::StructEnd, + ], + ); + + assert_de_tokens( + &SessionDType(DType::Variant(Nullability::Nullable)), + &[ + Token::Enum { name: "DType" }, + Token::U64(10), + Token::Bool(true), + ], + ); + + assert_tokens( + &SessionDType(DType::FixedSizeBinary(16, Nullability::Nullable)), + &[ + Token::TupleVariant { + name: "DType", + variant: "FixedSizeBinary", + len: 2, + }, + Token::U32(16), + Token::Bool(true), + Token::TupleVariantEnd, + ], + ); + + let map_dtype = DType::map( + DType::Utf8(Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::Nullable), + true, + Nullability::Nullable, + ) + .unwrap(); + assert_tokens( + &SessionDType(map_dtype), + &[ + Token::TupleVariant { + name: "DType", + variant: "Map", + len: 4, + }, + Token::NewtypeVariant { + name: "DType", + variant: "Utf8", + }, + Token::Bool(false), + Token::TupleVariant { + name: "DType", + variant: "Primitive", + len: 2, + }, + Token::UnitVariant { + name: "PType", + variant: "i32", + }, + Token::Bool(true), + Token::TupleVariantEnd, + Token::Bool(true), + Token::Bool(true), + Token::TupleVariantEnd, + ], + ); + + let union_dtype = DType::Union( + UnionVariants::new(["value"].into(), vec![DType::Utf8(Nullability::Nullable)]).unwrap(), + Nullability::Nullable, + ); + assert_de_tokens( + &SessionDType(union_dtype), + &[ + Token::Enum { name: "DType" }, + Token::U64(11), + Token::Tuple { len: 2 }, + Token::Struct { + name: "UnionVariants", + len: 3, + }, + Token::Str("names"), + Token::NewtypeStruct { name: "FieldNames" }, + Token::Seq { len: Some(1) }, + Token::Str("value"), + Token::SeqEnd, + Token::Str("dtypes"), + Token::Seq { len: Some(1) }, + Token::NewtypeVariant { + name: "DType", + variant: "Utf8", + }, + Token::Bool(true), + Token::SeqEnd, + Token::Str("type_ids"), + Token::Seq { len: Some(1) }, + Token::U8(0), + Token::SeqEnd, + Token::StructEnd, + Token::Bool(true), + Token::TupleEnd, + ], + ); + } + + #[test] + fn test_serde_union_dtype_json_roundtrip() { + let dtype = DType::Union( + UnionVariants::new(["value"].into(), vec![DType::Utf8(Nullability::Nullable)]).unwrap(), + Nullability::Nullable, + ); + + let json = serde_json::to_string(&dtype).unwrap(); + assert_eq!( + json, + r#"{"Union":[{"names":["value"],"dtypes":[{"Utf8":true}],"type_ids":[0]},true]}"# + ); + let mut deserializer = serde_json::Deserializer::from_str(&json); + let deserialized: DType = DTypeSerde::::new(&SESSION) + .deserialize(&mut deserializer) + .unwrap(); + + assert_eq!(deserialized, dtype); + assert_eq!(deserialized.nullability(), Nullability::Nullable); + } + + #[test] + fn test_serde_ext_dtype_ref_roundtrip() -> VortexResult<()> { + let registered: ExtDTypeRef = + Duration::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); + let json = serde_json::to_string(®istered).map_err(std::io::Error::from)?; + let mut de = serde_json::Deserializer::from_str(&json); + let restored = DTypeSerde::::new(&SESSION) + .deserialize(&mut de) + .map_err(std::io::Error::from)?; + assert_eq!(restored, registered); + + #[expect(clippy::disallowed_methods, reason = "test-only extension id")] + let foreign = ForeignExtDType::from_parts( + ExtId::new("test.foreign"), + vec![1, 2, 3], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let foreign_dtype = DType::Extension(foreign.clone()); + + let strict_json = serde_json::to_string(&foreign_dtype).map_err(std::io::Error::from)?; + let mut strict_de = serde_json::Deserializer::from_str(&strict_json); + assert!( + DTypeSerde::::new(&SESSION) + .deserialize(&mut strict_de) + .is_err() + ); + + let permissive = VortexSession::empty(); + permissive.allow_unknown(); + assert_eq!(roundtrip_json(&foreign_dtype, &permissive), foreign_dtype); + let foreign_json = serde_json::to_string(&foreign).map_err(std::io::Error::from)?; + let mut foreign_de = serde_json::Deserializer::from_str(&foreign_json); + assert_eq!( + DTypeSerde::::new(&permissive) + .deserialize(&mut foreign_de) + .map_err(std::io::Error::from)?, + foreign + ); + Ok(()) } #[test] @@ -131,8 +496,6 @@ mod test { #[test] fn test_serde_struct_dtype_json() { - use crate::dtype::StructFields; - // Create a struct dtype with various field types let fields = StructFields::from_iter([ ("name", DType::Utf8(Nullability::NonNullable)), @@ -184,10 +547,6 @@ mod test { #[test] fn test_serde_struct_fields_from_json_value() { - use serde::de::IntoDeserializer; - - use crate::dtype::StructFields; - let fields = StructFields::from_iter([ ("name", DType::Utf8(Nullability::NonNullable)), ("age", DType::Primitive(PType::I32, Nullability::Nullable)), @@ -210,81 +569,57 @@ mod test { } #[test] - fn test_serde_variant_dtype_json_roundtrip() { - let json = serde_json::to_string(&DType::Variant(Nullability::Nullable)).unwrap(); - assert_eq!(json, "{\"Variant\":true}"); - - let mut deserializer = serde_json::Deserializer::from_str(&json); - let deserialized: DType = DTypeSerde::::new(&SESSION) - .deserialize(&mut deserializer) + fn test_serde_positional_records() { + let mut de = + serde_json::Deserializer::from_str(r#"{"Struct":[[["name"],[{"Utf8":false}]],true]}"#); + let decoded = DTypeSerde::::new(&SESSION) + .deserialize(&mut de) .unwrap(); - assert_eq!(DType::Variant(Nullability::Nullable), deserialized); - } - - #[rstest] - #[case(16, Nullability::NonNullable)] - #[case(0, Nullability::Nullable)] - fn test_serde_fixed_size_binary_dtype_json_roundtrip( - #[case] size: u32, - #[case] nullability: Nullability, - ) -> VortexResult<()> { - let dtype = DType::FixedSizeBinary(size, nullability); - - let json = serde_json::to_string(&dtype).map_err(io::Error::from)?; - let mut deserializer = serde_json::Deserializer::from_str(&json); - let deserialized: DType = DTypeSerde::::new(&SESSION) - .deserialize(&mut deserializer) - .map_err(io::Error::from)?; - - assert_eq!(deserialized, dtype); - Ok(()) - } - - #[test] - fn test_serde_union_dtype_json_roundtrip() { - let dtype = DType::Union( - UnionVariants::new(["value"].into(), vec![DType::Utf8(Nullability::Nullable)]).unwrap(), - Nullability::Nullable, + assert_eq!( + decoded, + DType::struct_( + [("name", DType::Utf8(Nullability::NonNullable))], + Nullability::Nullable, + ) ); - let json = serde_json::to_string(&dtype).unwrap(); - assert_eq!( - json, - r#"{"Union":[{"names":["value"],"dtypes":[{"Utf8":true}],"type_ids":[0]},true]}"# + let mut de = serde_json::Deserializer::from_str( + r#"{"Union":[[["value"],[{"Utf8":true}],[0]],true]}"#, ); - let mut deserializer = serde_json::Deserializer::from_str(&json); - let deserialized: DType = DTypeSerde::::new(&SESSION) - .deserialize(&mut deserializer) + let decoded = DTypeSerde::::new(&SESSION) + .deserialize(&mut de) .unwrap(); + assert_eq!( + decoded, + DType::Union( + UnionVariants::new(["value"].into(), vec![DType::Utf8(Nullability::Nullable)]) + .unwrap(), + Nullability::Nullable, + ) + ); - assert_eq!(deserialized, dtype); - assert_eq!(deserialized.nullability(), Nullability::Nullable); - } - - #[test] - fn test_serde_nested_map_dtype_json_roundtrip() { - let inner_map = DType::map( - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::Nullable), - true, - Nullability::NonNullable, - ) - .unwrap(); - let map = DType::map( - inner_map, - DType::Utf8(Nullability::Nullable), - false, - Nullability::Nullable, - ) - .unwrap(); - let dtype = DType::struct_([("map", map)], Nullability::Nullable); - - let json = serde_json::to_string(&dtype).unwrap(); - let mut deserializer = serde_json::Deserializer::from_str(&json); - let deserialized: DType = DTypeSerde::::new(&SESSION) - .deserialize(&mut deserializer) + let ext_json = format!( + r#"{{"Extension":["vortex.duration",{{"Primitive":["i64",true]}},[{}]]}}"#, + u8::from(TimeUnit::Seconds), + ); + let mut de = serde_json::Deserializer::from_str(&ext_json); + let decoded = DTypeSerde::::new(&SESSION) + .deserialize(&mut de) .unwrap(); + assert_eq!( + decoded, + DType::Extension(Duration::new(TimeUnit::Seconds, Nullability::Nullable).erased()) + ); + } - assert_eq!(deserialized, dtype); + #[rstest] + #[case::positional(r#"{"Struct":[[["name"],[]],false]}"#)] + #[case::map(r#"{"Struct":[{"names":["name"],"dtypes":[]},false]}"#)] + fn test_serde_struct_fields_rejects_mismatched_lengths(#[case] json: &str) { + let mut de = serde_json::Deserializer::from_str(json); + let err = DTypeSerde::::new(&SESSION) + .deserialize(&mut de) + .unwrap_err(); + assert!(err.to_string().contains("does not match"), "{err}"); } } diff --git a/vortex-array/src/dtype/serde/serde.rs b/vortex-array/src/dtype/serde/serde.rs index 240b7b0edf4..60e0e469c88 100644 --- a/vortex-array/src/dtype/serde/serde.rs +++ b/vortex-array/src/dtype/serde/serde.rs @@ -25,7 +25,6 @@ use vortex_session::VortexSession; use crate::dtype::DType; use crate::dtype::FieldNames; use crate::dtype::Nullability; -use crate::dtype::PType; use crate::dtype::StructFields; use crate::dtype::UnionVariants; use crate::dtype::decimal::DecimalDType; @@ -207,13 +206,32 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, DType> { "List", "FixedSizeList", "Struct", - "Union", - "Variant", "Extension", + "Variant", + "Union", "Map", "FixedSizeBinary", ]; + #[derive(Deserialize)] + #[serde(variant_identifier)] + enum DTypeVariant { + Null, + Bool, + Primitive, + Decimal, + Utf8, + Binary, + List, + FixedSizeList, + Struct, + Extension, + Variant, + Union, + Map, + FixedSizeBinary, + } + struct DTypeVisitor<'a> { session: &'a VortexSession, } @@ -229,67 +247,81 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, DType> { where A: EnumAccess<'de>, { - let (variant, access) = data.variant::>()?; - match variant.as_ref() { - "Null" => { + let (variant, access) = data.variant::()?; + match variant { + DTypeVariant::Null => { access.unit_variant()?; Ok(DType::Null) } - "Bool" => { + DTypeVariant::Bool => { let n = access.newtype_variant()?; Ok(DType::Bool(n)) } - "Primitive" => { - #[derive(Deserialize)] - struct Fields(PType, Nullability); - let Fields(ptype, n) = access.newtype_variant()?; - Ok(DType::Primitive(ptype, n)) - } - "Decimal" => { - #[derive(Deserialize)] - struct Fields(DecimalDType, Nullability); - let Fields(decimal, n) = access.newtype_variant()?; - Ok(DType::Decimal(decimal, n)) - } - "Utf8" => { + DTypeVariant::Primitive => access.tuple_variant( + 2, + Tuple2Visitor::new( + DType::Primitive, + "Primitive tuple (ptype, nullability)", + ), + ), + DTypeVariant::Decimal => access.tuple_variant( + 2, + Tuple2Visitor::new(DType::Decimal, "Decimal tuple (decimal, nullability)"), + ), + DTypeVariant::Utf8 => { let n = access.newtype_variant()?; Ok(DType::Utf8(n)) } - "Binary" => { + DTypeVariant::Binary => { let n = access.newtype_variant()?; Ok(DType::Binary(n)) } - "FixedSizeBinary" => { - #[derive(Deserialize)] - struct Fields(u32, Nullability); - let Fields(size, n) = access.newtype_variant()?; - Ok(DType::FixedSizeBinary(size, n)) - } - "List" => access.newtype_variant_seed(ListFieldsSeed { - session: self.session, - }), - "FixedSizeList" => access.newtype_variant_seed(FixedSizeListFieldsSeed { - session: self.session, - }), - "Map" => access.newtype_variant_seed(MapFieldsSeed { - session: self.session, - }), - "Struct" => access.newtype_variant_seed(StructFieldsSeed { - session: self.session, - }), - "Union" => access.newtype_variant_seed(UnionFieldsSeed { - session: self.session, - }), - "Variant" => { + DTypeVariant::FixedSizeBinary => access.tuple_variant( + 2, + Tuple2Visitor::new( + DType::FixedSizeBinary, + "FixedSizeBinary tuple (size, nullability)", + ), + ), + DTypeVariant::List => access.tuple_variant( + 2, + ListVisitor { + session: self.session, + }, + ), + DTypeVariant::FixedSizeList => access.tuple_variant( + 3, + FixedSizeListVisitor { + session: self.session, + }, + ), + DTypeVariant::Map => access.tuple_variant( + 4, + MapVisitor { + session: self.session, + }, + ), + DTypeVariant::Struct => access.tuple_variant( + 2, + StructVisitor { + session: self.session, + }, + ), + DTypeVariant::Union => access.tuple_variant( + 2, + UnionVisitor { + session: self.session, + }, + ), + DTypeVariant::Variant => { let n = access.newtype_variant()?; Ok(DType::Variant(n)) } - "Extension" => { + DTypeVariant::Extension => { let ext = access .newtype_variant_seed(DTypeSerde::::new(self.session))?; Ok(DType::Extension(ext)) } - _ => Err(de::Error::unknown_variant(&variant, VARIANTS)), } } } @@ -304,247 +336,189 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, DType> { } } -struct MapFieldsSeed<'a> { - session: &'a VortexSession, +struct Tuple2Visitor { + build: F, + expected: &'static str, + _marker: PhantomData<(A, B)>, } -impl<'de> DeserializeSeed<'de> for MapFieldsSeed<'_> { +impl Tuple2Visitor { + fn new(build: F, expected: &'static str) -> Self { + Self { + build, + expected, + _marker: PhantomData, + } + } +} + +impl<'de, A, B, F> Visitor<'de> for Tuple2Visitor +where + A: Deserialize<'de>, + B: Deserialize<'de>, + F: FnOnce(A, B) -> DType, +{ type Value = DType; - fn deserialize(self, deserializer: D) -> Result + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str(self.expected) + } + + fn visit_seq(self, mut seq: S) -> Result where - D: Deserializer<'de>, + S: SeqAccess<'de>, { - struct MapVisitor<'a> { - session: &'a VortexSession, - } - - impl<'de> Visitor<'de> for MapVisitor<'_> { - type Value = DType; + let first = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let second = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + Ok((self.build)(first, second)) + } +} - fn expecting(&self, f: &mut Formatter) -> fmt::Result { - f.write_str("Map tuple (key_dtype, value_dtype, keys_sorted, nullability)") - } +struct MapVisitor<'a> { + session: &'a VortexSession, +} - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let key = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(0, &self))?; - let value = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(1, &self))?; - let keys_sorted = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(2, &self))?; - let nullability = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(3, &self))?; +impl<'de> Visitor<'de> for MapVisitor<'_> { + type Value = DType; - DType::map(key, value, keys_sorted, nullability) - .map_err(|error| de::Error::custom(error.to_string())) - } - } + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str("Map tuple (key_dtype, value_dtype, keys_sorted, nullability)") + } - deserializer.deserialize_tuple( - 4, - MapVisitor { - session: self.session, - }, - ) + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let key = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let value = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + let keys_sorted = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(2, &self))?; + let nullability = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(3, &self))?; + + DType::map(key, value, keys_sorted, nullability) + .map_err(|error| de::Error::custom(error.to_string())) } } // ============================================================================ -// Helper seeds for nested DType variants (with session) +// Helper visitors for nested DType variants (with session) // ============================================================================ -struct ListFieldsSeed<'a> { +struct ListVisitor<'a> { session: &'a VortexSession, } -impl<'de> DeserializeSeed<'de> for ListFieldsSeed<'_> { +impl<'de> Visitor<'de> for ListVisitor<'_> { type Value = DType; - fn deserialize(self, deserializer: D) -> Result + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str("List tuple (element_dtype, nullability)") + } + + fn visit_seq(self, mut seq: A) -> Result where - D: Deserializer<'de>, + A: SeqAccess<'de>, { - struct ListVisitor<'a> { - session: &'a VortexSession, - } - - impl<'de> Visitor<'de> for ListVisitor<'_> { - type Value = DType; - - fn expecting(&self, f: &mut Formatter) -> fmt::Result { - f.write_str("List tuple (element_dtype, nullability)") - } - - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let element_dtype = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(0, &self))?; - let nullability = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(1, &self))?; - Ok(DType::List(Arc::new(element_dtype), nullability)) - } - } - - deserializer.deserialize_tuple( - 2, - ListVisitor { - session: self.session, - }, - ) + let element_dtype = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let nullability = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + Ok(DType::List(Arc::new(element_dtype), nullability)) } } -struct FixedSizeListFieldsSeed<'a> { +struct FixedSizeListVisitor<'a> { session: &'a VortexSession, } -impl<'de> DeserializeSeed<'de> for FixedSizeListFieldsSeed<'_> { +impl<'de> Visitor<'de> for FixedSizeListVisitor<'_> { type Value = DType; - fn deserialize(self, deserializer: D) -> Result + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str("FixedSizeList tuple (element_dtype, size, nullability)") + } + + fn visit_seq(self, mut seq: A) -> Result where - D: Deserializer<'de>, + A: SeqAccess<'de>, { - struct FixedSizeListVisitor<'a> { - session: &'a VortexSession, - } - - impl<'de> Visitor<'de> for FixedSizeListVisitor<'_> { - type Value = DType; - - fn expecting(&self, f: &mut Formatter) -> fmt::Result { - f.write_str("FixedSizeList tuple (element_dtype, size, nullability)") - } - - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let element_dtype = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(0, &self))?; - let size = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(1, &self))?; - let nullability = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(2, &self))?; - Ok(DType::FixedSizeList( - Arc::new(element_dtype), - size, - nullability, - )) - } - } - - deserializer.deserialize_tuple( - 3, - FixedSizeListVisitor { - session: self.session, - }, - ) + let element_dtype = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let size = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + let nullability = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(2, &self))?; + Ok(DType::FixedSizeList( + Arc::new(element_dtype), + size, + nullability, + )) } } -struct StructFieldsSeed<'a> { +struct StructVisitor<'a> { session: &'a VortexSession, } -impl<'de> DeserializeSeed<'de> for StructFieldsSeed<'_> { +impl<'de> Visitor<'de> for StructVisitor<'_> { type Value = DType; - fn deserialize(self, deserializer: D) -> Result + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str("Struct tuple (fields, nullability)") + } + + fn visit_seq(self, mut seq: A) -> Result where - D: Deserializer<'de>, + A: SeqAccess<'de>, { - struct StructVisitor<'a> { - session: &'a VortexSession, - } - - impl<'de> Visitor<'de> for StructVisitor<'_> { - type Value = DType; - - fn expecting(&self, f: &mut Formatter) -> fmt::Result { - f.write_str("Struct tuple (fields, nullability)") - } - - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let fields = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(0, &self))?; - let nullability = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(1, &self))?; - Ok(DType::Struct(fields, nullability)) - } - } - - deserializer.deserialize_tuple( - 2, - StructVisitor { - session: self.session, - }, - ) + let fields = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let nullability = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + Ok(DType::Struct(fields, nullability)) } } -struct UnionFieldsSeed<'a> { +struct UnionVisitor<'a> { session: &'a VortexSession, } -impl<'de> DeserializeSeed<'de> for UnionFieldsSeed<'_> { +impl<'de> Visitor<'de> for UnionVisitor<'_> { type Value = DType; - fn deserialize(self, deserializer: D) -> Result + fn expecting(&self, f: &mut Formatter) -> fmt::Result { + f.write_str("Union tuple (variants, nullability)") + } + + fn visit_seq(self, mut seq: A) -> Result where - D: Deserializer<'de>, + A: SeqAccess<'de>, { - struct UnionVisitor<'a> { - session: &'a VortexSession, - } - - impl<'de> Visitor<'de> for UnionVisitor<'_> { - type Value = DType; - - fn expecting(&self, f: &mut Formatter) -> fmt::Result { - f.write_str("Union tuple (variants, nullability)") - } - - fn visit_seq(self, mut seq: A) -> Result - where - A: SeqAccess<'de>, - { - let variants = seq - .next_element_seed(DTypeSerde::::new(self.session))? - .ok_or_else(|| de::Error::invalid_length(0, &self))?; - let nullability = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(1, &self))?; - Ok(DType::Union(variants, nullability)) - } - } - - deserializer.deserialize_tuple( - 2, - UnionVisitor { - session: self.session, - }, - ) + let variants = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let nullability = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + Ok(DType::Union(variants, nullability)) } } @@ -568,6 +542,24 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, UnionVariants> { f.write_str("struct UnionVariants") } + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let names: FieldNames = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let dtypes = seq + .next_element_seed(DTypeSerde::>::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + let type_ids: Vec = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(2, &self))?; + + UnionVariants::try_new(names, dtypes, type_ids) + .map_err(|e| de::Error::custom(e.to_string())) + } + fn visit_map(self, mut map: V) -> Result where V: MapAccess<'de>, @@ -632,6 +624,20 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, StructFields> { { const FIELDS: &[&str] = &["names", "dtypes"]; + fn build_struct_fields( + names: FieldNames, + dtypes: Vec, + ) -> Result { + if names.len() != dtypes.len() { + return Err(de::Error::custom(format!( + "StructFields names length ({}) does not match dtypes length ({})", + names.len(), + dtypes.len() + ))); + } + Ok(StructFields::new(names, dtypes)) + } + struct StructFieldsInnerVisitor<'a> { session: &'a VortexSession, } @@ -643,6 +649,20 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, StructFields> { f.write_str("struct StructFields") } + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let names: FieldNames = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let dtypes = seq + .next_element_seed(DTypeSerde::>::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + + build_struct_fields(names, dtypes) + } + fn visit_map(self, mut map: V) -> Result where V: MapAccess<'de>, @@ -675,7 +695,7 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, StructFields> { let names = names.ok_or_else(|| de::Error::missing_field("names"))?; let dtypes = dtypes.ok_or_else(|| de::Error::missing_field("dtypes"))?; - Ok(StructFields::new(names, dtypes)) + build_struct_fields(names, dtypes) } } @@ -773,6 +793,23 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, ExtDTypeRef> { f.write_str("struct ExtDType") } + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let id: Arc = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let storage_dtype = seq + .next_element_seed(DTypeSerde::::new(self.session))? + .ok_or_else(|| de::Error::invalid_length(1, &self))?; + let metadata: Vec = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(2, &self))?; + + deserialize_ext_dtype(self.session, &id, storage_dtype, metadata) + } + fn visit_map(self, mut map: V) -> Result where V: MapAccess<'de>, @@ -809,32 +846,42 @@ impl<'de> DeserializeSeed<'de> for DTypeSerde<'_, ExtDTypeRef> { } let id = id.ok_or_else(|| de::Error::missing_field("id"))?; - #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")] - let id = ExtId::new(&id); let storage_dtype = storage_dtype.ok_or_else(|| de::Error::missing_field("storage_dtype"))?; let metadata = metadata.ok_or_else(|| de::Error::missing_field("metadata"))?; - if let Some(vtable) = self.session.dtypes().registry().get(&id) { - vtable.deserialize(&metadata, storage_dtype).map_err(|e| { - de::Error::custom(format!( - "failed to deserialize extension dtype {}: {}", - id, e - )) - }) - } else if self.session.allows_unknown() { - ForeignExtDType::from_parts(id, metadata, storage_dtype).map_err(|e| { - de::Error::custom(format!( - "failed to deserialize unknown extension dtype: {}", - e - )) - }) - } else { - Err(de::Error::custom(format!( - "unknown extension dtype id: {}", - id - ))) - } + deserialize_ext_dtype(self.session, &id, storage_dtype, metadata) + } + } + + fn deserialize_ext_dtype( + session: &VortexSession, + id: &str, + storage_dtype: DType, + metadata: Vec, + ) -> Result { + #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")] + let id = ExtId::new(id); + + if let Some(vtable) = session.dtypes().registry().get(&id) { + vtable.deserialize(&metadata, storage_dtype).map_err(|e| { + de::Error::custom(format!( + "failed to deserialize extension dtype {}: {}", + id, e + )) + }) + } else if session.allows_unknown() { + ForeignExtDType::from_parts(id, metadata, storage_dtype).map_err(|e| { + de::Error::custom(format!( + "failed to deserialize unknown extension dtype: {}", + e + )) + }) + } else { + Err(de::Error::custom(format!( + "unknown extension dtype id: {}", + id + ))) } }