From 21afe10929c9dae64f0c8c29602a1f449b91ae50 Mon Sep 17 00:00:00 2001 From: connor Date: Tue, 1 Dec 2026 22:41:46 +0000 Subject: [PATCH] Consolidate timezone and temporal dtype serde property tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Signed-off-by: connor Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../vortex-temporal/src/convert_time_zone.rs | 97 +++++++---- .../vortex-temporal/src/datetime/mod.rs | 3 + .../vortex-temporal/src/datetime/tests.rs | 102 ++++++++++++ .../vortex-temporal/src/replace_time_zone.rs | 152 +++++++++++++----- .../vortex-temporal/src/tests/common.rs | 18 +++ 5 files changed, 306 insertions(+), 66 deletions(-) create mode 100644 vortex-extensions/vortex-temporal/src/datetime/tests.rs diff --git a/vortex-extensions/vortex-temporal/src/convert_time_zone.rs b/vortex-extensions/vortex-temporal/src/convert_time_zone.rs index 2ec51f68b41..659d8d31421 100644 --- a/vortex-extensions/vortex-temporal/src/convert_time_zone.rs +++ b/vortex-extensions/vortex-temporal/src/convert_time_zone.rs @@ -150,8 +150,8 @@ impl ScalarFnVTable for ConvertTimeZone { #[cfg(test)] mod tests { - use std::sync::LazyLock; - + use hegel::TestCase; + use hegel::generators as gs; use rstest::rstest; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -168,12 +168,12 @@ mod tests { use vortex_array::test_harness::ExpectedOutcome; use vortex_array::test_harness::assert_execution_paths; use vortex_buffer::buffer; + use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_expr::ArrayExprExt; use vortex_expr::Expression; use vortex_expr::proto::ExprSerializeProtoExt; use vortex_expr::root; - use vortex_session::VortexSession; use super::ConvertTimeZone; use super::ConvertTimeZoneOptions; @@ -181,13 +181,8 @@ mod tests { use crate::datetime::TimeUnit; use crate::datetime::Timestamp; use crate::expr::convert_time_zone; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - vortex_array::initialize(&session); - crate::initialize(&session); - session - }); + use crate::tests::common::SESSION; + use crate::tests::common::timestamp_array; fn zoned(zone: &str, nullability: Nullability) -> ExtDTypeRef { Timestamp::new_with_tz(TimeUnit::Seconds, Some(zone.into()), nullability).erased() @@ -217,7 +212,7 @@ mod tests { false )] #[case::no_args(vec![], "UTC", false)] - fn supports_zoned_timestamps( + fn test_convert_time_zone_supports_zoned_timestamps( #[case] args: Vec, #[case] time_zone: &str, #[case] supported: bool, @@ -233,30 +228,76 @@ mod tests { ); } - #[test] - fn test_convert_time_zone_keeps_instants() -> VortexResult<()> { - let input = ExtensionArray::try_new( - zoned("America/New_York", Nullability::Nullable), - PrimitiveArray::from_option_iter([Some(0i64), None, Some(1_710_054_000)]).into_array(), + fn check_convert_time_zone_roundtrip(tc: &TestCase) -> VortexResult<()> { + const ZONES: [&str; 3] = ["UTC", "America/New_York", "Asia/Tokyo"]; + const UNITS: [TimeUnit; 4] = [ + TimeUnit::Nanoseconds, + TimeUnit::Microseconds, + TimeUnit::Milliseconds, + TimeUnit::Seconds, + ]; + + let source_index = tc.draw(gs::integers::().max_value(ZONES.len() - 1)); + let target_offset = tc.draw(gs::integers::().max_value(ZONES.len() - 2)) + 1; + let target_index = (source_index + target_offset) % ZONES.len(); + let source_zone = ZONES[source_index]; + let target_zone = ZONES[target_index]; + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + let len = tc.draw(gs::integers::().max_value(4)); + let nullable = tc.draw(gs::booleans()); + let has_nulls = nullable && tc.draw(gs::booleans()); + let nullability = if nullable { + Nullability::Nullable + } else { + Nullability::NonNullable + }; + let mut counts = Vec::with_capacity(len); + for _ in 0..len { + if has_nulls && tc.draw(gs::booleans()) { + counts.push(None); + } else { + counts.push(Some(tc.draw(gs::integers::()))); + } + } + if has_nulls && !counts.is_empty() && !counts.iter().any(Option::is_none) { + *counts.last_mut().expect("nonempty generated array") = None; + } + + let input = timestamp_array(source_zone, unit, &counts, nullability)?; + let expected_target = timestamp_array(target_zone, unit, &counts, nullability)?; + let expected_source = timestamp_array(source_zone, unit, &counts, nullability)?; + let to_target = Expression::from_proto( + &convert_time_zone(root(), target_zone).serialize_proto()?, + &SESSION, )?; - let expected = ExtensionArray::try_new( - zoned("UTC", Nullability::Nullable), - PrimitiveArray::from_option_iter([Some(0i64), None, Some(1_710_054_000)]).into_array(), + let to_source = Expression::from_proto( + &convert_time_zone(root(), source_zone).serialize_proto()?, + &SESSION, )?; - let session = VortexSession::empty(); - crate::initialize(&session); - let operation = convert_time_zone(root(), "UTC"); - let restored = Expression::from_proto(&operation.serialize_proto()?, &session)?; + let mut ctx = SESSION.create_execution_ctx(); assert_execution_paths( - &[input.into_array()], - |inputs| inputs[0].clone().apply(&restored), - ExpectedOutcome::Array(expected.into_array()), - &mut session.create_execution_ctx(), + std::slice::from_ref(&input), + |inputs| inputs[0].clone().apply(&to_target), + ExpectedOutcome::Array(expected_target), + &mut ctx, + ); + assert_execution_paths( + &[input], + |inputs| inputs[0].clone().apply(&to_target)?.apply(&to_source), + ExpectedOutcome::Array(expected_source), + &mut ctx, ); + Ok(()) } + #[hegel::test(test_cases = 100, print_blob = true)] + fn test_convert_time_zone_roundtrips_preserved_instants(tc: TestCase) { + check_convert_time_zone_roundtrip(&tc) + .vortex_expect("converting timestamp zones must preserve stored instants"); + } + #[test] fn test_convert_time_zone_pushes_into_dictionary_values() -> VortexResult<()> { // The null code needs a strict function, and the unused value `1` needs an infallible one. @@ -268,7 +309,7 @@ mod tests { )? .into_array(), )?; - let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut ctx = SESSION.create_execution_ctx(); let result = input .into_array() diff --git a/vortex-extensions/vortex-temporal/src/datetime/mod.rs b/vortex-extensions/vortex-temporal/src/datetime/mod.rs index e5daf58bf6e..f9495cc07b1 100644 --- a/vortex-extensions/vortex-temporal/src/datetime/mod.rs +++ b/vortex-extensions/vortex-temporal/src/datetime/mod.rs @@ -28,3 +28,6 @@ pub use timestamp::*; mod unit; pub use unit::*; + +#[cfg(test)] +mod tests; diff --git a/vortex-extensions/vortex-temporal/src/datetime/tests.rs b/vortex-extensions/vortex-temporal/src/datetime/tests.rs new file mode 100644 index 00000000000..8bf82c1a5cf --- /dev/null +++ b/vortex-extensions/vortex-temporal/src/datetime/tests.rs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Roundtrip tests for registered temporal DType metadata. +//! +//! These checks keep temporal extension registration covered across supported serializers. + +use std::sync::Arc; + +use hegel::TestCase; +use hegel::generators as gs; +#[cfg(feature = "serde")] +use serde::de::DeserializeSeed; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::proto::dtype as pb; +#[cfg(feature = "serde")] +use vortex_array::dtype::serde::DTypeSerde; +use vortex_array::flatbuffers::FlatBuffer; +use vortex_array::flatbuffers::WriteFlatBufferExt; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +#[cfg(feature = "serde")] +use vortex_error::vortex_err; + +use crate::datetime::Date; +use crate::datetime::Duration; +use crate::datetime::Time; +use crate::datetime::TimeUnit; +use crate::datetime::Timestamp; +use crate::tests::common::SESSION; + +fn draw_temporal_dtype(tc: &TestCase) -> DType { + const UNITS: [TimeUnit; 4] = [ + TimeUnit::Nanoseconds, + TimeUnit::Microseconds, + TimeUnit::Milliseconds, + TimeUnit::Seconds, + ]; + const DATE_UNITS: [TimeUnit; 2] = [TimeUnit::Days, TimeUnit::Milliseconds]; + + let nullability = if tc.draw(gs::booleans()) { + Nullability::Nullable + } else { + Nullability::NonNullable + }; + + match tc.draw(gs::integers::().max_value(3)) { + 0 => { + let unit = DATE_UNITS[tc.draw(gs::integers::().max_value(DATE_UNITS.len() - 1))]; + DType::Extension(Date::new(unit, nullability).erased()) + } + 1 => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + DType::Extension(Duration::new(unit, nullability).erased()) + } + 2 => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + DType::Extension(Time::new(unit, nullability).erased()) + } + _ => { + let unit = UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + let time_zone: Option> = match tc.draw(gs::integers::().max_value(2)) { + 0 => None, + 1 => Some(Arc::from("UTC")), + _ => Some(Arc::from("America/New_York")), + }; + DType::Extension(Timestamp::new_with_tz(unit, time_zone, nullability).erased()) + } + } +} + +#[track_caller] +fn assert_temporal_dtype_roundtrip(dtype: &DType) -> VortexResult<()> { + let flatbuffer_bytes = dtype.write_flatbuffer_bytes()?; + let from_flatbuffer = DType::from_flatbuffer(FlatBuffer::from(flatbuffer_bytes), &SESSION)?; + let proto = pb::DType::try_from(dtype)?; + let from_proto = DType::from_proto(&proto, &SESSION)?; + + assert_eq!(&from_flatbuffer, dtype); + assert_eq!(&from_proto, dtype); + + #[cfg(feature = "serde")] + { + let json = serde_json::to_string(dtype) + .map_err(|err| vortex_err!("serialize temporal DType to JSON: {err}"))?; + let mut deserializer = serde_json::Deserializer::from_str(&json); + let from_json = DTypeSerde::::new(&SESSION) + .deserialize(&mut deserializer) + .map_err(|err| vortex_err!("deserialize temporal DType from JSON: {err}"))?; + assert_eq!(&from_json, dtype); + } + + Ok(()) +} + +#[hegel::test(test_cases = 100)] +fn test_temporal_dtype_serde_roundtrips_registered_metadata(tc: TestCase) { + let dtype = draw_temporal_dtype(&tc); + assert_temporal_dtype_roundtrip(&dtype) + .vortex_expect("registered temporal DTypes must roundtrip across supported formats"); +} diff --git a/vortex-extensions/vortex-temporal/src/replace_time_zone.rs b/vortex-extensions/vortex-temporal/src/replace_time_zone.rs index 1f3b8d1786a..d93e29fab7f 100644 --- a/vortex-extensions/vortex-temporal/src/replace_time_zone.rs +++ b/vortex-extensions/vortex-temporal/src/replace_time_zone.rs @@ -326,8 +326,9 @@ fn replace( #[cfg(test)] mod tests { use std::error::Error; - use std::sync::LazyLock; + use hegel::TestCase; + use hegel::generators as gs; use rstest::rstest; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -346,13 +347,17 @@ mod tests { use vortex_array::scalar_fn::ScalarFnVTable; use vortex_array::scalar_fn::ScalarFnVTableExt; use vortex_array::scalar_fn::builtin::literal::Literal; + use vortex_array::test_harness::ExpectedOutcome; + use vortex_array::test_harness::assert_execution_paths; + use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_expr::ArrayExprExt; + use vortex_expr::Expression; use vortex_expr::get_item; use vortex_expr::lit; + use vortex_expr::proto::ExprSerializeProtoExt; use vortex_expr::root; - use vortex_session::VortexSession; use super::ReplaceTimeZone; use super::ReplaceTimeZoneOptions; @@ -362,16 +367,8 @@ mod tests { use crate::datetime::TimeUnit; use crate::datetime::Timestamp; use crate::expr::replace_time_zone; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - - vortex_array::initialize(&session); - - crate::initialize(&session); - - session - }); + use crate::tests::common::SESSION; + use crate::tests::common::timestamp_array; fn timestamp() -> DType { DType::Extension(Timestamp::new(TimeUnit::Seconds, Nullability::NonNullable).erased()) @@ -416,36 +413,115 @@ mod tests { ); } - #[rstest] - #[case(TimeUnit::Seconds, 1)] - #[case(TimeUnit::Milliseconds, 1_000)] - #[case(TimeUnit::Microseconds, 1_000_000)] - #[case(TimeUnit::Nanoseconds, 1_000_000_000)] - fn preserves_units_and_fractional_values( - #[case] unit: TimeUnit, - #[case] scale: i64, - ) -> VortexResult<()> { - let utc = resolve_zone(None)?; - let new_york = resolve_zone(Some("America/New_York"))?; - let value = 1_705_320_000 * scale + scale / 2; - assert_eq!( - replace(value, unit, &utc, &new_york, "raise", false)?, - Some(value + 18_000 * scale) + fn winter_offset_seconds(zone: &str) -> i64 { + match zone { + "UTC" => 0, + "America/New_York" => -18_000, + "Asia/Tokyo" => 32_400, + _ => unreachable!("generated timezone must have a known winter offset"), + } + } + + fn check_replace_time_zone_roundtrip(tc: &TestCase) -> VortexResult<()> { + const ZONES: [&str; 3] = ["UTC", "America/New_York", "Asia/Tokyo"]; + const UNITS: [(TimeUnit, i64); 4] = [ + (TimeUnit::Seconds, 1), + (TimeUnit::Milliseconds, 1_000), + (TimeUnit::Microseconds, 1_000_000), + (TimeUnit::Nanoseconds, 1_000_000_000), + ]; + + let source_index = tc.draw(gs::integers::().max_value(ZONES.len() - 1)); + let target_offset = tc.draw(gs::integers::().max_value(ZONES.len() - 2)) + 1; + let target_index = (source_index + target_offset) % ZONES.len(); + let source_zone = ZONES[source_index]; + let target_zone = ZONES[target_index]; + let (unit, units_per_second) = + UNITS[tc.draw(gs::integers::().max_value(UNITS.len() - 1))]; + let len = tc.draw(gs::integers::().max_value(4)); + let nullable = tc.draw(gs::booleans()); + let has_nulls = nullable && tc.draw(gs::booleans()); + let nullability = if nullable { + Nullability::Nullable + } else { + Nullability::NonNullable + }; + let mut values = Vec::with_capacity(len); + // The mid-January window stays away from DST transitions in all generated zones. + for _ in 0..len { + if has_nulls && tc.draw(gs::booleans()) { + values.push(None); + continue; + } + let offset = tc.draw(gs::integers::().min_value(-3_600).max_value(3_600)); + let fraction = tc.draw( + gs::integers::() + .min_value(0) + .max_value(units_per_second - 1), + ); + values.push(Some((1_705_320_000 + offset) * units_per_second + fraction)); + } + if has_nulls && !values.is_empty() && !values.iter().any(Option::is_none) { + *values.last_mut().expect("nonempty generated array") = None; + } + + let input = timestamp_array(source_zone, unit, &values, nullability)?; + let adjustment = (winter_offset_seconds(source_zone) - winter_offset_seconds(target_zone)) + * units_per_second; + let target_values = values + .iter() + .map(|value| value.map(|value| value + adjustment)) + .collect::>(); + let expected_target = + timestamp_array(target_zone, unit, &target_values, Nullability::Nullable)?; + let expected = timestamp_array(source_zone, unit, &values, Nullability::Nullable)?; + let target_dtype = DType::Extension( + Timestamp::new_with_tz(unit, Some(target_zone.into()), Nullability::Nullable).erased(), ); - assert_eq!( - replace( - value + 18_000 * scale, - unit, - &new_york, - &utc, - "raise", - false - )?, - Some(value) + let options = |time_zone: &str| ReplaceTimeZoneOptions { + time_zone: Some(time_zone.into()), + null_on_non_existent: false, + }; + let to_target = Expression::from_proto( + &replace_time_zone(root(), lit("raise"), options(target_zone)).serialize_proto()?, + &SESSION, + )?; + let to_source = Expression::from_proto( + &replace_time_zone(root(), lit("raise"), options(source_zone)).serialize_proto()?, + &SESSION, + )?; + let mut ctx = SESSION.create_execution_ctx(); + + assert_execution_paths( + std::slice::from_ref(&input), + |inputs| { + let changed = inputs[0].clone().apply(&to_target)?; + assert_eq!(changed.dtype(), &target_dtype); + Ok(changed) + }, + ExpectedOutcome::Array(expected_target), + &mut ctx, + ); + assert_execution_paths( + &[input], + |inputs| { + let changed = inputs[0].clone().apply(&to_target)?; + assert_eq!(changed.dtype(), &target_dtype); + changed.apply(&to_source) + }, + ExpectedOutcome::Array(expected), + &mut ctx, ); + Ok(()) } + #[hegel::test(test_cases = 100, print_blob = true)] + fn test_replace_time_zone_roundtrips_unambiguous_wall_times(tc: TestCase) { + check_replace_time_zone_roundtrip(&tc) + .vortex_expect("unambiguous wall-time replacement must roundtrip across zones"); + } + #[test] fn resolves_folds_and_gaps_separately() -> VortexResult<()> { let utc = resolve_zone(None)?; @@ -536,7 +612,7 @@ mod tests { let micros = Scalar::primitive(1_704_153_600_000_000i64, Nullability::Nullable); let expr = replace_time_zone( lit(Scalar::extension_ref(timestamp(source), micros)), - lit("earliest"), + lit("raise"), ReplaceTimeZoneOptions { time_zone: target.map(Into::into), null_on_non_existent: false, diff --git a/vortex-extensions/vortex-temporal/src/tests/common.rs b/vortex-extensions/vortex-temporal/src/tests/common.rs index c27f4a8e7ca..170fc74b1ce 100644 --- a/vortex-extensions/vortex-temporal/src/tests/common.rs +++ b/vortex-extensions/vortex-temporal/src/tests/common.rs @@ -9,11 +9,16 @@ use std::sync::LazyLock; use vortex_array::ArrayRef; use vortex_array::IntoArray; +use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; +use vortex_error::VortexResult; use vortex_session::VortexSession; +use crate::datetime::TimeUnit; +use crate::datetime::Timestamp; + pub(crate) static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); vortex_array::initialize(&session); @@ -37,3 +42,16 @@ pub(crate) fn primitive_array( } } } + +pub(crate) fn timestamp_array( + zone: &str, + unit: TimeUnit, + values: &[Option], + nullability: Nullability, +) -> VortexResult { + Ok(ExtensionArray::try_new( + Timestamp::new_with_tz(unit, Some(zone.into()), nullability).erased(), + primitive_array(values, nullability), + )? + .into_array()) +}