Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 69 additions & 28 deletions vortex-extensions/vortex-temporal/src/convert_time_zone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -168,26 +168,21 @@ 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;
use crate::datetime::Date;
use crate::datetime::TimeUnit;
use crate::datetime::Timestamp;
use crate::expr::convert_time_zone;

static SESSION: LazyLock<VortexSession> = 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()
Expand Down Expand Up @@ -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<DType>,
#[case] time_zone: &str,
#[case] supported: bool,
Expand All @@ -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::<usize>().max_value(ZONES.len() - 1));
let target_offset = tc.draw(gs::integers::<usize>().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::<usize>().max_value(UNITS.len() - 1))];
let len = tc.draw(gs::integers::<usize>().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::<i64>())));
}
}
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.
Expand All @@ -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()
Expand Down
3 changes: 3 additions & 0 deletions vortex-extensions/vortex-temporal/src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ pub use timestamp::*;

mod unit;
pub use unit::*;

#[cfg(test)]
mod tests;
102 changes: 102 additions & 0 deletions vortex-extensions/vortex-temporal/src/datetime/tests.rs
Original file line number Diff line number Diff line change
@@ -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::<u8>().max_value(3)) {
0 => {
let unit = DATE_UNITS[tc.draw(gs::integers::<usize>().max_value(DATE_UNITS.len() - 1))];
DType::Extension(Date::new(unit, nullability).erased())
}
1 => {
let unit = UNITS[tc.draw(gs::integers::<usize>().max_value(UNITS.len() - 1))];
DType::Extension(Duration::new(unit, nullability).erased())
}
2 => {
let unit = UNITS[tc.draw(gs::integers::<usize>().max_value(UNITS.len() - 1))];
DType::Extension(Time::new(unit, nullability).erased())
}
_ => {
let unit = UNITS[tc.draw(gs::integers::<usize>().max_value(UNITS.len() - 1))];
let time_zone: Option<Arc<str>> = match tc.draw(gs::integers::<u8>().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::<DType>::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");
}
Loading
Loading