From 55d31c785cf60903d3ce28d01f2ca5a770084ff6 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 19:17:30 +0000 Subject: [PATCH 1/9] Match struct scalar casts by field name and add Hegel suites Signed-off-by: Will Manning --- .../fns/all_non_distinct/tests.rs | 1653 ++++------------- vortex-array/src/scalar/mod.rs | 2 +- vortex-array/src/scalar/proto.rs | 552 +----- vortex-array/src/scalar/tests/casting.rs | 441 ++--- vortex-array/src/scalar/tests/hegel.rs | 655 +++++++ vortex-array/src/scalar/tests/mod.rs | 1 + vortex-array/src/scalar/tests/nested.rs | 1435 +------------- vortex-array/src/scalar/tests/nullability.rs | 796 +------- vortex-array/src/scalar/tests/primitives.rs | 639 ++----- vortex-array/src/scalar/tests/round_trip.rs | 248 +-- .../src/scalar/typed_view/decimal/tests.rs | 1513 ++++----------- .../src/scalar/typed_view/extension/tests.rs | 319 +--- vortex-array/src/scalar/typed_view/list.rs | 336 +--- .../src/scalar/typed_view/primitive/tests.rs | 858 +++------ vortex-array/src/scalar/typed_view/struct_.rs | 526 ++---- 15 files changed, 2342 insertions(+), 7632 deletions(-) create mode 100644 vortex-array/src/scalar/tests/hegel.rs diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs index 17b7e5193e3..f00d95c1c23 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs @@ -3,8 +3,13 @@ use std::sync::LazyLock; +use hegel::TestCase; +use hegel::generators as gs; use rstest::rstest; +use vortex_buffer::BitBuffer; +use vortex_buffer::Buffer; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -29,9 +34,10 @@ use crate::arrays::ListViewArray; use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; -use crate::arrays::VarBinViewArray; +use crate::arrays::UnionArray; use crate::arrays::VariantArray; use crate::arrays::WidenArray; +use crate::builders::builder_with_capacity_in; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::FieldNames; @@ -39,1007 +45,344 @@ use crate::dtype::MapDType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::StructFields; +use crate::dtype::UnionVariants; use crate::dtype::extension::ForeignExtDType; use crate::scalar::Scalar; +use crate::scalar::tests::hegel::draw_scalar; +use crate::scalar::tests::hegel::draw_scalar_dtype; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); /// Baseline oracle: compare two arrays element-wise using `execute_scalar`. -/// Returns true iff every position has the same scalar (null == null is true). fn scalar_baseline(a: &ArrayRef, b: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { assert_eq!(a.len(), b.len()); for i in 0..a.len() { - let sa = a.execute_scalar(i, ctx)?; - let sb = b.execute_scalar(i, ctx)?; - if sa != sb { + if a.execute_scalar(i, ctx)? != b.execute_scalar(i, ctx)? { return Ok(false); } } Ok(true) } -/// Assert that `all_non_distinct` agrees with the scalar baseline. fn assert_matches_baseline(a: &ArrayRef, b: &ArrayRef) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let expected = scalar_baseline(a, b, &mut ctx)?; let actual = all_non_distinct(a, b, &mut ctx)?; assert_eq!( actual, expected, - "all_non_distinct disagrees with scalar baseline for arrays:\n a: {:?}\n b: {:?}", - a, b + "all_non_distinct disagrees with scalar baseline for:\n a: {a:?}\n b: {b:?}" ); Ok(()) } -// ─── Null arrays ───────────────────────────────────────────────────────────── - -#[test] -fn null_arrays_identical() -> VortexResult<()> { - let a = NullArray::new(3).into_array(); - let b = NullArray::new(3).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn null_arrays_empty() -> VortexResult<()> { - let a = NullArray::new(0).into_array(); - let b = NullArray::new(0).into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Bool ──────────────────────────────────────────────────────────────────── - -#[rstest] -#[case::identical(&[true, false, true], &[true, false, true], true)] -#[case::different(&[true, false, true], &[true, true, true], false)] -#[case::empty(&[], &[], true)] -#[case::single_true(&[true], &[true], true)] -#[case::single_false(&[false], &[false], true)] -#[case::single_mismatch(&[true], &[false], false)] -#[case::all_true(&[true, true, true], &[true, true, true], true)] -#[case::all_false(&[false, false, false], &[false, false, false], true)] -fn bool_non_nullable( - #[case] a: &[bool], - #[case] b: &[bool], - #[case] expected: bool, -) -> VortexResult<()> { - let a = BoolArray::from_iter(a.iter().copied()).into_array(); - let b = BoolArray::from_iter(b.iter().copied()).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -#[rstest] -#[case::same_nulls( - &[Some(true), None, Some(false)], - &[Some(true), None, Some(false)], - true -)] -#[case::different_under_null( - &[Some(true), None, Some(false)], - &[Some(true), None, Some(true)], - false -)] -#[case::null_vs_value( - &[Some(true), None], - &[Some(true), Some(false)], - false -)] -#[case::all_null( - &[None, None, None], - &[None, None, None], - true -)] -fn bool_nullable( - #[case] a: &[Option], - #[case] b: &[Option], - #[case] expected: bool, -) -> VortexResult<()> { - let a = BoolArray::from_iter(a.iter().copied()).into_array(); - let b = BoolArray::from_iter(b.iter().copied()).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -// ─── Primitive (multiple ptypes) ───────────────────────────────────────────── - -#[rstest] -#[case::i32_identical(vec![1i32, 2, 3], vec![1i32, 2, 3], true)] -#[case::i32_different(vec![1i32, 2, 3], vec![1i32, 2, 4], false)] -#[case::i32_empty(vec![], vec![], true)] -#[case::i32_single(vec![42i32], vec![42i32], true)] -fn primitive_i32( - #[case] a: Vec, - #[case] b: Vec, - #[case] expected: bool, -) -> VortexResult<()> { - let a = PrimitiveArray::from_iter(a).into_array(); - let b = PrimitiveArray::from_iter(b).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -#[test] -fn primitive_f64() -> VortexResult<()> { - let a = buffer![1.0f64, 2.5, 3.0].into_array(); - let b = buffer![1.0f64, 2.5, 3.0].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn primitive_f64_different() -> VortexResult<()> { - let a = buffer![1.0f64, 2.5, 3.0].into_array(); - let b = buffer![1.0f64, 2.5, 3.1].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn primitive_u8() -> VortexResult<()> { - let a = buffer![0u8, 128, 255].into_array(); - let b = buffer![0u8, 128, 255].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn primitive_i64() -> VortexResult<()> { - let a = buffer![i64::MIN, 0i64, i64::MAX].into_array(); - let b = buffer![i64::MIN, 0i64, i64::MAX].into_array(); - assert_matches_baseline(&a, &b) -} - -#[rstest] -#[case::same_nulls( - &[Some(1i32), None, Some(3)], - &[Some(1i32), None, Some(3)], - true -)] -#[case::null_vs_value( - &[Some(1i32), None, Some(3)], - &[Some(1i32), Some(2), Some(3)], - false -)] -#[case::different_values_under_valid( - &[Some(1i32), None, Some(3)], - &[Some(1i32), None, Some(99)], - false -)] -#[case::all_null( - &[None, None], - &[None, None], - true -)] -#[case::single_null( - &[None], - &[None], - true -)] -fn primitive_nullable( - #[case] a: &[Option], - #[case] b: &[Option], - #[case] expected: bool, -) -> VortexResult<()> { - let a = PrimitiveArray::from_option_iter(a.iter().copied()).into_array(); - let b = PrimitiveArray::from_option_iter(b.iter().copied()).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -// ─── VarBinView (strings / binary) ────────────────────────────────────────── - -#[rstest] -#[case::identical(&["hello", "world"], &["hello", "world"], true)] -#[case::different(&["hello", "world"], &["hello", "earth"], false)] -#[case::empty_strings(&["", ""], &["", ""], true)] -#[case::single(&["abc"], &["abc"], true)] -#[case::long_strings( - &["a]long string that exceeds inline"], - &["a]long string that exceeds inline"], - true -)] -#[case::long_strings_different( - &["a long string that exceeds inline"], - &["a long string that exceeds OOPS!"], - false -)] -fn strings_non_nullable( - #[case] a: &[&str], - #[case] b: &[&str], - #[case] expected: bool, -) -> VortexResult<()> { - let a = VarBinViewArray::from_iter_str(a.iter().copied()).into_array(); - let b = VarBinViewArray::from_iter_str(b.iter().copied()).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -#[rstest] -#[case::same_nulls( - &[Some("hi"), None, Some("lo")], - &[Some("hi"), None, Some("lo")], - true -)] -#[case::null_vs_value( - &[Some("hi"), None], - &[Some("hi"), Some("lo")], - false -)] -fn strings_nullable( - #[case] a: &[Option<&str>], - #[case] b: &[Option<&str>], - #[case] expected: bool, -) -> VortexResult<()> { - let a = VarBinViewArray::from_iter_nullable_str(a.iter().copied()).into_array(); - let b = VarBinViewArray::from_iter_nullable_str(b.iter().copied()).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); - assert_matches_baseline(&a, &b) -} - -// ─── Decimal ───────────────────────────────────────────────────────────────── - -#[test] -fn decimal_identical() -> VortexResult<()> { - let dtype = DecimalDType::new(5, 2); - let a = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); - let b = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn decimal_different() -> VortexResult<()> { - let dtype = DecimalDType::new(5, 2); - let a = DecimalArray::from_iter([100i32, 200, 300], dtype).into_array(); - let b = DecimalArray::from_iter([100i32, 200, 999], dtype).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn decimal_widened_child() -> VortexResult<()> { - let dtype = DecimalDType::new(3, 0); - let canonical = DecimalArray::from_iter([1i16, 2, 3], dtype).into_array(); - let narrow = DecimalArray::from_iter([1i8, 2, 3], DecimalDType::new(2, 0)); - let widened = WidenArray::try_new(narrow.into_array(), canonical.dtype().clone())?.into_array(); - assert_matches_baseline(&canonical, &widened) -} - -#[rstest] -fn decimal_canonical_widths(#[values(2, 4, 9, 18, 38, 76)] precision: u8) -> VortexResult<()> { - let dtype = DecimalDType::new(precision, 0); - let a = DecimalArray::from_iter([1i8, 2, 3], dtype).into_array(); - let equal = DecimalArray::from_iter([1i8, 2, 3], dtype).into_array(); - let b = DecimalArray::from_iter([1i8, 2, -3], dtype).into_array(); - - assert_matches_baseline(&a, &equal)?; - assert_matches_baseline(&a, &b) -} - -#[test] -fn decimal_nullable() -> VortexResult<()> { - let dtype = DecimalDType::new(5, 2); - let validity = Validity::from_iter([true, false, true]); - let mut ctx = SESSION.create_execution_ctx(); - let a = DecimalArray::new(buffer![100i32, 200, 300], dtype, validity.clone(), &mut ctx) - .into_array(); - let b = DecimalArray::new(buffer![100i32, 999, 300], dtype, validity, &mut ctx).into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Struct ────────────────────────────────────────────────────────────────── - -#[test] -fn struct_identical() -> VortexResult<()> { - let a = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 2].into_array(), - buffer![10i32, 20].into_array(), - ], - 2, - Validity::NonNullable, - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 2].into_array(), - buffer![10i32, 20].into_array(), - ], - 2, - Validity::NonNullable, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn struct_different() -> VortexResult<()> { - let a = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 2].into_array(), - buffer![10i32, 20].into_array(), - ], - 2, - Validity::NonNullable, - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 2].into_array(), - buffer![10i32, 99].into_array(), - ], - 2, - Validity::NonNullable, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn struct_nullable_ignores_garbage_under_nulls() -> VortexResult<()> { - let validity = Validity::from_iter([true, false]); - let a = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 2].into_array(), - buffer![10i32, 20].into_array(), - ], - 2, - validity.clone(), - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["x", "y"]), - vec![ - buffer![1i32, 99].into_array(), - buffer![10i32, 999].into_array(), - ], - 2, - validity, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn struct_nested_nullable_fields() -> VortexResult<()> { - let a = StructArray::try_new( - FieldNames::from(["x"]), - vec![PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array()], - 3, - Validity::NonNullable, - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["x"]), - vec![PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array()], - 3, - Validity::NonNullable, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── List ──────────────────────────────────────────────────────────────────── - -#[test] -fn list_identical() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let elements = buffer![1i32, 2, 3, 4].into_array(); - let a = ListViewArray::try_new( - elements.clone(), - buffer![0u32, 2].into_array(), - buffer![2u32, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let b = ListViewArray::try_new( - elements, - buffer![0u32, 2].into_array(), - buffer![2u32, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn list_different_elements() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let a = ListViewArray::try_new( - buffer![1i32, 2, 3, 4].into_array(), - buffer![0u32, 2].into_array(), - buffer![2u32, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let b = ListViewArray::try_new( - buffer![1i32, 2, 3, 99].into_array(), - buffer![0u32, 2].into_array(), - buffer![2u32, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn list_different_lengths() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let a = ListViewArray::try_new( - buffer![1i32, 2, 3].into_array(), - buffer![0u32, 2].into_array(), - buffer![2u32, 1].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let b = ListViewArray::try_new( - buffer![1i32, 2, 3].into_array(), - buffer![0u32, 2].into_array(), - buffer![2u32, 1].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &b)?; - let mut ctx = SESSION.create_execution_ctx(); - assert!(all_non_distinct(&a, &b, &mut ctx)?); - let different = ListViewArray::try_new( - buffer![1i32, 2, 3].into_array(), - buffer![0u32, 1].into_array(), - buffer![1u32, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &different)?; - assert!(!all_non_distinct(&a, &different, &mut ctx)?); - Ok(()) -} - -#[test] -fn list_nullable_ignores_garbage() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let validity = Validity::from_iter([true, false]); - let a = ListViewArray::try_new( - buffer![1i32, 2, 3, 4].into_array(), - buffer![0u8, 2].into_array(), - buffer![2u8, 2].into_array(), - validity.clone(), - &mut ctx, - )? - .into_array(); - let b = ListViewArray::try_new( - buffer![1i32, 2, 9, 8].into_array(), - buffer![0u8, 2].into_array(), - buffer![2u8, 2].into_array(), - validity, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn list_different_offset_dtypes() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let elements = buffer![1i32, 2, 3, 4].into_array(); - let a = ListViewArray::try_new( - elements.clone(), - buffer![0u8, 2].into_array(), - buffer![2u8, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let b = ListViewArray::try_new( - elements, - buffer![0i16, 2].into_array(), - buffer![2i16, 2].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── FixedSizeList ─────────────────────────────────────────────────────────── - -#[test] -fn fixed_size_list_identical() -> VortexResult<()> { - let a = FixedSizeListArray::try_new( - buffer![1i32, 2, 3, 4].into_array(), - 2, - Validity::NonNullable, - 2, - )? - .into_array(); - let b = FixedSizeListArray::try_new( - buffer![1i32, 2, 3, 4].into_array(), - 2, - Validity::NonNullable, - 2, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn fixed_size_list_different() -> VortexResult<()> { - let a = FixedSizeListArray::try_new( - buffer![1i32, 2, 3, 4].into_array(), - 2, - Validity::NonNullable, - 2, - )? - .into_array(); - let b = FixedSizeListArray::try_new( - buffer![1i32, 2, 3, 99].into_array(), - 2, - Validity::NonNullable, - 2, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn fixed_size_list_nullable_ignores_garbage() -> VortexResult<()> { - let validity = Validity::from_iter([true, false]); - let a = - FixedSizeListArray::try_new(buffer![1i32, 2, 3, 4].into_array(), 2, validity.clone(), 2)? - .into_array(); - let b = FixedSizeListArray::try_new(buffer![1i32, 2, 9, 8].into_array(), 2, validity, 2)? - .into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Chunked ───────────────────────────────────────────────────────────────── - -#[test] -fn chunked_identical() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32, 4].into_array()], - dtype.clone(), - )? - .into_array(); - let b = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32, 4].into_array()], - dtype, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn chunked_different() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32, 4].into_array()], - dtype.clone(), - )? - .into_array(); - let b = ChunkedArray::try_new( - vec![ - buffer![1i32, 2].into_array(), - buffer![3i32, 99].into_array(), - ], - dtype, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn chunked_different_chunk_boundaries() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new( - vec![buffer![1i32, 2, 3].into_array(), buffer![4i32].into_array()], - dtype.clone(), - )? - .into_array(); - let b = ChunkedArray::try_new( - vec![buffer![1i32].into_array(), buffer![2i32, 3, 4].into_array()], - dtype, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn chunked_empty() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new(vec![], dtype.clone())?.into_array(); - let b = ChunkedArray::try_new(vec![], dtype)?.into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn chunked_with_nullable() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let a = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter([Some(1i32), None]).into_array(), - PrimitiveArray::from_option_iter([Some(3i32)]).into_array(), - ], - dtype.clone(), - )? - .into_array(); - let b = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter([Some(1i32), None]).into_array(), - PrimitiveArray::from_option_iter([Some(3i32)]).into_array(), - ], - dtype, - )? - .into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Edge cases ────────────────────────────────────────────────────────────── - -#[test] -fn single_element_different() -> VortexResult<()> { - let a = buffer![42i32].into_array(); - let b = buffer![43i32].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn first_element_different() -> VortexResult<()> { - let a = buffer![99i32, 2, 3, 4, 5].into_array(); - let b = buffer![1i32, 2, 3, 4, 5].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn last_element_different() -> VortexResult<()> { - let a = buffer![1i32, 2, 3, 4, 5].into_array(); - let b = buffer![1i32, 2, 3, 4, 99].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn middle_element_different() -> VortexResult<()> { - let a = buffer![1i32, 2, 3, 4, 5].into_array(); - let b = buffer![1i32, 2, 99, 4, 5].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn alternating_nulls_identical() -> VortexResult<()> { - let a = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None, Some(5)]).into_array(); - let b = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None, Some(5)]).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn alternating_nulls_different_value() -> VortexResult<()> { - let a = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None, Some(5)]).into_array(); - let b = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(99), None, Some(5)]).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn leading_nulls() -> VortexResult<()> { - let a = PrimitiveArray::from_option_iter([None, None, Some(3i32)]).into_array(); - let b = PrimitiveArray::from_option_iter([None, None, Some(3i32)]).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn trailing_nulls() -> VortexResult<()> { - let a = PrimitiveArray::from_option_iter([Some(1i32), None, None]).into_array(); - let b = PrimitiveArray::from_option_iter([Some(1i32), None, None]).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn large_array_identical() -> VortexResult<()> { - let values: Vec = (0..1000).collect(); - let a = PrimitiveArray::from_iter(values.clone()).into_array(); - let b = PrimitiveArray::from_iter(values).into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn large_array_last_differs() -> VortexResult<()> { - let mut values_a: Vec = (0..1000).collect(); - let mut values_b = values_a.clone(); - values_a[999] = 0; - values_b[999] = 1; - let a = PrimitiveArray::from_iter(values_a).into_array(); - let b = PrimitiveArray::from_iter(values_b).into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Cross-encoding (mixed non-canonical arrays) ──────────────────────────── - -#[test] -fn chunked_vs_primitive() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32, 4].into_array()], - dtype, - )? - .into_array(); - let b = buffer![1i32, 2, 3, 4].into_array(); - assert_matches_baseline(&a, &b) -} - -#[test] -fn chunked_vs_primitive_different() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let a = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32, 4].into_array()], - dtype, - )? - .into_array(); - let b = buffer![1i32, 2, 3, 99].into_array(); - assert_matches_baseline(&a, &b) -} - -// ─── Nested structs with nullable inner fields ────────────────────────────── - -#[test] -fn struct_with_nullable_string_field() -> VortexResult<()> { - let a = StructArray::try_new( - FieldNames::from(["name", "age"]), - vec![ - VarBinViewArray::from_iter_nullable_str([Some("alice"), None, Some("charlie")]) - .into_array(), - PrimitiveArray::from_option_iter([Some(30i32), Some(25), None]).into_array(), - ], - 3, - Validity::NonNullable, - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["name", "age"]), - vec![ - VarBinViewArray::from_iter_nullable_str([Some("alice"), None, Some("charlie")]) - .into_array(), - PrimitiveArray::from_option_iter([Some(30i32), Some(25), None]).into_array(), - ], - 3, - Validity::NonNullable, - )? - .into_array(); - assert_matches_baseline(&a, &b) +fn pair_dtype(elem: &DType, nullability: Nullability) -> DType { + DType::Struct( + StructFields::new( + FieldNames::from(["lhs", "rhs"]), + vec![elem.clone(), elem.clone()], + ), + nullability, + ) } -#[test] -fn struct_with_nullable_string_field_different() -> VortexResult<()> { - let a = StructArray::try_new( - FieldNames::from(["name"]), - vec![ - VarBinViewArray::from_iter_nullable_str([Some("alice"), None, Some("charlie")]) - .into_array(), - ], - 3, - Validity::NonNullable, - )? - .into_array(); - let b = StructArray::try_new( - FieldNames::from(["name"]), - vec![ - VarBinViewArray::from_iter_nullable_str([Some("alice"), None, Some("david")]) - .into_array(), - ], - 3, - Validity::NonNullable, - )? - .into_array(); - assert_matches_baseline(&a, &b) +fn const_pair(lhs: Scalar, rhs: Scalar, len: usize) -> ArrayRef { + let dt = pair_dtype(lhs.dtype(), Nullability::NonNullable); + ConstantArray::new(Scalar::struct_(dt, [lhs, rhs]), len).into_array() } -// ─── Constant struct batches via Accumulator ───────────────────────────────── - fn accumulate_all_non_distinct(batches: &[ArrayRef]) -> VortexResult { let mut ctx = SESSION.create_execution_ctx(); - let dtype = batches[0].dtype().clone(); - let mut acc = Accumulator::try_new(AllNonDistinct, EmptyOptions, dtype)?; + let mut acc = Accumulator::try_new(AllNonDistinct, EmptyOptions, batches[0].dtype().clone())?; for batch in batches { acc.accumulate(batch, &mut ctx)?; } - let result = acc.finish()?; - Ok(result.as_bool().value().unwrap_or(false)) + Ok(acc.finish()?.as_bool().value().unwrap_or(false)) +} + +fn build_array(dtype: &DType, scalars: &[Scalar], ctx: &ExecutionCtx) -> VortexResult { + let mut builder = builder_with_capacity_in(dtype, scalars.len(), ctx.allocator()); + for s in scalars { + builder.append_scalar(s)?; + } + Ok(builder.finish()) +} + +/// Randomly wraps an array as canonical, sliced, chunked (with arbitrary boundaries and empty +/// chunks), or constant (when uniform). +fn wrap_array( + tc: &TestCase, + dtype: &DType, + scalars: &[Scalar], + ctx: &ExecutionCtx, +) -> VortexResult { + match tc.draw(gs::integers::().max_value(3)) { + 0 => build_array(dtype, scalars, ctx), + 1 => { + let prefix = tc.draw(gs::integers::().max_value(3)); + let suffix = tc.draw(gs::integers::().max_value(3)); + let mut padded = Vec::with_capacity(prefix + scalars.len() + suffix); + padded.extend((0..prefix).map(|_| draw_scalar(tc, dtype))); + padded.extend_from_slice(scalars); + padded.extend((0..suffix).map(|_| draw_scalar(tc, dtype))); + build_array(dtype, &padded, ctx)?.slice(prefix..prefix + scalars.len()) + } + 2 => { + let mut chunks = Vec::new(); + let mut pos = 0; + while pos < scalars.len() { + if tc.draw(gs::integers::().max_value(4)) == 0 { + chunks.push(build_array(dtype, &[], ctx)?); + } + let take = tc.draw( + gs::integers::() + .min_value(1) + .max_value(scalars.len() - pos), + ); + chunks.push(build_array(dtype, &scalars[pos..pos + take], ctx)?); + pos += take; + } + Ok(ChunkedArray::try_new(chunks, dtype.clone())?.into_array()) + } + _ => match scalars.first() { + Some(first) if scalars.iter().all(|s| s == first) => { + Ok(ConstantArray::new(first.clone(), scalars.len()).into_array()) + } + _ => build_array(dtype, scalars, ctx), + }, + } } -#[rstest] -#[case::equal(1, 1, 4, true)] -#[case::distinct(1, 2, 4, false)] -#[case::empty_distinct(1, 2, 0, true)] -fn constant_struct_non_nullable( - #[case] lhs: i32, - #[case] rhs: i32, - #[case] len: usize, - #[case] expected: bool, -) -> VortexResult<()> { - let field_dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let struct_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![field_dtype.clone(), field_dtype], - ), - Nullability::NonNullable, - ); - let scalar = Scalar::struct_(struct_dtype, [Scalar::from(lhs), Scalar::from(rhs)]); - let batch = ConstantArray::new(scalar, len).into_array(); +#[hegel::test(test_cases = 200)] +fn hegel_all_non_distinct_matches_scalar_baseline(tc: TestCase) { + let depth = tc.draw(gs::integers::().max_value(2)); + let dtype = draw_scalar_dtype(&tc, depth, false); + let len = tc.draw(gs::integers::().max_value(10)); + let ctx = SESSION.create_execution_ctx(); + + let scalars_a: Vec = (0..len).map(|_| draw_scalar(&tc, &dtype)).collect(); + let scalars_b: Vec = match tc.draw(gs::integers::().max_value(3)) { + 0 => scalars_a.clone(), + 1 if len > 0 => { + let mut mutated = scalars_a.clone(); + let idx = tc.draw(gs::integers::().max_value(len - 1)); + mutated[idx] = draw_scalar(&tc, &dtype); + mutated + } + 2 if len > 0 => vec![draw_scalar(&tc, &dtype); len], + _ => (0..len).map(|_| draw_scalar(&tc, &dtype)).collect(), + }; - assert_eq!(accumulate_all_non_distinct(&[batch])?, expected); - Ok(()) + let a = wrap_array(&tc, &dtype, &scalars_a, &ctx).vortex_expect("build a"); + let b = wrap_array(&tc, &dtype, &scalars_b, &ctx).vortex_expect("build b"); + assert_matches_baseline(&a, &b).vortex_expect("differential check"); } -#[rstest] -#[case::both_null(None, None, true)] -#[case::lhs_null(None, Some(1), false)] -#[case::rhs_null(Some(1), None, false)] -#[case::both_equal(Some(1), Some(1), true)] -#[case::both_distinct(Some(1), Some(2), false)] -fn constant_struct_nullable_fields( - #[case] lhs: Option, - #[case] rhs: Option, - #[case] expected: bool, -) -> VortexResult<()> { - let field_dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let struct_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![field_dtype.clone(), field_dtype], - ), - Nullability::NonNullable, - ); - let to_scalar = |value: Option| match value { - Some(v) => Scalar::primitive(v, Nullability::Nullable), - None => Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - }; - let scalar = Scalar::struct_(struct_dtype, [to_scalar(lhs), to_scalar(rhs)]); - let batch = ConstantArray::new(scalar, 4).into_array(); +#[hegel::test(test_cases = 100)] +fn hegel_nullable_garbage_under_nulls_ignored(tc: TestCase) { + let len = tc.draw(gs::integers::().min_value(1).max_value(8)); + let valid: Vec = (0..len).map(|_| tc.draw(gs::booleans())).collect(); + let validity = Validity::from_iter(valid.iter().copied()); + let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(accumulate_all_non_distinct(&[batch])?, expected); - Ok(()) -} + let draw_i32_pair = |count_per_row: usize| -> (Vec, Vec) { + let mut a = Vec::with_capacity(len * count_per_row); + let mut b = Vec::with_capacity(len * count_per_row); + for &v in &valid { + for _ in 0..count_per_row { + let x = tc.draw(gs::integers::().min_value(-9999).max_value(9999)); + a.push(x); + b.push(if v { + x + } else { + tc.draw(gs::integers::().min_value(-9999).max_value(9999)) + }); + } + } + (a, b) + }; -#[test] -fn constant_struct_outer_null_is_true() -> VortexResult<()> { - let field_dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let struct_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![field_dtype.clone(), field_dtype], - ), - Nullability::Nullable, - ); - let batch = ConstantArray::new(Scalar::null(struct_dtype), 4).into_array(); + let [a, b]: [ArrayRef; 2] = match tc.draw(gs::integers::().max_value(4)) { + 0 => { + let (va, vb) = draw_i32_pair(1); + [va, vb].map(|v| PrimitiveArray::new(Buffer::from(v), validity.clone()).into_array()) + } + 1 => { + let (mut bool_a, mut bool_b) = (Vec::with_capacity(len), Vec::with_capacity(len)); + for &v in &valid { + let x = tc.draw(gs::booleans()); + bool_a.push(x); + bool_b.push(if v { x } else { tc.draw(gs::booleans()) }); + } + [bool_a, bool_b] + .map(|v| BoolArray::new(BitBuffer::from_iter(v), validity.clone()).into_array()) + } + 2 => { + let (va, vb) = draw_i32_pair(1); + let dt = DecimalDType::new(5, 2); + [va, vb].map(|v| { + DecimalArray::new(Buffer::from(v), dt, validity.clone(), &mut ctx).into_array() + }) + } + 3 => { + let (va, vb) = draw_i32_pair(1); + [va, vb].map(|v| { + StructArray::try_new( + FieldNames::from(["x"]), + vec![PrimitiveArray::from_iter(v).into_array()], + len, + validity.clone(), + ) + .vortex_expect("struct") + .into_array() + }) + } + _ => { + let (va, vb) = draw_i32_pair(2); + [va, vb].map(|v| { + FixedSizeListArray::try_new( + PrimitiveArray::from_iter(v).into_array(), + 2, + validity.clone(), + len, + ) + .vortex_expect("fsl") + .into_array() + }) + } + }; - assert!(accumulate_all_non_distinct(&[batch])?); - Ok(()) + assert!(all_non_distinct(&a, &b, &mut ctx).vortex_expect("all_non_distinct")); + assert_matches_baseline(&a, &b).vortex_expect("baseline match"); } +// ─── Focused Corner Cases ──────────────────────────────────────────────────── + #[rstest] -#[case::nan(f64::NAN, f64::NAN, true)] -#[case::signed_zeros(-0.0, 0.0, false)] -fn constant_struct_float_bit_equality( +#[case::signed_zeros(-0.0f64, 0.0f64, false)] +#[case::canonical_nan(f64::NAN, f64::NAN, true)] +#[case::same_nan_payload( + f64::from_bits(0x7ff8_0000_0000_0001), + f64::from_bits(0x7ff8_0000_0000_0001), + true +)] +#[case::nan_distinct_payloads( + f64::from_bits(0x7ff8_0000_0000_0001), + f64::from_bits(0x7ff8_0000_0000_0002), + false +)] +#[case::neg_nan_vs_pos_nan( + f64::from_bits(0xfff8_0000_0000_0000), + f64::from_bits(0x7ff8_0000_0000_0000), + false +)] +fn float_bit_equality_and_nan_payloads( #[case] lhs: f64, #[case] rhs: f64, #[case] expected: bool, ) -> VortexResult<()> { - let field_dtype = DType::Primitive(PType::F64, Nullability::NonNullable); - let struct_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![field_dtype.clone(), field_dtype], - ), - Nullability::NonNullable, + let (a, b) = (buffer![lhs].into_array(), buffer![rhs].into_array()); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!(all_non_distinct(&a, &b, &mut ctx)?, expected); + assert_matches_baseline(&a, &b)?; + assert_eq!( + accumulate_all_non_distinct(&[const_pair(Scalar::from(lhs), Scalar::from(rhs), 3)])?, + expected ); - let scalar = Scalar::struct_(struct_dtype, [Scalar::from(lhs), Scalar::from(rhs)]); - let batch = ConstantArray::new(scalar, 3).into_array(); - - assert_eq!(accumulate_all_non_distinct(&[batch])?, expected); Ok(()) } #[test] -fn constant_struct_null_nested_struct_distinct_from_null_fields() -> VortexResult<()> { - let inner_field_dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let inner_dtype = DType::Struct( - StructFields::new(FieldNames::from(["x"]), vec![inner_field_dtype.clone()]), - Nullability::Nullable, - ); - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![inner_dtype.clone(), inner_dtype.clone()], - ), - Nullability::NonNullable, - ); +fn empty_mismatched_widened_decimal_and_list_offsets() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let empty_null = NullArray::new(0).into_array(); + assert!(all_non_distinct(&empty_null, &empty_null, &mut ctx)?); + let empty_chunked = ChunkedArray::try_new( + vec![], + DType::Primitive(PType::I32, Nullability::NonNullable), + )? + .into_array(); + assert!(all_non_distinct(&empty_chunked, &empty_chunked, &mut ctx)?); - let null_struct = Scalar::null(inner_dtype.clone()); - let struct_of_null = Scalar::struct_(inner_dtype, [Scalar::null(inner_field_dtype)]); + // Mismatched lengths and dtypes return errors. + let a = buffer![1i32, 2].into_array(); + assert!(all_non_distinct(&a, &buffer![1i32].into_array(), &mut ctx).is_err()); + assert!(all_non_distinct(&a, &buffer![1i64, 2].into_array(), &mut ctx).is_err()); - let distinct = ConstantArray::new( - Scalar::struct_( - pair_dtype.clone(), - [null_struct.clone(), struct_of_null.clone()], - ), - 3, - ) - .into_array(); - let equal_nulls = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [null_struct.clone(), null_struct]), - 3, - ) + // Widened narrow DecimalArray matches canonical DecimalArray. + let canonical = DecimalArray::from_iter([1i16, 2, 3], DecimalDType::new(3, 0)).into_array(); + let narrow = DecimalArray::from_iter([1i8, 2, 3], DecimalDType::new(2, 0)); + let widened = WidenArray::try_new(narrow.into_array(), canonical.dtype().clone())?.into_array(); + assert_matches_baseline(&canonical, &widened)?; + + // ListView arrays with different offset/size ptypes (u8 vs i16) compare equal. + let elems = buffer![1i32, 2, 3, 4].into_array(); + let lv_u8 = ListViewArray::try_new( + elems.clone(), + buffer![0u8, 2].into_array(), + buffer![2u8, 2].into_array(), + Validity::NonNullable, + &mut ctx, + )? .into_array(); - let equal_inner = ConstantArray::new( - Scalar::struct_(pair_dtype, [struct_of_null.clone(), struct_of_null]), - 3, - ) + let lv_i16 = ListViewArray::try_new( + elems, + buffer![0i16, 2].into_array(), + buffer![2i16, 2].into_array(), + Validity::NonNullable, + &mut ctx, + )? .into_array(); - - assert!(!accumulate_all_non_distinct(&[distinct])?); - assert!(accumulate_all_non_distinct(&[equal_nulls])?); - assert!(accumulate_all_non_distinct(&[equal_inner])?); - Ok(()) + assert_matches_baseline(&lv_u8, &lv_i16) } -#[rstest] -#[case::equal_with_null(vec![Some(1i32), None], vec![Some(1i32), None], true)] -#[case::distinct_null_vs_val(vec![Some(1i32), None], vec![Some(1i32), Some(2i32)], false)] -fn constant_struct_list_with_null_elements( - #[case] lhs_elems: Vec>, - #[case] rhs_elems: Vec>, - #[case] expected: bool, -) -> VortexResult<()> { - let elem_dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let list_dtype = DType::list(elem_dtype.clone(), Nullability::NonNullable); - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![list_dtype.clone(), list_dtype], - ), - Nullability::NonNullable, - ); - let to_list = |elems: Vec>| { - let scalars: Vec = elems - .into_iter() - .map(|v| match v { - Some(n) => Scalar::primitive(n, Nullability::Nullable), - None => Scalar::null(elem_dtype.clone()), - }) - .collect(); - Scalar::list(elem_dtype.clone(), scalars, Nullability::NonNullable) - }; - let batch = ConstantArray::new( - Scalar::struct_(pair_dtype, [to_list(lhs_elems), to_list(rhs_elems)]), - 3, +#[test] +fn accumulator_constant_struct_saturation_and_nested_nulls() -> VortexResult<()> { + let eq = const_pair(Scalar::from(1i32), Scalar::from(1i32), 2); + let ne = const_pair(Scalar::from(1i32), Scalar::from(2i32), 2); + assert!(accumulate_all_non_distinct(&[const_pair( + Scalar::from(1i32), + Scalar::from(2i32), + 0 + )])?); + assert!(!accumulate_all_non_distinct(&[eq.clone(), ne, eq])?); + + let outer_null = ConstantArray::new( + Scalar::null(pair_dtype( + &DType::Primitive(PType::I32, Nullability::NonNullable), + Nullability::Nullable, + )), + 4, ) .into_array(); - - assert_eq!(accumulate_all_non_distinct(&[batch])?, expected); + assert!(accumulate_all_non_distinct(&[outer_null])?); + + // Null nested struct is distinct from non-null struct with null field. + let inner_field = DType::Primitive(PType::I32, Nullability::Nullable); + let inner_dt = DType::struct_([("x", inner_field.clone())], Nullability::Nullable); + let null_s = Scalar::null(inner_dt.clone()); + let of_null = Scalar::struct_(inner_dt, [Scalar::null(inner_field)]); + assert!(!accumulate_all_non_distinct(&[const_pair( + null_s.clone(), + of_null.clone(), + 3 + )])?); + assert!(accumulate_all_non_distinct(&[const_pair( + null_s.clone(), + null_s, + 3 + )])?); + assert!(accumulate_all_non_distinct(&[const_pair( + of_null.clone(), + of_null, + 3 + )])?); Ok(()) } #[test] -fn constant_struct_union_fields() -> VortexResult<()> { - let variants = crate::dtype::UnionVariants::try_new( +fn union_constant_fields_and_shared_null_inactive_payload() -> VortexResult<()> { + let variants = UnionVariants::try_new( FieldNames::from(["int", "text"]), vec![ DType::Primitive(PType::I32, Nullability::NonNullable), @@ -1047,69 +390,48 @@ fn constant_struct_union_fields() -> VortexResult<()> { ], vec![5, 9], )?; - let union_dtype = DType::Union(variants.clone(), Nullability::NonNullable); - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![union_dtype.clone(), union_dtype], - ), - Nullability::NonNullable, - ); - - let int_10 = Scalar::union( + let i10 = Scalar::union( variants.clone(), 5, Scalar::from(10i32), Nullability::NonNullable, )?; - let int_30 = Scalar::union( + let i30 = Scalar::union( variants.clone(), 5, Scalar::from(30i32), Nullability::NonNullable, )?; - let text_a = Scalar::union(variants, 9, Scalar::from("a"), Nullability::NonNullable)?; - - let equal = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [int_10.clone(), int_10.clone()]), - 3, - ) - .into_array(); - let distinct_payload = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [int_10.clone(), int_30]), - 3, - ) - .into_array(); - let distinct_tag = - ConstantArray::new(Scalar::struct_(pair_dtype, [int_10, text_a]), 3).into_array(); - - assert!(accumulate_all_non_distinct(&[equal])?); - assert!(!accumulate_all_non_distinct(&[distinct_payload])?); - assert!(!accumulate_all_non_distinct(&[distinct_tag])?); - Ok(()) -} - -#[test] -fn union_shared_null_ignores_inactive_payload() -> VortexResult<()> { - let variants = crate::dtype::UnionVariants::try_new( + let ta = Scalar::union(variants, 9, Scalar::from("a"), Nullability::NonNullable)?; + + assert!(accumulate_all_non_distinct(&[const_pair( + i10.clone(), + i10.clone(), + 3 + )])?); + assert!(!accumulate_all_non_distinct(&[const_pair( + i10.clone(), + i30, + 3 + )])?); + assert!(!accumulate_all_non_distinct(&[const_pair(i10, ta, 3)])?); + + // Shared outer null in UnionArray ignores differing inactive child payloads. + let single = UnionVariants::try_new( FieldNames::from(["int"]), vec![DType::Primitive(PType::I32, Nullability::NonNullable)], vec![0], )?; - let null_type_ids = - PrimitiveArray::new(buffer![0u8], Validity::from_iter([false])).into_array(); - let lhs = crate::arrays::UnionArray::try_new( - null_type_ids.clone(), - variants.clone(), - vec![buffer![10i32].into_array()], - )? - .into_array(); - let rhs = crate::arrays::UnionArray::try_new( - null_type_ids, - variants, - vec![buffer![20i32].into_array()], - )? - .into_array(); + let null_ids = PrimitiveArray::new(buffer![0u8], Validity::from_iter([false])).into_array(); + let [lhs, rhs] = [10i32, 20].map(|v| { + UnionArray::try_new( + null_ids.clone(), + single.clone(), + vec![buffer![v].into_array()], + ) + .vortex_expect("union") + .into_array() + }); let batch = StructArray::try_new( FieldNames::from(["lhs", "rhs"]), vec![lhs, rhs], @@ -1117,158 +439,87 @@ fn union_shared_null_ignores_inactive_payload() -> VortexResult<()> { Validity::NonNullable, )? .into_array(); - assert!(accumulate_all_non_distinct(&[batch])?); Ok(()) } #[test] -fn constant_struct_multiple_batches_saturates() -> VortexResult<()> { - let field_dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let struct_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![field_dtype.clone(), field_dtype], - ), - Nullability::NonNullable, - ); - let equal = ConstantArray::new( - Scalar::struct_( - struct_dtype.clone(), - [Scalar::from(1i32), Scalar::from(1i32)], - ), - 2, - ) - .into_array(); - let distinct = ConstantArray::new( - Scalar::struct_(struct_dtype, [Scalar::from(1i32), Scalar::from(2i32)]), - 2, - ) - .into_array(); - - assert!(!accumulate_all_non_distinct(&[ - equal.clone(), - distinct, - equal - ])?); - Ok(()) -} - -#[test] -fn test_variant_reordered_object_fields_match_across_canonical_and_constant() -> VortexResult<()> { - let lhs_obj_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["a", "b"]), - vec![ - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::NonNullable), - ], - ), +fn variant_reordered_fields_repeated_names_map_and_ext_storage() -> VortexResult<()> { + let lhs_obj = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Utf8(Nullability::NonNullable)), + ], Nullability::NonNullable, ); - let rhs_obj_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["b", "a"]), - vec![ - DType::Utf8(Nullability::NonNullable), - DType::Primitive(PType::I32, Nullability::NonNullable), - ], - ), + let rhs_obj = DType::struct_( + [ + ("b", DType::Utf8(Nullability::NonNullable)), + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ], Nullability::NonNullable, ); - - let lhs_scalar = Scalar::variant(Scalar::struct_( - lhs_obj_dtype, + let lhs_v = Scalar::variant(Scalar::struct_( + lhs_obj, [Scalar::from(1i32), Scalar::from("x")], )); - let rhs_scalar_equal = Scalar::variant(Scalar::struct_( - rhs_obj_dtype.clone(), + let rhs_eq = Scalar::variant(Scalar::struct_( + rhs_obj.clone(), [Scalar::from("x"), Scalar::from(1i32)], )); - let rhs_scalar_distinct = Scalar::variant(Scalar::struct_( - rhs_obj_dtype, + let rhs_ne = Scalar::variant(Scalar::struct_( + rhs_obj, [Scalar::from("y"), Scalar::from(1i32)], )); - assert!(variant_scalars_equal(&lhs_scalar, &rhs_scalar_equal)); - assert!(!variant_scalars_equal(&lhs_scalar, &rhs_scalar_distinct)); - - let lhs_variant = - VariantArray::try_new(ConstantArray::new(lhs_scalar.clone(), 2).into_array(), None)? - .into_array(); - let rhs_variant_equal = VariantArray::try_new( - ConstantArray::new(rhs_scalar_equal.clone(), 2).into_array(), - None, - )? - .into_array(); - let rhs_variant_distinct = VariantArray::try_new( - ConstantArray::new(rhs_scalar_distinct.clone(), 2).into_array(), - None, - )? - .into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - assert!(all_non_distinct( - &lhs_variant, - &rhs_variant_equal, - &mut ctx - )?); - assert!(!all_non_distinct( - &lhs_variant, - &rhs_variant_distinct, - &mut ctx - )?); - - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![ - DType::Variant(Nullability::NonNullable), - DType::Variant(Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ); - let const_equal = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [lhs_scalar.clone(), rhs_scalar_equal]), - 3, - ) - .into_array(); - let const_distinct = ConstantArray::new( - Scalar::struct_(pair_dtype, [lhs_scalar, rhs_scalar_distinct]), - 3, - ) - .into_array(); - - assert!(accumulate_all_non_distinct(&[const_equal])?); - assert!(!accumulate_all_non_distinct(&[const_distinct])?); - Ok(()) -} + assert!(variant_scalars_equal(&lhs_v, &rhs_eq)); + assert!(!variant_scalars_equal(&lhs_v, &rhs_ne)); -#[test] -fn test_variant_map_reordered_object_fields_match_across_canonical_and_constant() -> VortexResult<()> -{ - let lhs_obj_dtype = DType::Struct( + // Repeated field names compare positionally per name occurrence. + let dup_dt = DType::Struct( StructFields::new( - FieldNames::from(["a", "b"]), + FieldNames::from(["a", "a"]), vec![ DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ); - let rhs_obj_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["b", "a"]), - vec![ - DType::Utf8(Nullability::NonNullable), DType::Primitive(PType::I32, Nullability::NonNullable), ], ), Nullability::NonNullable, ); + let [d12, d21, d11] = [(1, 2), (2, 1), (1, 1)].map(|(x, y)| { + Scalar::variant(Scalar::struct_( + dup_dt.clone(), + [Scalar::from(x), Scalar::from(y)], + )) + }); + assert!(variant_scalars_equal(&d12, &d12)); + assert!(!variant_scalars_equal(&d11, &d12)); + assert!(!variant_scalars_equal(&d12, &d21)); + + // Direct VariantArray comparison + Constant/Canonical parity across Variant, Map, and Extension. + let mut ctx = SESSION.create_execution_ctx(); + let [v_lhs, v_eq, v_ne] = [&lhs_v, &rhs_eq, &rhs_ne].map(|s| { + VariantArray::try_new(ConstantArray::new(s.clone(), 2).into_array(), None) + .vortex_expect("variant") + .into_array() + }); + assert!(all_non_distinct(&v_lhs, &v_eq, &mut ctx)?); + assert!(!all_non_distinct(&v_lhs, &v_ne, &mut ctx)?); + + let mut check = |lhs: Scalar, eq: Scalar, ne: Scalar| -> VortexResult<()> { + let c_eq = const_pair(lhs.clone(), eq, 2); + let c_ne = const_pair(lhs, ne, 2); + let k_eq = c_eq.clone().execute::(&mut ctx)?.into_array(); + let k_ne = c_ne.clone().execute::(&mut ctx)?.into_array(); + assert!(accumulate_all_non_distinct(&[c_eq])?); + assert!(accumulate_all_non_distinct(&[k_eq])?); + assert!(!accumulate_all_non_distinct(&[c_ne])?); + assert!(!accumulate_all_non_distinct(&[k_ne])?); + Ok(()) + }; + + check(lhs_v.clone(), rhs_eq.clone(), rhs_ne.clone())?; - let map_dtype = DType::Map( + let map_dt = DType::Map( MapDType::try_new( DType::Utf8(Nullability::NonNullable), DType::Variant(Nullability::NonNullable), @@ -1276,178 +527,18 @@ fn test_variant_map_reordered_object_fields_match_across_canonical_and_constant( )?, Nullability::NonNullable, ); - - let lhs_map = Scalar::map( - map_dtype.clone(), - [( - Scalar::from("k"), - Scalar::variant(Scalar::struct_( - lhs_obj_dtype, - [Scalar::from(1i32), Scalar::from("x")], - )), - )], - ); - let rhs_map_equal = Scalar::map( - map_dtype.clone(), - [( - Scalar::from("k"), - Scalar::variant(Scalar::struct_( - rhs_obj_dtype.clone(), - [Scalar::from("x"), Scalar::from(1i32)], - )), - )], - ); - let rhs_map_distinct = Scalar::map( - map_dtype.clone(), - [( - Scalar::from("k"), - Scalar::variant(Scalar::struct_( - rhs_obj_dtype, - [Scalar::from("y"), Scalar::from(1i32)], - )), - )], - ); - - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![map_dtype.clone(), map_dtype], - ), - Nullability::NonNullable, - ); - let const_equal = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [lhs_map.clone(), rhs_map_equal]), - 2, - ) - .into_array(); - let const_distinct = - ConstantArray::new(Scalar::struct_(pair_dtype, [lhs_map, rhs_map_distinct]), 2) - .into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - let canon_equal = const_equal - .clone() - .execute::(&mut ctx)? - .into_array(); - let canon_distinct = const_distinct - .clone() - .execute::(&mut ctx)? - .into_array(); - - assert!(accumulate_all_non_distinct(&[const_equal])?); - assert!(accumulate_all_non_distinct(&[canon_equal])?); - assert!(!accumulate_all_non_distinct(&[const_distinct])?); - assert!(!accumulate_all_non_distinct(&[canon_distinct])?); - Ok(()) -} - -#[test] -fn test_variant_repeated_field_names_and_extension_storage() -> VortexResult<()> { - let dup_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["a", "a"]), - vec![ - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Primitive(PType::I32, Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ); - let dup_1_2 = Scalar::variant(Scalar::struct_( - dup_dtype.clone(), - [Scalar::from(1i32), Scalar::from(2i32)], - )); - let dup_2_1 = Scalar::variant(Scalar::struct_( - dup_dtype.clone(), - [Scalar::from(2i32), Scalar::from(1i32)], - )); - let dup_1_1 = Scalar::variant(Scalar::struct_( - dup_dtype, - [Scalar::from(1i32), Scalar::from(1i32)], - )); - - assert!(variant_scalars_equal(&dup_1_2, &dup_1_2)); - assert!(!variant_scalars_equal(&dup_1_1, &dup_1_2)); - assert!(!variant_scalars_equal(&dup_1_2, &dup_2_1)); + check( + Scalar::map(map_dt.clone(), [(Scalar::from("k"), lhs_v.clone())]), + Scalar::map(map_dt.clone(), [(Scalar::from("k"), rhs_eq.clone())]), + Scalar::map(map_dt, [(Scalar::from("k"), rhs_ne.clone())]), + )?; static ID: CachedId = CachedId::new("test.variant_ext"); - let ext_dtype = + let ext_dt = ForeignExtDType::from_parts(*ID, Vec::new(), DType::Variant(Nullability::NonNullable))?; - let lhs_obj_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["a", "b"]), - vec![ - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ); - let rhs_obj_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["b", "a"]), - vec![ - DType::Utf8(Nullability::NonNullable), - DType::Primitive(PType::I32, Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ); - - let lhs_ext = Scalar::extension_ref( - ext_dtype.clone(), - Scalar::variant(Scalar::struct_( - lhs_obj_dtype, - [Scalar::from(1i32), Scalar::from("x")], - )), - ); - let rhs_ext_equal = Scalar::extension_ref( - ext_dtype.clone(), - Scalar::variant(Scalar::struct_( - rhs_obj_dtype.clone(), - [Scalar::from("x"), Scalar::from(1i32)], - )), - ); - let rhs_ext_distinct = Scalar::extension_ref( - ext_dtype.clone(), - Scalar::variant(Scalar::struct_( - rhs_obj_dtype, - [Scalar::from("y"), Scalar::from(1i32)], - )), - ); - - let pair_dtype = DType::Struct( - StructFields::new( - FieldNames::from(["lhs", "rhs"]), - vec![ - DType::Extension(ext_dtype.clone()), - DType::Extension(ext_dtype), - ], - ), - Nullability::NonNullable, - ); - let const_equal = ConstantArray::new( - Scalar::struct_(pair_dtype.clone(), [lhs_ext.clone(), rhs_ext_equal]), - 2, + check( + Scalar::extension_ref(ext_dt.clone(), lhs_v), + Scalar::extension_ref(ext_dt.clone(), rhs_eq), + Scalar::extension_ref(ext_dt, rhs_ne), ) - .into_array(); - let const_distinct = - ConstantArray::new(Scalar::struct_(pair_dtype, [lhs_ext, rhs_ext_distinct]), 2) - .into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - let canon_equal = const_equal - .clone() - .execute::(&mut ctx)? - .into_array(); - let canon_distinct = const_distinct - .clone() - .execute::(&mut ctx)? - .into_array(); - - assert!(accumulate_all_non_distinct(&[const_equal])?); - assert!(accumulate_all_non_distinct(&[canon_equal])?); - assert!(!accumulate_all_non_distinct(&[const_distinct])?); - assert!(!accumulate_all_non_distinct(&[canon_distinct])?); - Ok(()) } diff --git a/vortex-array/src/scalar/mod.rs b/vortex-array/src/scalar/mod.rs index 4a45e202ad5..5541fcf0226 100644 --- a/vortex-array/src/scalar/mod.rs +++ b/vortex-array/src/scalar/mod.rs @@ -50,4 +50,4 @@ pub struct Scalar { } #[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/vortex-array/src/scalar/proto.rs b/vortex-array/src/scalar/proto.rs index 119c2c3362a..e2e5a72b50d 100644 --- a/vortex-array/src/scalar/proto.rs +++ b/vortex-array/src/scalar/proto.rs @@ -532,17 +532,10 @@ fn union_from_proto( #[cfg(test)] mod tests { - use std::f32; - use std::f64; - use std::sync::Arc; - - use vortex_buffer::BufferString; - use vortex_error::vortex_panic; use vortex_session::VortexSession; use super::*; use crate::dtype::DType; - use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::UnionVariants; @@ -551,7 +544,6 @@ mod tests { use crate::dtype::extension::ExtVTable; use crate::dtype::half::f16; use crate::proto::scalar as pb; - use crate::scalar::DecimalValue; use crate::scalar::Scalar; use crate::scalar::ScalarValue; use crate::scalar_fn::ScalarFnVTable; @@ -561,193 +553,8 @@ mod tests { VortexSession::empty() } - fn round_trip(scalar: Scalar) { - let decoded = Scalar::from_proto(&pb::Scalar::from(&scalar), &session()).unwrap(); - assert_eq!(decoded.dtype(), scalar.dtype()); - assert_eq!(decoded, scalar); - } - - #[test] - fn test_null() { - round_trip(Scalar::null(DType::Null)); - } - - #[test] - fn test_bool() { - round_trip(Scalar::new( - DType::Bool(Nullability::Nullable), - Some(ScalarValue::Bool(true)), - )); - } - - #[test] - fn test_primitive() { - round_trip(Scalar::new( - DType::Primitive(PType::I32, Nullability::Nullable), - Some(ScalarValue::Primitive(42i32.into())), - )); - } - - #[test] - fn test_buffer() { - round_trip(Scalar::new( - DType::Binary(Nullability::Nullable), - Some(ScalarValue::Binary(vec![1, 2, 3].into())), - )); - } - - #[test] - fn test_buffer_string() { - round_trip(Scalar::new( - DType::Utf8(Nullability::Nullable), - Some(ScalarValue::Utf8(BufferString::from("hello".to_string()))), - )); - } - - #[test] - fn test_list() { - round_trip(Scalar::new( - DType::List( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - Nullability::Nullable, - ), - Some(ScalarValue::Tuple(vec![ - Some(ScalarValue::Primitive(42i32.into())), - Some(ScalarValue::Primitive(43i32.into())), - ])), - )); - } - - #[test] - fn test_map() { - let dtype = DType::map( - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::Nullable), - true, - Nullability::Nullable, - ) - .unwrap(); - round_trip( - Scalar::try_map( - dtype.clone(), - [ - ( - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::utf8("one", Nullability::Nullable), - ), - ( - Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::null(DType::Utf8(Nullability::Nullable)), - ), - ], - ) - .unwrap(), - ); - round_trip(Scalar::null(dtype)); - } - - #[test] - fn test_f16() { - round_trip(Scalar::primitive( - f16::from_f32(0.42), - Nullability::Nullable, - )); - } - - #[test] - fn test_i8() { - round_trip(Scalar::new( - DType::Primitive(PType::I8, Nullability::Nullable), - Some(ScalarValue::Primitive(i8::MIN.into())), - )); - - round_trip(Scalar::new( - DType::Primitive(PType::I8, Nullability::Nullable), - Some(ScalarValue::Primitive(0i8.into())), - )); - - round_trip(Scalar::new( - DType::Primitive(PType::I8, Nullability::Nullable), - Some(ScalarValue::Primitive(i8::MAX.into())), - )); - } - - #[test] - fn test_decimal_i32_roundtrip() { - // A typical decimal with moderate precision and scale. - round_trip(Scalar::decimal( - DecimalValue::I32(123_456), - DecimalDType::new(10, 2), - Nullability::NonNullable, - )); - } - - #[test] - fn test_decimal_i128_roundtrip() { - // A large decimal value that requires i128 storage. - round_trip(Scalar::decimal( - DecimalValue::I128(99_999_999_999_999_999_999), - DecimalDType::new(38, 6), - Nullability::Nullable, - )); - } - #[test] - fn test_decimal_null_roundtrip() { - round_trip(Scalar::null(DType::Decimal( - DecimalDType::new(10, 2), - Nullability::Nullable, - ))); - } - - #[test] - fn test_scalar_value_serde_roundtrip_binary() { - round_trip(Scalar::binary( - ByteBuffer::copy_from(b"hello"), - Nullability::NonNullable, - )); - } - - #[test] - fn test_scalar_value_serde_roundtrip_utf8() { - round_trip(Scalar::utf8("hello", Nullability::NonNullable)); - } - - #[test] - fn test_variant_scalar_roundtrip() { - let nums = Scalar::list( - Arc::new(DType::Variant(Nullability::NonNullable)), - vec![ - Scalar::variant(Scalar::primitive(-7_i16, Nullability::NonNullable)), - Scalar::variant(Scalar::primitive(42_u32, Nullability::NonNullable)), - Scalar::variant(Scalar::decimal( - DecimalValue::I128(123_456_789), - DecimalDType::new(18, 0), - Nullability::NonNullable, - )), - ], - Nullability::NonNullable, - ); - - let nested = Scalar::list( - Arc::new(DType::Variant(Nullability::NonNullable)), - vec![ - Scalar::variant(Scalar::from(true)), - Scalar::variant(nums), - Scalar::variant(Scalar::binary( - ByteBuffer::copy_from(b"abc"), - Nullability::NonNullable, - )), - Scalar::variant(Scalar::null(DType::Null)), - ], - Nullability::NonNullable, - ); - - round_trip(Scalar::variant(nested)); - } - - #[test] - fn test_variant_scalar_proto_preserves_scalar_null_vs_variant_null() { + fn test_variant_scalar_proto_preserves_scalar_null_vs_variant_null() -> VortexResult<()> { let scalar_null = Scalar::null(DType::Variant(Nullability::Nullable)); let variant_null = Scalar::variant(Scalar::null(DType::Null)); @@ -756,17 +563,18 @@ mod tests { assert_ne!(scalar_null_pb, variant_null_pb); assert_eq!( - Scalar::from_proto(&scalar_null_pb, &session()).unwrap(), - scalar_null, + Scalar::from_proto(&scalar_null_pb, &session())?, + scalar_null ); assert_eq!( - Scalar::from_proto(&variant_null_pb, &session()).unwrap(), - variant_null, + Scalar::from_proto(&variant_null_pb, &session())?, + variant_null ); + Ok(()) } #[test] - fn test_union_scalar_roundtrip() -> VortexResult<()> { + fn test_union_proto_distinguishes_inner_and_outer_null() -> VortexResult<()> { let variants = UnionVariants::try_new( ["int", "string"].into(), vec![ @@ -776,13 +584,6 @@ mod tests { vec![5, 9], )?; - round_trip(Scalar::union( - variants.clone(), - 5, - Scalar::primitive(42_i32, Nullability::Nullable), - Nullability::Nullable, - )?); - let inner_null = Scalar::union( variants.clone(), 5, @@ -790,7 +591,6 @@ mod tests { Nullability::Nullable, )?; let inner_null_proto = pb::Scalar::from(&inner_null); - assert!(matches!( inner_null_proto .value @@ -805,6 +605,7 @@ mod tests { Some(Kind::NullValue(_)) ) )); + let outer_null = Scalar::null(DType::Union(variants, Nullability::Nullable)); let outer_null_proto = pb::Scalar::from(&outer_null); assert!(matches!( @@ -814,37 +615,15 @@ mod tests { .and_then(|value| value.kind.as_ref()), Some(Kind::NullValue(_)) )); - assert_ne!(inner_null_proto, outer_null_proto); - round_trip(inner_null); - round_trip(outer_null); - - let struct_dtype = DType::struct_( - [ - ( - "number", - DType::Primitive(PType::I32, Nullability::NonNullable), - ), - ("label", DType::Utf8(Nullability::Nullable)), - ], - Nullability::NonNullable, + assert_eq!( + Scalar::from_proto(&inner_null_proto, &session())?, + inner_null ); - let struct_scalar = Scalar::struct_( - struct_dtype.clone(), - [ - Scalar::primitive(42_i32, Nullability::NonNullable), - Scalar::utf8("answer", Nullability::Nullable), - ], + assert_eq!( + Scalar::from_proto(&outer_null_proto, &session())?, + outer_null ); - let struct_variants = - UnionVariants::try_new(["record"].into(), vec![struct_dtype], vec![13])?; - round_trip(Scalar::union( - struct_variants, - 13, - struct_scalar, - Nullability::NonNullable, - )?); - Ok(()) } @@ -865,7 +644,6 @@ mod tests { ))), }))), }; - assert!(ScalarValue::from_proto(&unknown_tag, &dtype, &session()).is_err()); let missing_child = pb::ScalarValue { @@ -874,7 +652,6 @@ mod tests { value: None, }))), }; - let err = ScalarValue::from_proto(&missing_child, &dtype, &session()) .unwrap_err() .to_string(); @@ -888,7 +665,6 @@ mod tests { ))), }))), }; - let err = ScalarValue::from_proto(&wrong_child_value, &dtype, &session()) .unwrap_err() .to_string(); @@ -896,305 +672,59 @@ mod tests { err.contains("expected Utf8 or Binary dtype for StringValue, got i32?"), "{err}" ); - Ok(()) } #[test] - fn test_backcompat_f16_serialized_as_u64() { - // Backwards compatibility test for the legacy f16 serialization format. - // - // Previously, f16 ScalarValues were serialized as `Uint64Value(v.to_bits() as u64)` because - // the proto schema only had 64-bit integer types, and f16's underlying representation is - // u16 which got widened to u64. - // - // The current implementation uses a dedicated `F16Value` proto field, but we must still be - // able to deserialize the old format. This test verifies that: - // - // 1. A `Uint64Value` containing f16 bits can be read as a U64 primitive (the raw bits). - // 2. When wrapped in a Scalar with F16 dtype, the value is correctly interpreted as f16. - // - // This ensures data written with the old serialization format remains readable. - - // Simulate the old serialization: f16(0.42) stored as Uint64Value with its bit pattern. + fn test_backcompat_f16_serialized_as_u64() -> VortexResult<()> { + // Legacy format serialized f16 bit patterns as Uint64Value. let f16_value = f16::from_f32(0.42); - let f16_bits_as_u64 = f16_value.to_bits() as u64; // 14008 - let pb_scalar_value = pb::ScalarValue { - kind: Some(Kind::Uint64Value(f16_bits_as_u64)), + kind: Some(Kind::Uint64Value(u64::from(f16_value.to_bits()))), }; - // Step 1: Verify the normal U64 scalar. - let scalar_value = ScalarValue::from_proto( + let u64_val = ScalarValue::from_proto( &pb_scalar_value, &DType::Primitive(PType::U64, Nullability::NonNullable), &session(), - ) - .unwrap(); + )?; assert_eq!( - scalar_value.as_ref().map(|v| v.as_primitive()), - Some(&PValue::U64(14008u64)), + u64_val.as_ref().map(|v| v.as_primitive()), + Some(&PValue::U64(u64::from(f16_value.to_bits()))), ); - // Step 2: Verify that when we use F16 dtype, the Uint64Value is correctly interpreted. - let scalar_value_f16 = ScalarValue::from_proto( + let f16_val = ScalarValue::from_proto( &pb_scalar_value, &DType::Primitive(PType::F16, Nullability::Nullable), &session(), - ) - .unwrap(); - - let scalar = Scalar::new( - DType::Primitive(PType::F16, Nullability::Nullable), - scalar_value_f16, - ); - - assert_eq!( - scalar.as_primitive().pvalue().unwrap(), - PValue::F16(f16::from_f32(0.42)), - "Uint64Value should be correctly interpreted as f16 when dtype is F16" - ); - } - - #[test] - fn test_scalar_value_direct_roundtrip_f16() { - // Test that ScalarValue with f16 roundtrips correctly without going through Scalar. - let f16_values = vec![ - f16::from_f32(0.0), - f16::from_f32(1.0), - f16::from_f32(-1.0), - f16::from_f32(0.42), - f16::from_f32(5.722046e-6), - f16::from_f32(f32::consts::PI), - f16::INFINITY, - f16::NEG_INFINITY, - f16::NAN, - ]; - - for f16_val in f16_values { - let scalar_value = ScalarValue::Primitive(PValue::F16(f16_val)); - let pb_value = ScalarValue::to_proto(Some(&scalar_value)); - let read_back = ScalarValue::from_proto( - &pb_value, - &DType::Primitive(PType::F16, Nullability::NonNullable), - &session(), - ) - .unwrap(); - - match (&scalar_value, read_back.as_ref()) { - ( - ScalarValue::Primitive(PValue::F16(original)), - Some(ScalarValue::Primitive(PValue::F16(roundtripped))), - ) => { - if original.is_nan() && roundtripped.is_nan() { - // NaN values are equal for our purposes. - continue; - } - assert_eq!( - original, roundtripped, - "F16 value {original:?} did not roundtrip correctly" - ); - } - _ => { - vortex_panic!( - "Expected f16 primitive values, got {scalar_value:?} and {read_back:?}" - ) - } - } - } - } - - #[test] - fn test_scalar_value_direct_roundtrip_preserves_values() { - // Test that ScalarValue roundtripping preserves values (but not necessarily exact types). - // Note: Proto encoding consolidates integer types (u8/u16/u32 → u64, i8/i16/i32 → i64). - - // Test cases that should roundtrip exactly. - let exact_roundtrip_cases: Vec<(&str, Option, DType)> = vec![ - ("null", None, DType::Null), - ( - "bool_true", - Some(ScalarValue::Bool(true)), - DType::Bool(Nullability::Nullable), - ), - ( - "bool_false", - Some(ScalarValue::Bool(false)), - DType::Bool(Nullability::Nullable), - ), - ( - "u64", - Some(ScalarValue::Primitive(PValue::U64(18446744073709551615))), - DType::Primitive(PType::U64, Nullability::Nullable), - ), - ( - "i64", - Some(ScalarValue::Primitive(PValue::I64(-9223372036854775808))), - DType::Primitive(PType::I64, Nullability::Nullable), - ), - ( - "f32", - Some(ScalarValue::Primitive(PValue::F32(f32::consts::E))), - DType::Primitive(PType::F32, Nullability::Nullable), - ), - ( - "f64", - Some(ScalarValue::Primitive(PValue::F64(f64::consts::PI))), - DType::Primitive(PType::F64, Nullability::Nullable), - ), - ( - "string", - Some(ScalarValue::Utf8(BufferString::from("test"))), - DType::Utf8(Nullability::Nullable), - ), - ( - "bytes", - Some(ScalarValue::Binary(vec![1, 2, 3, 4, 5].into())), - DType::Binary(Nullability::Nullable), - ), - ]; - - for (name, value, dtype) in exact_roundtrip_cases { - let pb_value = ScalarValue::to_proto(value.as_ref()); - let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap(); - - let original_debug = format!("{value:?}"); - let roundtrip_debug = format!("{read_back:?}"); - assert_eq!( - original_debug, roundtrip_debug, - "ScalarValue {name} did not roundtrip exactly" - ); - } - - // The wire format widens integers; decoding must restore their original widths. - let unsigned_cases = vec![ - ( - "u8", - ScalarValue::Primitive(PValue::U8(255)), - DType::Primitive(PType::U8, Nullability::Nullable), - 255u64, - ), - ( - "u16", - ScalarValue::Primitive(PValue::U16(65535)), - DType::Primitive(PType::U16, Nullability::Nullable), - 65535u64, - ), - ( - "u32", - ScalarValue::Primitive(PValue::U32(4294967295)), - DType::Primitive(PType::U32, Nullability::Nullable), - 4294967295u64, - ), - ]; - - for (name, value, dtype, expected) in unsigned_cases { - let pb_value = ScalarValue::to_proto(Some(&value)); - let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap(); - - match read_back.as_ref() { - Some(ScalarValue::Primitive(pv)) => { - assert_eq!(pv.ptype(), dtype.as_ptype(), "{name} primitive width"); - let v = match pv { - PValue::U8(v) => *v as u64, - PValue::U16(v) => *v as u64, - PValue::U32(v) => *v as u64, - PValue::U64(v) => *v, - _ => { - vortex_panic!("Unexpected primitive type for {name}: {pv:?}") - } - }; - assert_eq!( - v, expected, - "ScalarValue {name} value not preserved: expected {expected}, got {v}" - ); - } - _ => { - vortex_panic!("Unexpected type after roundtrip for {name}: {read_back:?}") - } - } - } - - // Signed integers must also recover their original widths. - let signed_cases = vec![ - ( - "i8", - ScalarValue::Primitive(PValue::I8(-128)), - DType::Primitive(PType::I8, Nullability::Nullable), - -128i64, - ), - ( - "i16", - ScalarValue::Primitive(PValue::I16(-32768)), - DType::Primitive(PType::I16, Nullability::Nullable), - -32768i64, - ), - ( - "i32", - ScalarValue::Primitive(PValue::I32(-2147483648)), - DType::Primitive(PType::I32, Nullability::Nullable), - -2147483648i64, - ), - ]; - - for (name, value, dtype, expected) in signed_cases { - let pb_value = ScalarValue::to_proto(Some(&value)); - let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap(); - - match read_back.as_ref() { - Some(ScalarValue::Primitive(pv)) => { - assert_eq!(pv.ptype(), dtype.as_ptype(), "{name} primitive width"); - let v = match pv { - PValue::I8(v) => *v as i64, - PValue::I16(v) => *v as i64, - PValue::I32(v) => *v as i64, - PValue::I64(v) => *v, - _ => { - vortex_panic!("Unexpected primitive type for {name}: {pv:?}") - } - }; - assert_eq!( - v, expected, - "ScalarValue {name} value not preserved: expected {expected}, got {v}" - ); - } - _ => { - vortex_panic!("Unexpected type after roundtrip for {name}: {read_back:?}") - } - } - } + )?; + let scalar = Scalar::try_new(DType::Primitive(PType::F16, Nullability::Nullable), f16_val)?; + assert_eq!(scalar.as_primitive().pvalue(), Some(PValue::F16(f16_value))); + Ok(()) } - // Backwards compatibility: signed integer stats could previously be serialized as unsigned. - // Therefore, we allow casting between signed and unsigned integers of the same bit width. #[test] - fn test_backcompat_signed_integer_deserialized_as_unsigned() { - let v = ScalarValue::Primitive(PValue::I64(0)); + fn test_backcompat_signed_unsigned_integer_stats() -> VortexResult<()> { + let i64_val = ScalarValue::Primitive(PValue::I64(0)); assert_eq!( Scalar::from_proto_value( - &pb::ScalarValue::from(&v), + &pb::ScalarValue::from(&i64_val), &DType::Primitive(PType::U64, Nullability::Nullable), - &session() - ) - .unwrap(), + &session(), + )?, Scalar::primitive(0u64, Nullability::Nullable) ); - } - // Backwards compatibility: unsigned integer stats could previously be serialized as signed. - // Therefore, we allow casting between signed and unsigned integers of the same bit width. - #[test] - fn test_backcompat_unsigned_integer_deserialized_as_signed() { - let v = ScalarValue::Primitive(PValue::U64(0)); + let u64_val = ScalarValue::Primitive(PValue::U64(0)); assert_eq!( Scalar::from_proto_value( - &pb::ScalarValue::from(&v), + &pb::ScalarValue::from(&u64_val), &DType::Primitive(PType::I64, Nullability::Nullable), - &session() - ) - .unwrap(), + &session(), + )?, Scalar::primitive(0i64, Nullability::Nullable) ); + Ok(()) } /// An extension type whose metadata serializer always fails, standing in for a plugin. @@ -1248,17 +778,15 @@ mod tests { } #[test] - fn to_proto_propagates_extension_metadata_error() { - let err = failing_metadata_scalar().to_proto().unwrap_err(); + fn to_proto_and_literal_propagate_extension_metadata_error() { + let scalar = failing_metadata_scalar(); + let err = scalar.to_proto().unwrap_err(); assert!( err.to_string().contains("metadata serializer failed"), "{err}" ); - } - #[test] - fn literal_serializer_propagates_extension_metadata_error() { - let err = Literal.serialize(&failing_metadata_scalar()).unwrap_err(); + let err = Literal.serialize(&scalar).unwrap_err(); assert!( err.to_string().contains("metadata serializer failed"), "{err}" diff --git a/vortex-array/src/scalar/tests/casting.rs b/vortex-array/src/scalar/tests/casting.rs index 37acb06add9..088607d52ec 100644 --- a/vortex-array/src/scalar/tests/casting.rs +++ b/vortex-array/src/scalar/tests/casting.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for type casting and coercion between different scalar types. +//! Focused corner-case tests for scalar casting (`f16` legacy bits, `bool -> primitive`, +//! extension storage guards, and `Union` nullability/schema rules). #[cfg(test)] mod tests { - use std::f32; use std::sync::Arc; use rstest::rstest; @@ -30,9 +30,6 @@ mod tests { struct Apples; impl ExtVTable for Apples { - // The metadata is the storage dtype, so the tests can wrap any storage dtype. It is the - // nullable form of that dtype, because the extension dtype applies the top-level - // nullability. type Metadata = DType; type StoredMetadata = (); type NativeValue<'a> = &'a str; @@ -71,7 +68,6 @@ mod tests { } impl Apples { - /// An `Apples` dtype with the supplied storage, reconstructed through the read path. fn new(storage_dtype: DType) -> ExtDType { ExtDType::try_from_storage((), storage_dtype) .vortex_expect("Apples accepts every storage dtype") @@ -102,61 +98,9 @@ mod tests { .cast(&DType::Extension(apples_u8.erased())) .is_err() ); - Ok(()) } - #[test] - fn test_struct_field_values() { - let f16_value = f16::from_f32(0.42); - let f32_value = f32::consts::PI; - - let struct_dtype = DType::Struct( - StructFields::from_iter([ - ( - "a", - FieldDType::from(DType::Primitive(PType::U32, Nullability::NonNullable)), - ), - ( - "b", - FieldDType::from(DType::Primitive(PType::F16, Nullability::NonNullable)), - ), - ( - "c", - FieldDType::from(DType::Primitive(PType::F32, Nullability::NonNullable)), - ), - ]), - Nullability::NonNullable, - ); - - let field_values = vec![ - Some(ScalarValue::Primitive(PValue::U32(42))), - Some(ScalarValue::Primitive(PValue::F16(f16_value))), - Some(ScalarValue::Primitive(PValue::F32(f32_value))), - ]; - - let scalar = Scalar::new(struct_dtype, Some(ScalarValue::Tuple(field_values))); - - let struct_scalar = scalar.as_struct(); - let fields: Vec<_> = (0..3) - .map(|i| struct_scalar.field_by_idx(i).unwrap()) - .collect(); - - // Check first field (no coercion needed) - assert_eq!(fields[0].as_primitive().pvalue().unwrap(), PValue::U32(42)); - - assert_eq!( - fields[1].as_primitive().pvalue().unwrap(), - PValue::F16(f16_value) - ); - - // Check third field (no coercion needed) - assert_eq!( - fields[2].as_primitive().pvalue().unwrap(), - PValue::F32(f32_value) - ); - } - #[rstest] #[case::u8(PType::U8)] #[case::i32(PType::I32)] @@ -178,49 +122,6 @@ mod tests { Ok(()) } - #[test] - fn test_fake_coercion_for_matching_type() { - // Test that when types already match, no coercion happens. - let i32_value = 42i32; - let scalar = Scalar::new( - DType::Primitive(PType::I32, Nullability::NonNullable), - Some(ScalarValue::Primitive(PValue::I32(i32_value))), - ); - - assert_eq!( - scalar.as_primitive().pvalue().unwrap(), - PValue::I32(i32_value) - ); - } - - #[test] - fn test_list_element_values() { - let f16_value1 = f16::from_f32(1.0); - let f16_value2 = f16::from_f32(2.0); - - let list_dtype = DType::List( - Arc::new(DType::Primitive(PType::F16, Nullability::NonNullable)), - Nullability::NonNullable, - ); - - let elements = vec![ - Some(ScalarValue::Primitive(PValue::F16(f16_value1))), - Some(ScalarValue::Primitive(PValue::F16(f16_value2))), - ]; - - let scalar = Scalar::new(list_dtype, Some(ScalarValue::Tuple(elements))); - - let list_scalar = scalar.as_list(); - let elements = list_scalar.elements().unwrap(); - - for (i, expected) in [f16_value1, f16_value2].iter().enumerate() { - assert_eq!( - elements[i].as_primitive().pvalue().unwrap(), - PValue::F16(*expected) - ); - } - } - #[rstest] #[case::zero(0x0000)] #[case::negative_zero(0x8000)] @@ -234,114 +135,99 @@ mod tests { assert_eq!(scalar.value(), Some(&expected)); assert!(Scalar::validate(&dtype, Some(&value)).is_err()); - Ok(()) } #[test] - fn test_f16_construction_rejects_bit_overflow() { - let error = Scalar::try_new( + fn test_f16_legacy_bit_restrictions() -> VortexResult<()> { + let err = Scalar::try_new( DType::Primitive(PType::F16, Nullability::NonNullable), Some(ScalarValue::Primitive(PValue::U64(u64::MAX))), ) .unwrap_err(); - assert!( - error - .to_string() - .contains("f16 bit representation must fit in 16 bits") + err.to_string() + .contains("f16 bit representation must fit in 16 bits"), + "{err}" ); - } - #[test] - fn test_nested_f16_requires_canonical_values() { - let dtype = DType::list( + let list_dtype = DType::list( DType::Primitive(PType::F16, Nullability::NonNullable), Nullability::NonNullable, ); - let value = ScalarValue::Tuple(vec![Some(ScalarValue::Primitive(PValue::U64(0x3c00)))]); - - assert!(Scalar::try_new(dtype, Some(value)).is_err()); - } - - #[test] - fn test_extension_dtype_requires_canonical_storage() -> VortexResult<()> { - let ext_dtype = Apples::new(DType::Primitive(PType::F16, Nullability::NonNullable)); + assert!( + Scalar::try_new( + list_dtype, + Some(ScalarValue::Tuple(vec![Some(ScalarValue::Primitive( + PValue::U64(0x3c00) + ))])), + ) + .is_err() + ); let f16_value = f16::from_f32(0.42); - let dtype = DType::Extension(ext_dtype.erased()); + let ext_dtype = DType::Extension( + Apples::new(DType::Primitive(PType::F16, Nullability::NonNullable)).erased(), + ); assert!( Scalar::try_new( - dtype.clone(), + ext_dtype.clone(), Some(ScalarValue::Primitive(PValue::U64(u64::from( f16_value.to_bits() )))), ) .is_err() ); - - let scalar = Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::F16(f16_value))))?; - + let scalar = Scalar::try_new( + ext_dtype, + Some(ScalarValue::Primitive(PValue::F16(f16_value))), + )?; assert_eq!( scalar .as_extension() .to_storage_scalar() .as_primitive() - .pvalue() - .unwrap(), - PValue::F16(f16_value) + .pvalue(), + Some(PValue::F16(f16_value)) ); - Ok(()) - } - - #[test] - fn test_extension_dtype_nested_struct_values() -> VortexResult<()> { - let struct_dtype = DType::Struct( + let struct_ext = Apples::new(DType::Struct( StructFields::from_iter([ ( "id", FieldDType::from(DType::Primitive(PType::U32, Nullability::NonNullable)), ), ( - "value", + "val", FieldDType::from(DType::Primitive(PType::F16, Nullability::NonNullable)), ), ]), Nullability::NonNullable, - ); - let ext_dtype = Apples::new(struct_dtype); - - let f16_value = f16::from_f32(1.5); - let field_values = vec![ - Some(ScalarValue::Primitive(PValue::U32(123))), - Some(ScalarValue::Primitive(PValue::F16(f16_value))), - ]; - - let scalar = Scalar::try_new( - DType::Extension(ext_dtype.erased()), - Some(ScalarValue::Tuple(field_values)), + )); + let struct_scalar = Scalar::try_new( + DType::Extension(struct_ext.erased()), + Some(ScalarValue::Tuple(vec![ + Some(ScalarValue::Primitive(PValue::U32(123))), + Some(ScalarValue::Primitive(PValue::F16(f16::from_f32(1.5)))), + ])), )?; - - let fields = scalar + let fields: Vec<_> = struct_scalar .as_extension() .to_storage_scalar() .as_struct() .fields_iter() .vortex_expect("non null") - .collect::>(); - assert_eq!(fields[0].as_primitive().pvalue().unwrap(), PValue::U32(123)); + .collect(); assert_eq!( - fields[1].as_primitive().pvalue().unwrap(), - PValue::F16(f16_value) + fields[1].as_primitive().pvalue(), + Some(PValue::F16(f16::from_f32(1.5))) ); - Ok(()) } #[test] - fn union_casts_apply_inner_nullability() -> VortexResult<()> { - let source_variants = UnionVariants::try_new( + fn union_nullability_casts() -> VortexResult<()> { + let src = UnionVariants::try_new( ["int", "string"].into(), vec![ DType::Primitive(PType::I32, Nullability::NonNullable), @@ -349,8 +235,7 @@ mod tests { ], vec![5, 9], )?; - - let target_variants = UnionVariants::try_new( + let dst = UnionVariants::try_new( ["int", "string"].into(), vec![ DType::Primitive(PType::I32, Nullability::NonNullable), @@ -358,230 +243,134 @@ mod tests { ], vec![5, 9], )?; - let target_dtype = DType::Union(target_variants, Nullability::NonNullable); + let dst_dtype = DType::Union(dst, Nullability::NonNullable); - let unchanged_child = Scalar::union( - source_variants.clone(), + let unchanged = Scalar::union( + src.clone(), 5, - Scalar::primitive(42_i32, Nullability::NonNullable), + Scalar::from(42_i32), Nullability::NonNullable, - )?; - let changed_child = Scalar::union( - source_variants, + )? + .cast(&dst_dtype)?; + let changed = Scalar::union( + src.clone(), 9, - Scalar::utf8("hello", Nullability::NonNullable), + Scalar::from("hello"), Nullability::NonNullable, - )?; - - let unchanged_child = unchanged_child.cast(&target_dtype)?; - let changed_child = changed_child.cast(&target_dtype)?; - - assert_eq!(unchanged_child.dtype(), &target_dtype); + )? + .cast(&dst_dtype)?; + assert_eq!(unchanged.as_union().child(), Some(Scalar::from(42_i32))); assert_eq!( - unchanged_child - .as_union() - .child() - .map(|scalar| scalar.dtype().clone()), - Some(DType::Primitive(PType::I32, Nullability::NonNullable)) - ); - assert_eq!(changed_child.dtype(), &target_dtype); - assert_eq!( - changed_child - .as_union() - .child() - .map(|scalar| scalar.dtype().clone()), - Some(DType::Utf8(Nullability::Nullable)) - ); - - assert_eq!( - unchanged_child.as_union().child(), - Some(Scalar::primitive(42i32, Nullability::NonNullable)) - ); - assert_eq!( - changed_child.as_union().child(), + changed.as_union().child(), Some(Scalar::utf8("hello", Nullability::Nullable)) ); - Ok(()) - } - #[test] - fn union_cast_rejects_null_for_non_nullable_child() -> VortexResult<()> { - let source_variants = UnionVariants::try_new( + // Outer nullability widening preserves selected child nullability and inner null. + let nullable_outer = DType::Union(src.clone(), Nullability::Nullable); + let widened = Scalar::union(src, 5, Scalar::from(42_i32), Nullability::NonNullable)? + .cast(&nullable_outer)?; + assert_eq!(widened.dtype(), &nullable_outer); + assert_eq!(widened.as_union().type_id(), Some(5)); + + let nullable_child = UnionVariants::try_new( ["int"].into(), vec![DType::Primitive(PType::I32, Nullability::Nullable)], vec![5], )?; - let target_variants = UnionVariants::try_new( + let nonnull_child = UnionVariants::try_new( ["int"].into(), vec![DType::Primitive(PType::I32, Nullability::NonNullable)], vec![5], )?; - let scalar = Scalar::union( - source_variants, + let inner_null = Scalar::union( + nullable_child.clone(), 5, Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), Nullability::NonNullable, )?; - assert!( - scalar - .cast(&DType::Union(target_variants, Nullability::NonNullable)) + inner_null + .cast(&DType::Union( + nonnull_child.clone(), + Nullability::NonNullable + )) .is_err() ); - - Ok(()) - } - - #[test] - fn union_cast_widens_outer_nullability_with_selected_inner_null() -> VortexResult<()> { - let variants = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I32, Nullability::Nullable)], - vec![5], - )?; - let scalar = Scalar::union( - variants.clone(), - 5, - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Nullability::NonNullable, - )?; - let target_dtype = DType::Union(variants, Nullability::Nullable); - - let cast = scalar.cast(&target_dtype)?; - let selected_child = cast - .as_union() - .child() - .vortex_expect("present union must have a selected child"); - - assert_eq!(cast.dtype(), &target_dtype); - assert!(selected_child.is_null()); - assert_eq!( - selected_child.dtype(), - &DType::Primitive(PType::I32, Nullability::Nullable) + let widened_inner_null = + inner_null.cast(&DType::Union(nullable_child.clone(), Nullability::Nullable))?; + assert!( + widened_inner_null + .as_union() + .child() + .vortex_expect("present") + .is_null() ); - Ok(()) - } - - #[test] - fn union_nullability_cast_recurses_inside_list() -> VortexResult<()> { - let source_variants = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I32, Nullability::NonNullable)], - vec![5], - )?; - let source_union_dtype = DType::Union(source_variants.clone(), Nullability::NonNullable); - let scalar = Scalar::list( - source_union_dtype, + // Recurses inside List. + let list = Scalar::list( + DType::Union(nonnull_child.clone(), Nullability::NonNullable), vec![Scalar::union( - source_variants, + nonnull_child, 5, - Scalar::primitive(42_i32, Nullability::NonNullable), + Scalar::from(42_i32), Nullability::NonNullable, )?], Nullability::NonNullable, ); - - let target_variants = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I32, Nullability::Nullable)], - vec![5], - )?; - let target_union_dtype = DType::Union(target_variants, Nullability::NonNullable); - let target_dtype = DType::List(Arc::new(target_union_dtype.clone()), Nullability::Nullable); - - let cast = scalar.cast(&target_dtype)?; - let union = cast - .as_list() - .element(0) - .vortex_expect("list must contain its union child"); - - assert_eq!(cast.dtype(), &target_dtype); - assert_eq!(union.dtype(), &target_union_dtype); + let target_list = DType::List( + Arc::new(DType::Union(nullable_child, Nullability::NonNullable)), + Nullability::Nullable, + ); + let cast_list = list.cast(&target_list)?; assert_eq!( - union.as_union().child(), + cast_list + .as_list() + .element(0) + .vortex_expect("elem") + .as_union() + .child(), Some(Scalar::primitive(42_i32, Nullability::Nullable)) ); - Ok(()) } #[test] fn union_cast_rejects_schema_changes() -> VortexResult<()> { - let source_variants = UnionVariants::try_new( + let source = UnionVariants::try_new( ["int"].into(), vec![DType::Primitive(PType::I32, Nullability::Nullable)], vec![5], )?; let scalar = Scalar::union( - source_variants, + source, 5, Scalar::primitive(42_i32, Nullability::Nullable), Nullability::NonNullable, )?; - let changed_name = UnionVariants::try_new( - ["integer"].into(), - vec![DType::Primitive(PType::I32, Nullability::NonNullable)], - vec![5], - )?; - let changed_type_id = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I32, Nullability::NonNullable)], - vec![6], - )?; - let changed_dtype = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I64, Nullability::Nullable)], - vec![5], - )?; - - for variants in [changed_name, changed_type_id, changed_dtype] { + for variants in [ + UnionVariants::try_new( + ["integer"].into(), + vec![DType::Primitive(PType::I32, Nullability::NonNullable)], + vec![5], + )?, + UnionVariants::try_new( + ["int"].into(), + vec![DType::Primitive(PType::I32, Nullability::NonNullable)], + vec![6], + )?, + UnionVariants::try_new( + ["int"].into(), + vec![DType::Primitive(PType::I64, Nullability::Nullable)], + vec![5], + )?, + ] { assert!( scalar .cast(&DType::Union(variants, Nullability::NonNullable)) .is_err() ); } - - Ok(()) - } - - #[test] - fn cast_changes_only_outer_union_nullability() -> VortexResult<()> { - let variants = UnionVariants::try_new( - ["int", "string"].into(), - vec![ - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Utf8(Nullability::NonNullable), - ], - vec![5, 9], - )?; - let scalar = Scalar::union( - variants.clone(), - 5, - Scalar::primitive(42_i32, Nullability::NonNullable), - Nullability::NonNullable, - )?; - - let expected = DType::Union(variants, Nullability::Nullable); - let nullable = scalar.cast(&expected)?; - - assert_eq!(nullable.dtype(), &expected); - assert!(nullable.dtype().is_nullable()); - assert_eq!(nullable.as_union().type_id(), Some(5)); - assert_eq!( - nullable - .as_union() - .child() - .map(|scalar| scalar.dtype().clone()), - Some(DType::Primitive(PType::I32, Nullability::NonNullable)) - ); - - assert_eq!( - nullable.as_union().child(), - Some(Scalar::primitive(42i32, Nullability::NonNullable)) - ); Ok(()) } } diff --git a/vortex-array/src/scalar/tests/hegel.rs b/vortex-array/src/scalar/tests/hegel.rs new file mode 100644 index 00000000000..e0d78158ece --- /dev/null +++ b/vortex-array/src/scalar/tests/hegel.rs @@ -0,0 +1,655 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Hegel property tests for [`Scalar`] proto roundtrips, casting, decimal coherence, and +//! `Eq`/`PartialOrd`/`Hash` laws. + +use std::cmp::Ordering; +use std::hash::DefaultHasher; +use std::hash::Hash; +use std::hash::Hasher; +use std::sync::Arc; +use std::sync::LazyLock; + +use hegel::TestCase; +use hegel::generators as gs; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::Canonical; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::arrays::ConstantArray; +use crate::builtins::ArrayBuiltins; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::DecimalType; +use crate::dtype::NativeDecimalType; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::dtype::UnionVariants; +use crate::dtype::extension::ExtDType; +use crate::dtype::extension::ExtId; +use crate::dtype::extension::ExtVTable; +use crate::dtype::generate::draw_ptype; +use crate::dtype::half::f16; +use crate::dtype::i256; +use crate::dtype::session::DTypeSession; +use crate::dtype::session::DTypeSessionExt; +use crate::scalar::DecimalValue; +use crate::scalar::PValue; +use crate::scalar::Scalar; +use crate::scalar::ScalarValue; + +/// Simple test extension dtype backed by `i32` with a `u8` tag metadata. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct TestTagExt; + +impl ExtVTable for TestTagExt { + type Metadata = u8; + type StoredMetadata = u8; + type NativeValue<'a> = i32; + + #[expect(clippy::disallowed_methods, reason = "test-only extension id")] + fn id(&self) -> ExtId { + ExtId::new("vortex.test.tag") + } + + fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { + Ok(vec![*metadata]) + } + + fn deserialize_metadata(&self, data: &[u8]) -> VortexResult { + Ok(data.first().copied().unwrap_or(0)) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + storage_value + .as_primitive() + .as_i32() + .ok_or_else(|| vortex_error::vortex_err!("expected i32 storage value")) + } +} + +static PROTO_SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty().with::(); + session.dtypes().register(TestTagExt); + session +}); + +fn hash_of(value: &T) -> u64 { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() +} + +fn draw_decimal_dtype(tc: &TestCase) -> DecimalDType { + let precision = tc.draw(gs::integers::().min_value(1).max_value(76)); + let scale = tc.draw( + gs::integers::() + .min_value(-128) + .max_value(precision.cast_signed()), + ); + DecimalDType::new(precision, scale) +} + +fn draw_ext_dtype(tc: &TestCase, nullability: Nullability) -> DType { + let tag = tc.draw(gs::integers::().max_value(3)); + DType::Extension( + ExtDType::::try_new(tag, nullability) + .vortex_expect("valid test extension dtype") + .erased(), + ) +} + +/// Draws a [`DType`] suited for nested [`Scalar`] property tests. +pub(crate) fn draw_scalar_dtype( + tc: &TestCase, + depth: u8, + include_variant_and_union: bool, +) -> DType { + let leaf_kinds = if include_variant_and_union { 8 } else { 7 }; + let container_kinds = if include_variant_and_union { 5 } else { 4 }; + let max_kind = if depth == 0 { + leaf_kinds - 1 + } else { + leaf_kinds + container_kinds - 1 + }; + let nullability = Nullability::from(tc.draw(gs::booleans())); + let child = || draw_scalar_dtype(tc, depth - 1, include_variant_and_union); + + match tc.draw(gs::integers::().max_value(max_kind)) { + 0 => DType::Null, + 1 => DType::Bool(nullability), + 2 => DType::Primitive(draw_ptype(tc), nullability), + 3 => DType::Decimal(draw_decimal_dtype(tc), nullability), + 4 => DType::Utf8(nullability), + 5 => DType::Binary(nullability), + 6 => draw_ext_dtype(tc, nullability), + 7 if include_variant_and_union => DType::Variant(nullability), + k => { + let container = k - leaf_kinds; + match container { + 0 => DType::List(Arc::new(child()), nullability), + 1 => { + let size = tc.draw(gs::integers::().max_value(4)); + DType::FixedSizeList(Arc::new(child()), size, nullability) + } + 2 => { + let width = tc.draw(gs::integers::().max_value(3)); + DType::struct_((0..width).map(|i| (format!("f{i}"), child())), nullability) + } + 3 => { + let key_dtype = if tc.draw(gs::booleans()) { + DType::Primitive(draw_ptype(tc), Nullability::NonNullable) + } else { + DType::Utf8(Nullability::NonNullable) + }; + DType::map(key_dtype, child(), tc.draw(gs::booleans()), nullability) + .vortex_expect("map keys are non-nullable") + } + _ => { + let width = tc.draw(gs::integers::().min_value(1).max_value(3)); + DType::Union( + UnionVariants::new( + (0..width).map(|i| format!("v{i}")).collect(), + (0..width).map(|_| child()).collect(), + ) + .vortex_expect("union variants are distinct"), + nullability, + ) + } + } + } + } +} + +fn draw_f16(tc: &TestCase) -> f16 { + match tc.draw(gs::integers::().max_value(7)) { + 0 => f16::from_f32(0.0), + 1 => f16::from_f32(-0.0), + 2 => f16::NAN, + 3 => f16::from_bits(f16::NAN.to_bits() | 0x8000), + 4 => f16::INFINITY, + 5 => f16::NEG_INFINITY, + 6 => f16::from_f32(1.5), + _ => f16::from_bits(tc.draw(gs::integers::())), + } +} + +fn draw_f32(tc: &TestCase) -> f32 { + match tc.draw(gs::integers::().max_value(7)) { + 0 => 0.0f32, + 1 => -0.0f32, + 2 => f32::NAN, + 3 => f32::from_bits(f32::NAN.to_bits() | 0x8000_0000), + 4 => f32::INFINITY, + 5 => f32::NEG_INFINITY, + 6 => f32::MIN_POSITIVE, + _ => f32::from_bits(tc.draw(gs::integers::())), + } +} + +fn draw_f64(tc: &TestCase) -> f64 { + match tc.draw(gs::integers::().max_value(7)) { + 0 => 0.0f64, + 1 => -0.0f64, + 2 => f64::NAN, + 3 => f64::from_bits(f64::NAN.to_bits() | 0x8000_0000_0000_0000), + 4 => f64::INFINITY, + 5 => f64::NEG_INFINITY, + 6 => f64::MIN_POSITIVE, + _ => f64::from_bits(tc.draw(gs::integers::())), + } +} + +fn draw_pvalue(tc: &TestCase, ptype: PType) -> PValue { + match ptype { + PType::U8 => PValue::U8(tc.draw(gs::integers::())), + PType::U16 => PValue::U16(tc.draw(gs::integers::())), + PType::U32 => PValue::U32(tc.draw(gs::integers::())), + PType::U64 => PValue::U64(tc.draw(gs::integers::())), + PType::I8 => PValue::I8(tc.draw(gs::integers::())), + PType::I16 => PValue::I16(tc.draw(gs::integers::())), + PType::I32 => PValue::I32(tc.draw(gs::integers::())), + PType::I64 => PValue::I64(tc.draw(gs::integers::())), + PType::F16 => PValue::F16(draw_f16(tc)), + PType::F32 => PValue::F32(draw_f32(tc)), + PType::F64 => PValue::F64(draw_f64(tc)), + } +} + +fn draw_decimal_value(tc: &TestCase, decimal_dtype: DecimalDType) -> DecimalValue { + let p = decimal_dtype.precision() as usize; + match decimal_dtype.canonical_values_type() { + DecimalType::I8 => DecimalValue::I8( + tc.draw( + gs::integers::() + .min_value(i8::MIN_BY_PRECISION[p]) + .max_value(i8::MAX_BY_PRECISION[p]), + ), + ), + DecimalType::I16 => DecimalValue::I16( + tc.draw( + gs::integers::() + .min_value(i16::MIN_BY_PRECISION[p]) + .max_value(i16::MAX_BY_PRECISION[p]), + ), + ), + DecimalType::I32 => DecimalValue::I32( + tc.draw( + gs::integers::() + .min_value(i32::MIN_BY_PRECISION[p]) + .max_value(i32::MAX_BY_PRECISION[p]), + ), + ), + DecimalType::I64 => DecimalValue::I64( + tc.draw( + gs::integers::() + .min_value(i64::MIN_BY_PRECISION[p]) + .max_value(i64::MAX_BY_PRECISION[p]), + ), + ), + DecimalType::I128 => DecimalValue::I128( + tc.draw( + gs::integers::() + .min_value(i128::MIN_BY_PRECISION[p]) + .max_value(i128::MAX_BY_PRECISION[p]), + ), + ), + DecimalType::I256 => { + let min = i256::MIN_BY_PRECISION[p]; + let max = i256::MAX_BY_PRECISION[p]; + let val = match tc.draw(gs::integers::().max_value(4)) { + 0 => i256::ZERO, + 1 => min, + 2 => max, + 3 => i256::from_i128(tc.draw(gs::integers::())), + _ => { + let hi = tc.draw(gs::integers::()); + let lo = tc.draw(gs::integers::()); + i256::from_parts(lo, hi).clamp(min, max) + } + }; + DecimalValue::I256(val) + } + } +} + +fn draw_variant_inner(tc: &TestCase) -> Scalar { + let inner_dtype = draw_scalar_dtype(tc, 1, false); + let inner = draw_scalar(tc, &inner_dtype); + if inner.is_null() { + Scalar::null(DType::Null) + } else { + inner + } +} + +pub(crate) fn draw_scalar(tc: &TestCase, dtype: &DType) -> Scalar { + if dtype.is_nullable() && tc.draw(gs::integers::().max_value(3)) == 0 { + return Scalar::null(dtype.clone()); + } + + match dtype { + DType::Null => Scalar::null(DType::Null), + DType::Bool(n) => Scalar::bool(tc.draw(gs::booleans()), *n), + DType::Primitive(p, n) => Scalar::primitive_value(draw_pvalue(tc, *p), *p, *n), + DType::Decimal(d, n) => Scalar::decimal(draw_decimal_value(tc, *d), *d, *n), + DType::Utf8(n) => Scalar::utf8(tc.draw(gs::text().max_size(24)), *n), + DType::Binary(n) => Scalar::binary(tc.draw(gs::binary().max_size(24)), *n), + DType::Variant(n) => { + let s = Scalar::variant(draw_variant_inner(tc)); + if *n == Nullability::Nullable { + s.into_nullable() + } else { + s + } + } + DType::Extension(ext) => { + let storage = Scalar::primitive( + tc.draw(gs::integers::()), + ext.storage_dtype().nullability(), + ); + Scalar::extension_ref(ext.clone(), storage) + } + DType::List(elem, n) => { + let len = tc.draw(gs::integers::().max_value(4)); + let elems = (0..len).map(|_| draw_scalar(tc, elem)).collect(); + Scalar::list(Arc::clone(elem), elems, *n) + } + DType::FixedSizeList(elem, size, n) => { + let elems = (0..*size).map(|_| draw_scalar(tc, elem)).collect(); + Scalar::fixed_size_list(Arc::clone(elem), elems, *n) + } + DType::Struct(fields, n) => { + let values: Vec<_> = fields.fields().map(|f| draw_scalar(tc, &f)).collect(); + Scalar::struct_(DType::Struct(fields.clone(), *n), values) + } + DType::Map(map, n) => { + let len = tc.draw(gs::integers::().max_value(3)); + let key_dtype = map.key_dtype(); + let val_dtype = map.value_dtype(); + let pairs: Vec<_> = (0..len) + .map(|_| (draw_scalar(tc, &key_dtype), draw_scalar(tc, &val_dtype))) + .collect(); + Scalar::map(DType::Map(map.clone(), *n), pairs) + } + DType::Union(variants, n) => { + let idx = tc.draw(gs::integers::().max_value(variants.len() - 1)); + let child_dtype = variants + .variant_by_index(idx) + .vortex_expect("valid union variant index"); + let child = draw_scalar(tc, &child_dtype); + Scalar::union( + variants.clone(), + variants.child_index_to_tag(idx), + child, + *n, + ) + .vortex_expect("valid union scalar") + } + DType::FixedSizeBinary(..) => unreachable!("FixedSizeBinary is not drawn"), + } +} + +/// Mutates a [`DType`] into a plausible cast target (or draws a fresh target) to exercise both +/// valid and invalid casts in [`hegel_scalar_cast_matches_constant_array_cast`]. +fn draw_cast_target(tc: &TestCase, source: &DType) -> DType { + match tc.draw(gs::integers::().max_value(4)) { + // Same dtype with flipped nullability (Null is always nullable) + 0 if !matches!(source, DType::Null) => { + source.with_nullability(Nullability::from(!source.is_nullable())) + } + // Related cast target by kind + 1 => { + let n = Nullability::from(tc.draw(gs::booleans())); + match source { + DType::Primitive(..) | DType::Bool(_) => { + if tc.draw(gs::booleans()) { + DType::Primitive(draw_ptype(tc), n) + } else { + DType::Decimal(draw_decimal_dtype(tc), n) + } + } + DType::Decimal(..) => { + if tc.draw(gs::booleans()) { + DType::Decimal(draw_decimal_dtype(tc), n) + } else { + DType::Primitive(draw_ptype(tc), n) + } + } + DType::List(elem, _) => { + let target_elem = Arc::new(draw_cast_target(tc, elem)); + if tc.draw(gs::booleans()) { + DType::List(target_elem, n) + } else { + DType::FixedSizeList( + target_elem, + tc.draw(gs::integers::().max_value(4)), + n, + ) + } + } + DType::FixedSizeList(elem, size, _) => { + let target_elem = Arc::new(draw_cast_target(tc, elem)); + if tc.draw(gs::booleans()) { + DType::List(target_elem, n) + } else { + let new_size = if tc.draw(gs::booleans()) { + *size + } else { + tc.draw(gs::integers::().max_value(4)) + }; + DType::FixedSizeList(target_elem, new_size, n) + } + } + DType::Struct(fields, _) => { + let mut target_fields: Vec<_> = fields + .names() + .iter() + .zip(fields.fields()) + .map(|(name, f)| (name.clone(), draw_cast_target(tc, &f))) + .collect(); + match tc.draw(gs::integers::().max_value(3)) { + 0 => {} + 1 => target_fields.reverse(), + 2 => { + target_fields.pop(); + } + _ => { + let extra_dtype = draw_scalar_dtype(tc, 0, false); + target_fields.push(("extra".into(), extra_dtype)); + } + } + DType::struct_(target_fields, n) + } + DType::Map(map, _) => { + let key_candidate = draw_cast_target(tc, &map.key_dtype()); + let key = if matches!(key_candidate, DType::Null) { + map.key_dtype() + } else { + key_candidate.as_nonnullable() + }; + let val = draw_cast_target(tc, &map.value_dtype()); + DType::map(key, val, tc.draw(gs::booleans()), n) + .vortex_expect("non-nullable map key") + } + DType::Extension(ext) => { + if tc.draw(gs::booleans()) { + ext.storage_dtype().with_nullability(n) + } else { + draw_ext_dtype(tc, n) + } + } + _ => draw_scalar_dtype(tc, 1, false), + } + } + // Arbitrary fresh dtype + _ => draw_scalar_dtype(tc, 1, false), + } +} + +#[hegel::test(test_cases = 200)] +fn hegel_proto_roundtrip(tc: TestCase) { + let depth = tc.draw(gs::integers::().max_value(2)); + let dtype = draw_scalar_dtype(&tc, depth, true); + let scalar = draw_scalar(&tc, &dtype); + + let pb = scalar.to_proto().vortex_expect("Scalar::to_proto"); + let roundtripped = Scalar::from_proto(&pb, &PROTO_SESSION).vortex_expect("Scalar::from_proto"); + assert_eq!(roundtripped.dtype(), scalar.dtype()); + assert_eq!(roundtripped, scalar); + assert_eq!(hash_of(&roundtripped), hash_of(&scalar)); + + // Also exercise direct ScalarValue::to_proto / from_proto. + let pb_val = ScalarValue::to_proto(scalar.value()); + let val_back = ScalarValue::from_proto(&pb_val, &dtype, &PROTO_SESSION) + .vortex_expect("ScalarValue::from_proto"); + let reconstructed = + Scalar::try_new(dtype, val_back).vortex_expect("reconstruct scalar from proto value"); + assert_eq!(reconstructed, scalar); +} + +#[hegel::test(test_cases = 500)] +fn hegel_scalar_cast_matches_constant_array_cast(tc: TestCase) { + let depth = tc.draw(gs::integers::().max_value(2)); + let dtype = draw_scalar_dtype(&tc, depth, false); + let scalar = draw_scalar(&tc, &dtype); + let target = draw_cast_target(&tc, &dtype); + + let mut ctx = PROTO_SESSION.create_execution_ctx(); + let scalar_res = scalar.cast(&target); + let const_res = ConstantArray::new(scalar.clone(), 1) + .into_array() + .cast(target.clone()) + .and_then(|arr| arr.execute::(&mut ctx)) + .and_then(|c| c.into_array().execute_scalar(0, &mut ctx)); + + match (&scalar_res, &const_res) { + (Ok(s), Ok(a)) => { + assert_eq!( + s.dtype(), + a.dtype(), + "ConstantArray dtype mismatch casting {scalar:?} to {target}" + ); + assert_eq!( + s, a, + "ConstantArray value mismatch casting {scalar:?} to {target}" + ); + } + (Err(_), Err(_)) => {} + (Ok(s), Err(err)) => panic!( + "Scalar::cast succeeded ({s:?}) while ConstantArray::cast failed ({err}) for {scalar:?} -> {target}" + ), + (Err(err), Ok(a)) => panic!( + "Scalar::cast failed ({err}) while ConstantArray::cast succeeded ({a:?}) for {scalar:?} -> {target}" + ), + } + + if !scalar.is_null() { + let canon_res = ConstantArray::new(scalar.clone(), 1) + .into_array() + .execute::(&mut ctx) + .and_then(|c| c.into_array().cast(target.clone())) + .and_then(|arr| arr.execute::(&mut ctx)) + .and_then(|c| c.into_array().execute_scalar(0, &mut ctx)); + match (&scalar_res, &canon_res) { + (Ok(s), Ok(a)) => { + assert_eq!( + s.dtype(), + a.dtype(), + "Canonical dtype mismatch casting {scalar:?} to {target}" + ); + assert_eq!( + s, a, + "Canonical value mismatch casting {scalar:?} to {target}" + ); + } + (Err(err), Ok(a)) => panic!( + "Scalar::cast failed ({err}) while Canonical::cast succeeded ({a:?}) for {scalar:?} -> {target}" + ), + _ => {} + } + } +} + +#[hegel::test(test_cases = 200)] +fn hegel_decimal_value_eq_ord_hash_across_widths(tc: TestCase) { + let v1 = tc.draw(gs::integers::()); + let v2 = tc.draw(gs::integers::()); + + let reps = |v: i128| -> Vec { + let mut out = vec![ + DecimalValue::I128(v), + DecimalValue::I256(i256::from_i128(v)), + ]; + if let Ok(x) = i64::try_from(v) { + out.push(DecimalValue::I64(x)); + } + if let Ok(x) = i32::try_from(v) { + out.push(DecimalValue::I32(x)); + } + if let Ok(x) = i16::try_from(v) { + out.push(DecimalValue::I16(x)); + } + if let Ok(x) = i8::try_from(v) { + out.push(DecimalValue::I8(x)); + } + out + }; + + let reps1 = reps(v1); + let reps2 = reps(v2); + + for a in &reps1 { + for b in &reps1 { + assert_eq!(a, b); + assert_eq!(a.partial_cmp(b), Some(Ordering::Equal)); + assert_eq!(hash_of(a), hash_of(b)); + } + } + + let expected_ord = Some(v1.cmp(&v2)); + for a in &reps1 { + for b in &reps2 { + assert_eq!(a.partial_cmp(b), expected_ord); + assert_eq!(a == b, expected_ord == Some(Ordering::Equal)); + if a == b { + assert_eq!(hash_of(a), hash_of(b)); + } + } + } +} + +fn contains_variant(dtype: &DType) -> bool { + match dtype { + DType::Variant(_) => true, + DType::List(e, _) | DType::FixedSizeList(e, ..) => contains_variant(e), + DType::Struct(fields, _) => fields.fields().any(|f| contains_variant(&f)), + DType::Map(m, _) => contains_variant(&m.key_dtype()) || contains_variant(&m.value_dtype()), + DType::Union(u, _) => u.variants().any(|v| contains_variant(&v)), + DType::Extension(e) => contains_variant(e.storage_dtype()), + _ => false, + } +} + +#[hegel::test(test_cases = 200)] +fn hegel_eq_ord_hash_and_nullability_laws(tc: TestCase) { + let depth = tc.draw(gs::integers::().max_value(2)); + let dtype = draw_scalar_dtype(&tc, depth, true); + let a = draw_scalar(&tc, &dtype); + let b = draw_scalar(&tc, &dtype); + + // Reflexivity and into_parts/try_new roundtrip + assert_eq!(a, a); + if !contains_variant(&dtype) { + assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal)); + } + let (d, v) = a.clone().into_parts(); + assert_eq!(Scalar::try_new(d, v).vortex_expect("try_new roundtrip"), a); + + // Symmetry and Eq/Hash/PartialOrd coherence + assert_eq!(a == b, b == a); + if a == b { + assert_eq!(hash_of(&a), hash_of(&b)); + if !contains_variant(&dtype) { + assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal)); + } + } + if let Some(ord) = a.partial_cmp(&b) { + assert_eq!(b.partial_cmp(&a), Some(ord.reverse())); + assert_eq!(ord == Ordering::Equal, a == b); + } + + // Nullability invariance and null-orders-first law + let a_nullable = a.clone().into_nullable(); + assert_eq!(a, a_nullable); + assert_eq!(hash_of(&a), hash_of(&a_nullable)); + if !contains_variant(&dtype) { + assert_eq!(a.partial_cmp(&a_nullable), Some(Ordering::Equal)); + } + + if !a.is_null() { + let null_s = Scalar::null(dtype.as_nullable()); + assert_ne!(null_s, a_nullable); + assert_eq!(null_s.partial_cmp(&a_nullable), Some(Ordering::Less)); + assert_eq!(a_nullable.partial_cmp(&null_s), Some(Ordering::Greater)); + } +} diff --git a/vortex-array/src/scalar/tests/mod.rs b/vortex-array/src/scalar/tests/mod.rs index c208e7870ed..2c174082b28 100644 --- a/vortex-array/src/scalar/tests/mod.rs +++ b/vortex-array/src/scalar/tests/mod.rs @@ -5,6 +5,7 @@ mod casting; mod consistency; +pub(crate) mod hegel; mod nested; mod nullability; mod primitives; diff --git a/vortex-array/src/scalar/tests/nested.rs b/vortex-array/src/scalar/tests/nested.rs index f6c9d825975..7c57aa9a75d 100644 --- a/vortex-array/src/scalar/tests/nested.rs +++ b/vortex-array/src/scalar/tests/nested.rs @@ -1,12 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for nested structures including Lists, FixedSizeLists, and Structs. +//! Focused corner-case tests for nested scalar structures (`List`, `FixedSizeList`, `Struct`). +//! +//! General nested construction, equality, ordering, casting, and proto roundtrips are covered by +//! `scalar::tests::hegel`. #[cfg(test)] mod tests { use std::sync::Arc; + use vortex_error::VortexResult; + use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; @@ -15,1443 +20,131 @@ mod tests { use crate::scalar::ScalarValue; #[test] - fn test_fixed_size_list_of_fixed_size_list() { - // Create FixedSizeList[2] of FixedSizeList[3] of I32. - let inner_element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let inner_dtype = Arc::new(DType::FixedSizeList( - Arc::clone(&inner_element_dtype), - 3, - Nullability::NonNullable, - )); - - // Create inner FixedSizeLists. - let inner_list1 = Scalar::fixed_size_list( - Arc::clone(&inner_element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_list2 = Scalar::fixed_size_list( - inner_element_dtype, - vec![ - Scalar::primitive(4i32, Nullability::NonNullable), - Scalar::primitive(5i32, Nullability::NonNullable), - Scalar::primitive(6i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Create outer FixedSizeList. - let outer_list = Scalar::fixed_size_list( - inner_dtype, - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - assert!(matches!(outer_list.dtype(), DType::FixedSizeList(_, 2, _))); - - // Access nested elements. - let outer = outer_list.as_list(); - assert_eq!(outer.len(), 2); - - let first_inner = outer.element(0).unwrap(); - let first_inner_list = first_inner.as_list(); - assert_eq!(first_inner_list.len(), 3); - assert_eq!( - first_inner_list - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - - let second_inner = outer.element(1).unwrap(); - let second_inner_list = second_inner.as_list(); - assert_eq!( - second_inner_list - .element(2) - .unwrap() - .as_primitive() - .typed_value::(), - Some(6) - ); - } - - #[test] - fn test_fixed_size_list_of_list() { - // Create FixedSizeList[2] of variable List of I32. - let inner_element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let inner_dtype = Arc::new(DType::List( - Arc::clone(&inner_element_dtype), - Nullability::NonNullable, - )); - - let inner_list1 = Scalar::list( - Arc::clone(&inner_element_dtype), - vec![ - Scalar::primitive(10i32, Nullability::NonNullable), - Scalar::primitive(20i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_list2 = Scalar::list( - inner_element_dtype, - vec![ - Scalar::primitive(30i32, Nullability::NonNullable), - Scalar::primitive(40i32, Nullability::NonNullable), - Scalar::primitive(50i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer_fixed_list = Scalar::fixed_size_list( - inner_dtype, - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - let outer = outer_fixed_list.as_list(); - assert_eq!(outer.len(), 2); - - // First inner list has 2 elements. - let first_inner = outer.element(0).unwrap(); - assert_eq!(first_inner.as_list().len(), 2); - - // Second inner list has 3 elements. - let second_inner = outer.element(1).unwrap(); - assert_eq!(second_inner.as_list().len(), 3); - } - - #[test] - fn test_list_of_fixed_size_list() { - // Create variable List of FixedSizeList[3] of I32. - let inner_element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let inner_dtype = Arc::new(DType::FixedSizeList( - Arc::clone(&inner_element_dtype), - 3, - Nullability::NonNullable, - )); - - let fixed_list1 = Scalar::fixed_size_list( - Arc::clone(&inner_element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let fixed_list2 = Scalar::fixed_size_list( - inner_element_dtype, - vec![ - Scalar::primitive(4i32, Nullability::NonNullable), - Scalar::primitive(5i32, Nullability::NonNullable), - Scalar::primitive(6i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer_list = Scalar::list( - inner_dtype, - vec![fixed_list1, fixed_list2], - Nullability::NonNullable, - ); - - assert!(matches!(outer_list.dtype(), DType::List(..))); - - let outer = outer_list.as_list(); - assert_eq!(outer.len(), 2); - - // Each inner list should be FixedSizeList[3]. - let first_inner = outer.element(0).unwrap(); - assert!(matches!(first_inner.dtype(), DType::FixedSizeList(_, 3, _))); - assert_eq!(first_inner.as_list().len(), 3); - } - - #[test] - fn test_fixed_size_list_containing_structs() { - // Create FixedSizeList[2] of Struct{a: I32, b: Utf8}. - let struct_dtype = DType::struct_( - [ - ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), - ("b", DType::Utf8(Nullability::NonNullable)), - ], - Nullability::NonNullable, - ); - - let struct1 = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::primitive(100i32, Nullability::NonNullable), - Scalar::utf8("first", Nullability::NonNullable), - ], - ); - - let struct2 = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::primitive(200i32, Nullability::NonNullable), - Scalar::utf8("second", Nullability::NonNullable), - ], - ); - - let fixed_list_of_structs = Scalar::fixed_size_list( - Arc::new(struct_dtype), - vec![struct1, struct2], - Nullability::NonNullable, - ); - - let list = fixed_list_of_structs.as_list(); - assert_eq!(list.len(), 2); - - // Access struct fields through the list. - let first_struct = list.element(0).unwrap(); - let first = first_struct.as_struct(); - assert_eq!( - first - .field("a") - .unwrap() - .as_primitive() - .typed_value::(), - Some(100) - ); - assert_eq!( - first - .field("b") - .unwrap() - .as_utf8() - .value() - .cloned() - .unwrap(), - "first".into() - ); - } - - #[test] - fn test_struct_with_fixed_size_list_field() { - // Create Struct with a FixedSizeList field. - let fixed_list_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - 3, - Nullability::NonNullable, - ); - - let struct_dtype = DType::struct_( - [ - ("name", DType::Utf8(Nullability::NonNullable)), - ("values", fixed_list_dtype), - ( - "count", - DType::Primitive(PType::U32, Nullability::NonNullable), - ), - ], - Nullability::NonNullable, - ); - - let fixed_list_field = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - vec![ - Scalar::primitive(10i64, Nullability::NonNullable), - Scalar::primitive(20i64, Nullability::NonNullable), - Scalar::primitive(30i64, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let struct_scalar = Scalar::struct_( - struct_dtype, - vec![ - Scalar::utf8("test_struct", Nullability::NonNullable), - fixed_list_field, - Scalar::primitive(3u32, Nullability::NonNullable), - ], - ); - - let struct_view = struct_scalar.as_struct(); - assert_eq!( - struct_view - .field("name") - .unwrap() - .as_utf8() - .value() - .unwrap() - .as_str(), - "test_struct" - ); - - let values_field = struct_view.field("values").unwrap(); - assert!(matches!( - values_field.dtype(), - DType::FixedSizeList(_, 3, _) - )); - assert_eq!(values_field.as_list().len(), 3); - assert_eq!( - values_field - .as_list() - .element(1) - .unwrap() - .as_primitive() - .typed_value::(), - Some(20) - ); - } - - #[test] - fn test_list_cast_element_types() { - // Test casting list elements between different primitive types. + fn test_list_cast_element_overflow_error() { let list = Scalar::new( - DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), - Nullability::Nullable, - ), - Some(ScalarValue::Tuple(vec![ - Some(ScalarValue::Primitive(PValue::U16(6))), - Some(ScalarValue::Primitive(PValue::U16(100))), - ])), - ); - - // Cast U16 -> U32. - let target_u32 = DType::List( - Arc::from(DType::Primitive(PType::U32, Nullability::Nullable)), - Nullability::Nullable, - ); - let casted = list.cast(&target_u32).unwrap(); - assert_eq!(casted.dtype(), &target_u32); - - // Cast U16 -> U8 (with values that fit). - let target_u8 = DType::List( - Arc::from(DType::Primitive(PType::U8, Nullability::Nullable)), - Nullability::Nullable, - ); - let casted = list.cast(&target_u8).unwrap(); - assert_eq!(casted.dtype(), &target_u8); - - // Cast U16 -> I32. - let target_i32 = DType::List( - Arc::from(DType::Primitive(PType::I32, Nullability::Nullable)), - Nullability::Nullable, - ); - let casted = list.cast(&target_i32).unwrap(); - assert_eq!(casted.dtype(), &target_i32); - } - - #[test] - fn test_list_cast_element_overflow() { - // Test that casting U16 values too large for U8 fails. - let list_with_large_values = Scalar::new( DType::List( Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), Nullability::Nullable, ), Some(ScalarValue::Tuple(vec![ Some(ScalarValue::Primitive(PValue::U16(100))), - Some(ScalarValue::Primitive(PValue::U16(256))), // Too large for U8 - Some(ScalarValue::Primitive(PValue::U16(1000))), // Too large for U8 + Some(ScalarValue::Primitive(PValue::U16(256))), ])), ); - - let target_u8 = DType::List( + let target = DType::List( Arc::from(DType::Primitive(PType::U8, Nullability::Nullable)), Nullability::Nullable, ); - - let result = list_with_large_values.cast(&target_u8); - assert!(result.is_err()); + let err = list.cast(&target).unwrap_err(); assert!( - result - .unwrap_err() - .to_string() - .contains("Cannot cast 256u16 to u8") + err.to_string().contains("Cannot cast 256u16 to u8"), + "{err}" ); } #[test] - fn test_list_cast_nested_lists() { - // Create a list of lists. - let inner_list1 = Scalar::list( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - let inner_list2 = Scalar::list( + fn test_list_cast_incompatible_element_types() { + let int_list = Scalar::list( Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - let nested_list = Scalar::list( - Arc::from(DType::List( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), - Nullability::NonNullable, - )), - vec![inner_list1, inner_list2], + vec![Scalar::primitive(1i32, Nullability::NonNullable)], Nullability::NonNullable, ); - - // Cast to nested list with I64 elements. let target = DType::List( - Arc::from(DType::List( - Arc::from(DType::Primitive(PType::I64, Nullability::NonNullable)), - Nullability::NonNullable, - )), + Arc::from(DType::Utf8(Nullability::NonNullable)), Nullability::NonNullable, ); - let casted = nested_list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); + assert!(int_list.cast(&target).is_err()); } #[test] - fn test_list_cast_empty_list() { - // Test casting empty list. - let empty_list = Scalar::list( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![], - Nullability::NonNullable, - ); + fn test_fixed_size_list_size_zero_and_empty_cast() -> VortexResult<()> { + let elem = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); + let empty_fsl = + Scalar::fixed_size_list(Arc::clone(&elem), vec![], Nullability::NonNullable); + assert!(matches!(empty_fsl.dtype(), DType::FixedSizeList(_, 0, _))); + assert!(empty_fsl.as_list().is_empty()); + assert!(!empty_fsl.as_list().is_null()); + assert_eq!(empty_fsl.approx_nbytes(), 0); - // Cast to different element type. - let target = DType::List( - Arc::from(DType::Primitive(PType::I64, Nullability::NonNullable)), - Nullability::NonNullable, - ); - let casted = empty_list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); - assert_eq!(casted.as_list().len(), 0); + let as_list = empty_fsl.cast(&DType::List(Arc::clone(&elem), Nullability::NonNullable))?; + assert!(as_list.as_list().is_empty()); - // Cast empty list to FixedSizeList[0]. - let target_fixed = DType::FixedSizeList( - Arc::from(DType::Primitive(PType::I64, Nullability::NonNullable)), + let target_fsl = DType::FixedSizeList( + Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), 0, Nullability::NonNullable, ); - let casted_fixed = empty_list.cast(&target_fixed).unwrap(); - assert_eq!(casted_fixed.dtype(), &target_fixed); - } - - #[test] - fn test_list_cast_string_elements() { - // Create a list of strings. - let string_list = Scalar::list( - Arc::from(DType::Utf8(Nullability::NonNullable)), - vec![ - Scalar::utf8("hello", Nullability::NonNullable), - Scalar::utf8("world", Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Cast to nullable strings. - let target = DType::List( - Arc::from(DType::Utf8(Nullability::Nullable)), - Nullability::NonNullable, - ); - let casted = string_list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); + assert_eq!(as_list.cast(&target_fsl)?.dtype(), &target_fsl); + Ok(()) } #[test] - fn test_list_cast_struct_elements() { - // Create a list of structs. - let struct_dtype = DType::struct_( - [ - ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), - ("b", DType::Primitive(PType::I64, Nullability::NonNullable)), - ], - Nullability::NonNullable, - ); - let struct1 = Scalar::struct_( - struct_dtype.clone(), + fn test_fixed_size_list_size_mismatch_errors() { + let elem = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); + let list = Scalar::list( + Arc::clone(&elem), vec![ Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(10i64, Nullability::NonNullable), - ], - ); - let struct2 = Scalar::struct_( - struct_dtype.clone(), - vec![ Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(20i64, Nullability::NonNullable), - ], - ); - let struct_list = Scalar::list( - Arc::from(struct_dtype), - vec![struct1, struct2], - Nullability::NonNullable, - ); - - // Cast struct fields. - let target_struct_dtype = DType::struct_( - [ - ("a", DType::Primitive(PType::I64, Nullability::NonNullable)), - ("b", DType::Primitive(PType::I32, Nullability::NonNullable)), ], Nullability::NonNullable, ); - let target = DType::List(Arc::from(target_struct_dtype), Nullability::NonNullable); - let casted = struct_list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); - } - #[test] - fn test_list_cast_incompatible_element_types() { - // Create a list of integers. - let int_list = Scalar::list( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![Scalar::primitive(1i32, Nullability::NonNullable)], - Nullability::NonNullable, + let larger = DType::FixedSizeList(Arc::clone(&elem), 3, Nullability::NonNullable); + let err = list.cast(&larger).unwrap_err(); + assert!( + err.to_string() + .contains("tried to cast to a `FixedSizeList[3]` but had 2 elements"), + "{err}" ); - // Try to cast to list of strings - should fail. - let target = DType::List( - Arc::from(DType::Utf8(Nullability::NonNullable)), - Nullability::NonNullable, - ); - assert!(int_list.cast(&target).is_err()); + let smaller = DType::FixedSizeList(elem, 1, Nullability::NonNullable); + assert!(list.cast(&smaller).is_err()); } #[test] - fn test_list_to_fixed_size_list_cast() { - // Create a list with 3 elements. - let list = Scalar::list( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), + fn test_fixed_size_list_display() { + let fixed_list = Scalar::fixed_size_list( + Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), + Scalar::primitive(100i32, Nullability::NonNullable), + Scalar::primitive(200i32, Nullability::NonNullable), ], Nullability::NonNullable, ); - // Cast to FixedSizeList with matching size. - let target = DType::FixedSizeList( - Arc::from(DType::Primitive(PType::I64, Nullability::NonNullable)), - 3, - Nullability::NonNullable, - ); - let casted = list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); - assert_eq!(casted.as_list().len(), 3); + let display_str = format!("{}", fixed_list.as_list()); + assert!(display_str.contains("fixed_size<2>")); + assert!(display_str.contains("100")); + assert!(display_str.contains("200")); } #[test] - fn test_fixed_size_list_to_fixed_size_list_cast() { - // Create a FixedSizeList[4] with I32 elements. - let fixed_list = Scalar::fixed_size_list( - Arc::from(DType::Primitive(PType::I32, Nullability::NonNullable)), + fn test_nested_fixed_size_list_nbytes() { + let i32_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); + let inner = Scalar::fixed_size_list( + Arc::clone(&i32_dtype), vec![ Scalar::primitive(1i32, Nullability::NonNullable), Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Cast to FixedSizeList[4] with I64 elements. - let target = DType::FixedSizeList( - Arc::from(DType::Primitive(PType::I64, Nullability::NonNullable)), - 4, - Nullability::NonNullable, - ); - let casted = fixed_list.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); - } - - #[test] - fn test_deeply_nested_mixed_structures() { - // Create a deeply nested structure: - // List of FixedSizeList[2] of Struct{id: I32, data: FixedSizeList[2] of I64}. - - let inner_fixed_list_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - )); - - let struct_dtype = Arc::new(DType::struct_( - [ - ("id", DType::Primitive(PType::I32, Nullability::NonNullable)), - ("data", (*inner_fixed_list_dtype).clone()), - ], - Nullability::NonNullable, - )); - - let middle_fixed_list_dtype = Arc::new(DType::FixedSizeList( - Arc::clone(&struct_dtype), - 2, - Nullability::NonNullable, - )); - - // Create inner FixedSizeList for struct field. - let inner_list1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - vec![ - Scalar::primitive(100i64, Nullability::NonNullable), - Scalar::primitive(200i64, Nullability::NonNullable), ], Nullability::NonNullable, ); - - let inner_list2 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - vec![ - Scalar::primitive(300i64, Nullability::NonNullable), - Scalar::primitive(400i64, Nullability::NonNullable), - ], + let outer = Scalar::fixed_size_list( + Arc::new(DType::FixedSizeList(i32_dtype, 2, Nullability::NonNullable)), + vec![inner.clone(), inner], Nullability::NonNullable, ); + assert_eq!(outer.approx_nbytes(), 16); - // Create structs. - let struct1 = Scalar::struct_( - (*struct_dtype).clone(), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - inner_list1, - ], - ); - - let struct2 = Scalar::struct_( - (*struct_dtype).clone(), + let string_list = Scalar::fixed_size_list( + Arc::new(DType::Utf8(Nullability::NonNullable)), vec![ - Scalar::primitive(2i32, Nullability::NonNullable), - inner_list2, - ], - ); - - // Create middle FixedSizeList[2] of structs. - let middle_list = Scalar::fixed_size_list( - struct_dtype, - vec![struct1, struct2], - Nullability::NonNullable, - ); - - // Create outer List. - let outer_list = Scalar::list( - middle_fixed_list_dtype, - vec![middle_list.clone(), middle_list], - Nullability::NonNullable, - ); - - // Verify structure. - assert!(matches!(outer_list.dtype(), DType::List(..))); - let outer = outer_list.as_list(); - assert_eq!(outer.len(), 2); - - let first_middle = outer.element(0).unwrap(); - assert!(matches!( - first_middle.dtype(), - DType::FixedSizeList(_, 2, _) - )); - - let first_struct = first_middle.as_list().element(0).unwrap(); - let struct_view = first_struct.as_struct(); - assert_eq!( - struct_view - .field("id") - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - - let data_field = struct_view.field("data").unwrap(); - assert_eq!( - data_field - .as_list() - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(100) - ); - } - - #[test] - fn test_nested_structure_casting() { - // Test casting nested structures with element type changes. - let inner_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - )); - - let inner_list1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_list2 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer_list = Scalar::list( - inner_dtype, - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - // Cast to List of FixedSizeList[2] of I64. - let target_dtype = DType::List( - Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - )), - Nullability::NonNullable, - ); - - let casted = outer_list.cast(&target_dtype).unwrap(); - assert!(matches!(casted.dtype(), DType::List(..))); - - let casted_list = casted.as_list(); - let first_inner = casted_list.element(0).unwrap(); - let first_inner_list = first_inner.as_list(); - assert_eq!( - first_inner_list - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - } - - #[test] - fn test_mixed_list_and_fixed_size_list() { - // Create a structure mixing List and FixedSizeList at different levels. - // FixedSizeList[2] of List of FixedSizeList[2] of I32. - - let innermost_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - )); - - let middle_dtype = Arc::new(DType::List( - Arc::clone(&innermost_dtype), - Nullability::NonNullable, - )); - - // Create innermost FixedSizeLists. - let inner_fixed1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_fixed2 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Create middle Lists. - let middle_list1 = Scalar::list( - Arc::clone(&innermost_dtype), - vec![inner_fixed1.clone()], - Nullability::NonNullable, - ); - - let middle_list2 = Scalar::list( - innermost_dtype, - vec![inner_fixed2, inner_fixed1], - Nullability::NonNullable, - ); - - // Create outer FixedSizeList. - let outer = Scalar::fixed_size_list( - middle_dtype, - vec![middle_list1, middle_list2], - Nullability::NonNullable, - ); - - assert!(matches!(outer.dtype(), DType::FixedSizeList(_, 2, _))); - - let outer_list = outer.as_list(); - assert_eq!(outer_list.len(), 2); - - // Second middle list has 2 inner fixed lists. - let second_middle = outer_list.element(1).unwrap(); - assert_eq!(second_middle.as_list().len(), 2); - } - - #[test] - fn test_nested_structure_nbytes() { - // Test nbytes calculation for nested structures. - let inner_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - )); - - let inner_list1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_list2 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer = Scalar::fixed_size_list( - inner_dtype, - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - // 2 outer elements * 2 inner elements * 4 bytes (i32) = 16 bytes. - assert_eq!(outer.approx_nbytes(), 16); - } - - // Tests merged from fixed_size_list.rs - - #[test] - fn test_fixed_size_list_creation_and_access() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(10i32, Nullability::NonNullable), - Scalar::primitive(20i32, Nullability::NonNullable), - Scalar::primitive(30i32, Nullability::NonNullable), - ]; - let fixed_list = Scalar::fixed_size_list(element_dtype, children, Nullability::NonNullable); - - assert!(matches!(fixed_list.dtype(), DType::FixedSizeList(_, 3, _))); - - let list = fixed_list.as_list(); - assert_eq!(list.len(), 3); - assert!(!list.is_null()); - - // Test element access. - assert_eq!( - list.element(0).unwrap().as_primitive().typed_value::(), - Some(10) - ); - assert_eq!( - list.element(1).unwrap().as_primitive().typed_value::(), - Some(20) - ); - assert_eq!( - list.element(2).unwrap().as_primitive().typed_value::(), - Some(30) - ); - } - - #[test] - fn test_fixed_size_list_size_zero() { - // Test FixedSizeList[0] behavior. - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let empty_fixed_list = - Scalar::fixed_size_list(Arc::clone(&element_dtype), vec![], Nullability::NonNullable); - - assert!(matches!( - empty_fixed_list.dtype(), - DType::FixedSizeList(_, 0, _) - )); - - let list = empty_fixed_list.as_list(); - assert_eq!(list.len(), 0); - assert!(list.is_empty()); - assert!(!list.is_null()); - - // Cast to regular list should work. - let target = DType::List(element_dtype, Nullability::NonNullable); - let casted = empty_fixed_list.cast(&target).unwrap(); - assert_eq!(casted.as_list().len(), 0); - } - - #[test] - fn test_fixed_size_list_cast_to_list() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let fixed_list = Scalar::fixed_size_list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Cast to regular List with same element type. - let target = DType::List(element_dtype, Nullability::NonNullable); - let casted = fixed_list.cast(&target).unwrap(); - assert!(matches!(casted.dtype(), DType::List(..))); - assert_eq!(casted.as_list().len(), 2); - - // Cast to regular List with different element type. - let target_i64 = DType::List( - Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), - Nullability::NonNullable, - ); - let casted_i64 = fixed_list.cast(&target_i64).unwrap(); - assert_eq!(casted_i64.dtype(), &target_i64); - assert_eq!(casted_i64.as_list().len(), 2); - assert_eq!( - casted_i64 - .as_list() - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - } - - #[test] - fn test_list_cast_to_fixed_size_list() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let list = Scalar::list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(10i32, Nullability::NonNullable), - Scalar::primitive(20i32, Nullability::NonNullable), - Scalar::primitive(30i32, Nullability::NonNullable), - Scalar::primitive(40i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Cast to FixedSizeList[4] should succeed. - let target = DType::FixedSizeList(element_dtype, 4, Nullability::NonNullable); - let casted = list.cast(&target).unwrap(); - assert!(matches!(casted.dtype(), DType::FixedSizeList(_, 4, _))); - - // Cast with element type change. - let target_u32 = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U32, Nullability::NonNullable)), - 4, - Nullability::NonNullable, - ); - let casted_u32 = list.cast(&target_u32).unwrap(); - assert_eq!( - casted_u32 - .as_list() - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(10) - ); - } - - #[test] - fn test_fixed_size_list_size_validation() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let list = Scalar::list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - // Try to cast to wrong size - should fail. - let wrong_size_target = - DType::FixedSizeList(Arc::clone(&element_dtype), 3, Nullability::NonNullable); - let result = list.cast(&wrong_size_target); - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("tried to cast to a `FixedSizeList[3]` but had 2 elements") - ); - - // Try to cast to wrong size (smaller). - let smaller_target = DType::FixedSizeList(element_dtype, 1, Nullability::NonNullable); - let result = list.cast(&smaller_target); - assert!(result.is_err()); - } - - #[test] - fn test_fixed_size_list_display() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let fixed_list = Scalar::fixed_size_list( - element_dtype, - vec![ - Scalar::primitive(100i32, Nullability::NonNullable), - Scalar::primitive(200i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let display_str = format!("{}", fixed_list.as_list()); - assert!(display_str.contains("fixed_size<2>")); - assert!(display_str.contains("100")); - assert!(display_str.contains("200")); - } - - #[test] - fn test_fixed_size_list_equality_and_ordering() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - - // Create two equal fixed size lists. - let list1 = Scalar::fixed_size_list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let list2 = Scalar::fixed_size_list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - assert_eq!(list1, list2); - - // Create a different list. - let list3 = Scalar::fixed_size_list( - element_dtype, - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - assert_ne!(list1, list3); - - // Test ordering. - assert!(list1 < list3); - assert!(list3 > list1); - } - - #[test] - fn test_fixed_size_list_single_element() { - // Test FixedSizeList[1]. - let element_dtype = Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)); - let single_element = Scalar::fixed_size_list( - Arc::clone(&element_dtype), - vec![Scalar::primitive(42i64, Nullability::NonNullable)], - Nullability::NonNullable, - ); - - assert!(matches!( - single_element.dtype(), - DType::FixedSizeList(_, 1, _) - )); - - let list = single_element.as_list(); - assert_eq!(list.len(), 1); - assert_eq!( - list.element(0).unwrap().as_primitive().typed_value::(), - Some(42) - ); - - // Cast to variable list. - let target = DType::List(element_dtype, Nullability::NonNullable); - let casted = single_element.cast(&target).unwrap(); - assert_eq!(casted.as_list().len(), 1); - } - - #[test] - fn test_fixed_size_list_with_strings() { - let element_dtype = Arc::new(DType::Utf8(Nullability::NonNullable)); - let string_list = Scalar::fixed_size_list( - element_dtype, - vec![ - Scalar::utf8("hello", Nullability::NonNullable), - Scalar::utf8("world", Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - assert!(matches!(string_list.dtype(), DType::FixedSizeList(_, 3, _))); - - let list = string_list.as_list(); - assert_eq!( - list.element(0).unwrap().as_utf8().value().unwrap().as_str(), - "hello" - ); - assert_eq!( - list.element(1).unwrap().as_utf8().value().unwrap().as_str(), - "world" - ); - assert_eq!( - list.element(2).unwrap().as_utf8().value().unwrap().as_str(), - "test" - ); - } - - #[test] - fn test_fixed_size_list_nbytes() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - - // FixedSizeList[3] of i32 = 3 * 4 bytes = 12 bytes. - let fixed_list = Scalar::fixed_size_list( - Arc::clone(&element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - assert_eq!(fixed_list.approx_nbytes(), 12); - - // Empty FixedSizeList[0] = 0 bytes. - let empty_list = Scalar::fixed_size_list(element_dtype, vec![], Nullability::NonNullable); - assert_eq!(empty_list.approx_nbytes(), 0); - - // FixedSizeList with strings. - let string_list = Scalar::fixed_size_list( - Arc::new(DType::Utf8(Nullability::NonNullable)), - vec![ - Scalar::utf8("ab", Nullability::NonNullable), // 2 bytes - Scalar::utf8("cde", Nullability::NonNullable), // 3 bytes + Scalar::utf8("ab", Nullability::NonNullable), + Scalar::utf8("cde", Nullability::NonNullable), ], Nullability::NonNullable, ); assert_eq!(string_list.approx_nbytes(), 5); } - - #[test] - fn test_fixed_size_list_casting_with_nullability() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)); - let fixed_list = Scalar::fixed_size_list( - element_dtype, - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::primitive(2i32, Nullability::Nullable), - ], - Nullability::Nullable, - ); - - // Cast to non-nullable container. - let target = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::NonNullable, - ); - let casted = fixed_list.cast(&target).unwrap(); - assert_eq!(casted.dtype().nullability(), Nullability::NonNullable); - - // Cast to non-nullable elements. - let target_nonnull_elems = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::Nullable, - ); - let casted_elems = fixed_list.cast(&target_nonnull_elems).unwrap(); - match casted_elems.dtype() { - DType::FixedSizeList(elem_dtype, ..) => { - assert_eq!(elem_dtype.nullability(), Nullability::NonNullable); - } - _ => panic!("Expected FixedSizeList"), - } - } - - // Additional tests for pure List structures (without FixedSizeList) - - #[test] - fn test_list_of_lists() { - // Create nested lists without FixedSizeList. - let inner_list1 = Scalar::list( - Arc::new(DType::Utf8(Nullability::NonNullable)), - vec![ - Scalar::utf8("a", Nullability::NonNullable), - Scalar::utf8("b", Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let inner_list2 = Scalar::list( - Arc::new(DType::Utf8(Nullability::NonNullable)), - vec![ - Scalar::utf8("c", Nullability::NonNullable), - Scalar::utf8("d", Nullability::NonNullable), - Scalar::utf8("e", Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer_list = Scalar::list( - Arc::new(DType::List( - Arc::new(DType::Utf8(Nullability::NonNullable)), - Nullability::NonNullable, - )), - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - assert_eq!(outer_list.as_list().len(), 2); - assert_eq!(outer_list.as_list().element(0).unwrap().as_list().len(), 2); - assert_eq!(outer_list.as_list().element(1).unwrap().as_list().len(), 3); - } - - #[test] - fn test_struct_only_nesting() { - // Test nested structs without any lists. - let inner_struct_dtype = DType::struct_( - [ - ("x", DType::Primitive(PType::F32, Nullability::NonNullable)), - ("y", DType::Primitive(PType::F32, Nullability::NonNullable)), - ], - Nullability::NonNullable, - ); - - let outer_struct_dtype = DType::struct_( - [ - ("id", DType::Primitive(PType::I64, Nullability::NonNullable)), - ("point", inner_struct_dtype.clone()), - ("name", DType::Utf8(Nullability::NonNullable)), - ], - Nullability::NonNullable, - ); - - let inner_struct = Scalar::struct_( - inner_struct_dtype, - vec![ - Scalar::primitive(1.5f32, Nullability::NonNullable), - Scalar::primitive(2.5f32, Nullability::NonNullable), - ], - ); - - let outer_struct = Scalar::struct_( - outer_struct_dtype, - vec![ - Scalar::primitive(123i64, Nullability::NonNullable), - inner_struct, - Scalar::utf8("test_point", Nullability::NonNullable), - ], - ); - - let struct_view = outer_struct.as_struct(); - assert_eq!( - struct_view - .field("id") - .unwrap() - .as_primitive() - .typed_value::(), - Some(123) - ); - - let point_field = struct_view.field("point").unwrap(); - let point_struct = point_field.as_struct(); - assert_eq!( - point_struct - .field("x") - .unwrap() - .as_primitive() - .typed_value::(), - Some(1.5) - ); - } - - #[test] - fn test_list_of_structs_without_fixed_size() { - // Create a list of structs (no FixedSizeList). - let struct_dtype = DType::struct_( - [ - ("key", DType::Utf8(Nullability::NonNullable)), - ( - "value", - DType::Primitive(PType::I64, Nullability::NonNullable), - ), - ], - Nullability::NonNullable, - ); - - let struct1 = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::utf8("first", Nullability::NonNullable), - Scalar::primitive(100i64, Nullability::NonNullable), - ], - ); - - let struct2 = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::utf8("second", Nullability::NonNullable), - Scalar::primitive(200i64, Nullability::NonNullable), - ], - ); - - let struct3 = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::utf8("third", Nullability::NonNullable), - Scalar::primitive(300i64, Nullability::NonNullable), - ], - ); - - let list_of_structs = Scalar::list( - Arc::new(struct_dtype), - vec![struct1, struct2, struct3], - Nullability::NonNullable, - ); - - assert_eq!(list_of_structs.as_list().len(), 3); - - let first_struct = list_of_structs.as_list().element(0).unwrap(); - assert_eq!( - first_struct - .as_struct() - .field("key") - .unwrap() - .as_utf8() - .value() - .unwrap() - .as_str(), - "first" - ); - } - - #[test] - fn test_struct_containing_list() { - // Create a struct with a List field (not FixedSizeList). - let struct_dtype = DType::struct_( - [ - ("id", DType::Primitive(PType::I32, Nullability::NonNullable)), - ( - "tags", - DType::List( - Arc::new(DType::Utf8(Nullability::NonNullable)), - Nullability::NonNullable, - ), - ), - ("active", DType::Bool(Nullability::NonNullable)), - ], - Nullability::NonNullable, - ); - - let tags_list = Scalar::list( - Arc::new(DType::Utf8(Nullability::NonNullable)), - vec![ - Scalar::utf8("rust", Nullability::NonNullable), - Scalar::utf8("scala", Nullability::NonNullable), - Scalar::utf8("python", Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let struct_with_list = Scalar::struct_( - struct_dtype, - vec![ - Scalar::primitive(42i32, Nullability::NonNullable), - tags_list, - Scalar::bool(true, Nullability::NonNullable), - ], - ); - - let struct_view = struct_with_list.as_struct(); - assert_eq!( - struct_view - .field("id") - .unwrap() - .as_primitive() - .typed_value::(), - Some(42) - ); - - let tags_field = struct_view.field("tags").unwrap(); - assert_eq!(tags_field.as_list().len(), 3); - assert_eq!( - tags_field - .as_list() - .element(0) - .unwrap() - .as_utf8() - .value() - .unwrap() - .as_str(), - "rust" - ); - } - - #[test] - fn test_deeply_nested_lists_only() { - // Create a 3-level nested list structure without any FixedSizeList. - let level3 = Scalar::list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let level2 = Scalar::list( - Arc::new(DType::List( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - Nullability::NonNullable, - )), - vec![level3.clone(), level3], - Nullability::NonNullable, - ); - - let level1 = Scalar::list( - Arc::new(DType::List( - Arc::new(DType::List( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - Nullability::NonNullable, - )), - Nullability::NonNullable, - )), - vec![level2.clone(), level2], - Nullability::NonNullable, - ); - - assert_eq!(level1.as_list().len(), 2); - assert_eq!( - level1 - .as_list() - .element(0) - .unwrap() - .as_list() - .element(0) - .unwrap() - .as_list() - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - } } diff --git a/vortex-array/src/scalar/tests/nullability.rs b/vortex-array/src/scalar/tests/nullability.rs index 9f4c4af9125..8d5c30f0bab 100644 --- a/vortex-array/src/scalar/tests/nullability.rs +++ b/vortex-array/src/scalar/tests/nullability.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Comprehensive nullability testing for nested structures. +//! Focused nullability corner-case tests for [`Scalar`]. +//! +//! General nested nullability, casting, equality, and ordering properties are covered by +//! `scalar::tests::hegel`. #[cfg(test)] mod tests { use std::sync::Arc; - use rstest::rstest; use vortex_error::VortexResult; use crate::dtype::DType; @@ -28,91 +30,39 @@ mod tests { .erased() } - #[rstest] - fn null_cast_to_nullable_dtype( - #[values( - DType::Null, - DType::Bool(Nullability::Nullable), - DType::Primitive(PType::I32, Nullability::Nullable), - DType::Extension(Date::new(TimeUnit::Days, Nullability::Nullable).erased()), - DType::Extension(utc_timestamp()), - )] - source_dtype: DType, - #[values( + #[test] + fn null_cast_to_nullable_dtype() -> VortexResult<()> { + let dtypes = [ DType::Null, DType::Bool(Nullability::Nullable), DType::Primitive(PType::I32, Nullability::Nullable), DType::Extension(Date::new(TimeUnit::Days, Nullability::Nullable).erased()), DType::Extension(utc_timestamp()), - )] - target_dtype: DType, - ) -> VortexResult<()> { - let changes_type = source_dtype != DType::Null && source_dtype != target_dtype; - let involves_extension = source_dtype.is_extension() || target_dtype.is_extension(); - let result = Scalar::null(source_dtype).cast(&target_dtype); - - if changes_type && involves_extension { - assert!(result.is_err()); - return Ok(()); + ]; + + for source_dtype in &dtypes { + for target_dtype in &dtypes { + let changes_type = *source_dtype != DType::Null && source_dtype != target_dtype; + let involves_extension = source_dtype.is_extension() || target_dtype.is_extension(); + let result = Scalar::null(source_dtype.clone()).cast(target_dtype); + + if changes_type && involves_extension { + assert!( + result.is_err(), + "expected {source_dtype} -> {target_dtype} null cast to fail" + ); + } else { + let casted = result?; + assert_eq!(casted.dtype(), target_dtype); + assert!(casted.is_null()); + } + } } - - let casted = result?; - assert_eq!(casted.dtype(), &target_dtype); - assert!(casted.is_null()); Ok(()) } #[test] - fn test_list_cast_nullability_changes() { - let list = Scalar::new( - DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), - Nullability::Nullable, - ), - Some(ScalarValue::Tuple(vec![Some(ScalarValue::Primitive( - PValue::U16(6), - ))])), - ); - - // Change element nullability from Nullable to NonNullable. - let target_elem_nonnull = DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::NonNullable)), - Nullability::Nullable, - ); - let casted = list.cast(&target_elem_nonnull).unwrap(); - assert_eq!(casted.dtype(), &target_elem_nonnull); - assert_eq!( - casted.as_list().elements().unwrap(), - vec![Scalar::from(6u16)] - ); - - // Change list nullability from Nullable to NonNullable. - let target_list_nonnull = DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), - Nullability::NonNullable, - ); - let casted = list.cast(&target_list_nonnull).unwrap(); - assert_eq!(casted.dtype(), &target_list_nonnull); - assert_eq!( - casted.as_list().elements().unwrap(), - vec![Scalar::from(6u16)] - ); - - // Change both element and list nullability. - let target_both_nonnull = DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::NonNullable)), - Nullability::NonNullable, - ); - let casted = list.cast(&target_both_nonnull).unwrap(); - assert_eq!(casted.dtype(), &target_both_nonnull); - assert_eq!( - casted.as_list().elements().unwrap(), - vec![Scalar::from(6u16)] - ); - } - - #[test] - fn test_list_cast_with_null_elements() { + fn test_cast_null_to_nonnull_errors() { let list_with_null = Scalar::new( DType::List( Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), @@ -121,49 +71,62 @@ mod tests { Some(ScalarValue::Tuple(vec![ Some(ScalarValue::Primitive(PValue::U16(6))), None, - Some(ScalarValue::Primitive(PValue::U16(10))), ])), ); - - // Cast to different element type with nullable elements - should succeed. - let target_u8_nullable = DType::List( - Arc::from(DType::Primitive(PType::U8, Nullability::Nullable)), - Nullability::Nullable, + assert!( + list_with_null + .cast(&DType::List( + Arc::from(DType::Primitive(PType::U32, Nullability::NonNullable)), + Nullability::Nullable, + )) + .is_err() ); - let casted = list_with_null.cast(&target_u8_nullable).unwrap(); - assert_eq!(casted.dtype(), &target_u8_nullable); - assert_eq!( - casted.as_list().elements().unwrap(), + + let fsl_with_nulls = Scalar::fixed_size_list( + Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), vec![ - Scalar::from(Some(6u8)), - Scalar::from(None::), - Scalar::from(Some(10u8)) - ] + Scalar::primitive(1i32, Nullability::Nullable), + Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), + ], + Nullability::NonNullable, + ); + assert!( + fsl_with_nulls + .cast(&DType::FixedSizeList( + Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), + 2, + Nullability::NonNullable, + )) + .is_err() ); - // Cast to non-nullable U16 elements should fail because we have null elements. - let target_u16_nonnull = DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::NonNullable)), + let null_fsl = Scalar::null(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), + 2, Nullability::Nullable, - ); - let result = list_with_null.cast(&target_u16_nonnull); + )); assert!( - result.is_err(), - "Expected cast to fail when casting list with null elements to non-nullable element type" + null_fsl + .cast(&DType::FixedSizeList( + Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), + 2, + Nullability::NonNullable, + )) + .is_err() ); } #[test] fn test_scalar_nbytes_with_nulls() { - // Test null string - let null_utf8 = Scalar::null(DType::Utf8(Nullability::Nullable)); - assert_eq!(null_utf8.approx_nbytes(), 0); - - // Test null binary - let null_binary = Scalar::null(DType::Binary(Nullability::Nullable)); - assert_eq!(null_binary.approx_nbytes(), 0); + assert_eq!( + Scalar::null(DType::Utf8(Nullability::Nullable)).approx_nbytes(), + 0 + ); + assert_eq!( + Scalar::null(DType::Binary(Nullability::Nullable)).approx_nbytes(), + 0 + ); - // Test struct with null fields let struct_with_null = Scalar::struct_( DType::struct_( [ @@ -177,10 +140,8 @@ mod tests { Scalar::primitive(100i64, Nullability::NonNullable), ], ); - // Primitive null fields still count their byte width assert_eq!(struct_with_null.approx_nbytes(), 4 + 8); - // Test list with null elements let list_with_null = Scalar::list( Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), vec![ @@ -190,357 +151,59 @@ mod tests { ], Nullability::NonNullable, ); - // Primitive null elements still count their byte width - assert_eq!(list_with_null.approx_nbytes(), 3 * 4); // 3 i32 values (including null) - } - - #[test] - fn test_scalar_is_valid_is_null() { - let valid_scalar = Scalar::primitive(42i32, Nullability::NonNullable); - assert!(valid_scalar.is_valid()); - assert!(!valid_scalar.is_null()); - - let null_scalar = Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)); - assert!(!null_scalar.is_valid()); - assert!(null_scalar.is_null()); - } - - #[test] - fn test_scalar_into_nullable() { - let non_nullable = Scalar::primitive(42i32, Nullability::NonNullable); - assert_eq!(non_nullable.dtype().nullability(), Nullability::NonNullable); - - let nullable = non_nullable.into_nullable(); - assert_eq!(nullable.dtype().nullability(), Nullability::Nullable); - assert_eq!(nullable.as_primitive().typed_value::(), Some(42)); - - // Test with already nullable scalar - let already_nullable = Scalar::primitive(42i32, Nullability::Nullable); - let still_nullable = already_nullable.into_nullable(); - assert_eq!(still_nullable.dtype().nullability(), Nullability::Nullable); - assert_eq!(still_nullable.as_primitive().typed_value::(), Some(42)); + assert_eq!(list_with_null.approx_nbytes(), 3 * 4); } #[test] - fn test_list_cast_null_to_nonnull_error() { - let list_with_null = Scalar::new( - DType::List( - Arc::from(DType::Primitive(PType::U16, Nullability::Nullable)), - Nullability::Nullable, - ), - Some(ScalarValue::Tuple(vec![ - Some(ScalarValue::Primitive(PValue::U16(6))), - None, - ])), - ); - - // Casting to non-nullable element type should fail. - let target_nonnull = DType::List( - Arc::from(DType::Primitive(PType::U32, Nullability::NonNullable)), - Nullability::Nullable, - ); - assert!(list_with_null.cast(&target_nonnull).is_err()); - } - - #[test] - fn test_nested_nullability_propagation() { - // Test null propagation through nested structures. - // Create List of FixedSizeList[2] with nulls at different levels. - - let inner_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - // First inner list: non-null container with one null element. - let inner_list1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::Nullable, - ); - - // Second inner list: null container. - let inner_list2 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - // Third inner list: non-null container with non-null elements. - let inner_list3 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(3i32, Nullability::Nullable), - Scalar::primitive(4i32, Nullability::Nullable), - ], - Nullability::Nullable, - ); - - let outer_list = Scalar::list( - inner_dtype, - vec![inner_list1, inner_list2, inner_list3], - Nullability::NonNullable, - ); - - let outer = outer_list.as_list(); - assert_eq!(outer.len(), 3); - assert!(!outer.is_null()); - - // First inner: not null, but has null element. - let first = outer.element(0).unwrap(); - assert!(!first.is_null()); - assert!(first.as_list().element(1).unwrap().is_null()); - - // Second inner: is null. - let second = outer.element(1).unwrap(); - assert!(second.is_null()); - - // Third inner: not null, no null elements. - let third = outer.element(2).unwrap(); - assert!(!third.is_null()); - assert!(!third.as_list().element(0).unwrap().is_null()); - assert!(!third.as_list().element(1).unwrap().is_null()); - } - - #[test] - fn test_struct_null_field_handling() { - // Test struct with nullable fields including FixedSizeList. - let struct_dtype = DType::struct_( - [ - ("id", DType::Primitive(PType::I32, Nullability::NonNullable)), - ( - "values", - DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - 2, - Nullability::Nullable, - ), - ), - ("name", DType::Utf8(Nullability::Nullable)), - ], - Nullability::NonNullable, - ); - - // Create struct with null FixedSizeList field. - let struct_with_null_list = Scalar::struct_( - struct_dtype.clone(), - vec![ - Scalar::primitive(42i32, Nullability::NonNullable), - Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - 2, - Nullability::Nullable, - )), - Scalar::utf8("test", Nullability::Nullable), - ], - ); - - let struct_view = struct_with_null_list.as_struct(); - assert!(!struct_view.is_null()); - assert!(!struct_view.field("id").unwrap().is_null()); - assert!(struct_view.field("values").unwrap().is_null()); - assert!(!struct_view.field("name").unwrap().is_null()); - - // Create struct with non-null FixedSizeList containing null elements. - let fixed_list_with_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - vec![ - Scalar::primitive(100i64, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)), - ], - Nullability::Nullable, - ); - - let struct_with_list_nulls = Scalar::struct_( - struct_dtype, - vec![ - Scalar::primitive(43i32, Nullability::NonNullable), - fixed_list_with_nulls, - Scalar::null(DType::Utf8(Nullability::Nullable)), - ], - ); - - let struct_view2 = struct_with_list_nulls.as_struct(); - let values_field = struct_view2.field("values").unwrap(); - assert!(!values_field.is_null()); - assert!(values_field.as_list().element(1).unwrap().is_null()); - assert!(struct_view2.field("name").unwrap().is_null()); - } - - #[test] - fn test_list_partial_null_elements() { - // Test List with mixture of null and non-null elements. - let element_dtype = Arc::new(DType::Primitive(PType::F32, Nullability::Nullable)); - let list_with_nulls = Scalar::list( - element_dtype, - vec![ - Scalar::primitive(1.5f32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::F32, Nullability::Nullable)), - Scalar::primitive(2.5f32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::F32, Nullability::Nullable)), - Scalar::primitive(3.5f32, Nullability::Nullable), - ], - Nullability::NonNullable, - ); - - let list = list_with_nulls.as_list(); - assert_eq!(list.len(), 5); - assert!(!list.is_null()); - - // Check null pattern. - assert!(!list.element(0).unwrap().is_null()); - assert!(list.element(1).unwrap().is_null()); - assert!(!list.element(2).unwrap().is_null()); - assert!(list.element(3).unwrap().is_null()); - assert!(!list.element(4).unwrap().is_null()); - } - - #[test] - fn test_cast_null_to_nonnull_errors() { - // Test that casting null elements to non-nullable fails. - - // FixedSizeList with null elements can't cast to non-nullable elements. - let fixed_list_with_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::NonNullable, - ); - - let target_nonnull_elems = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - ); - - let result = fixed_list_with_nulls.cast(&target_nonnull_elems); - assert!(result.is_err()); - - // Null FixedSizeList can't cast to non-nullable container. - let null_fixed_list = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), + fn test_null_container_distinct_from_container_of_nulls() { + let elem = Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)); + let null_list = Scalar::null(DType::FixedSizeList( + Arc::clone(&elem), 2, Nullability::Nullable, )); - - let target_nonnull_container = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::NonNullable, - ); - - let result = null_fixed_list.cast(&target_nonnull_container); - assert!(result.is_err()); - } - - #[test] - fn test_nullable_to_nonnullable_valid_cast() { - // Test that casting nullable types to non-nullable succeeds when no nulls present. - let fixed_list_no_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(10i32, Nullability::Nullable), - Scalar::primitive(20i32, Nullability::Nullable), - ], - Nullability::Nullable, - ); - - // Should succeed - no actual nulls. - let target = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - 2, - Nullability::NonNullable, - ); - - let casted = fixed_list_no_nulls.cast(&target).unwrap(); - assert_eq!(casted.dtype(), &target); - assert_eq!( - casted.as_list().elements().unwrap(), - vec![Scalar::from(10i32), Scalar::from(20i32)] - ); - match casted.dtype() { - DType::FixedSizeList(elem_dtype, ..) => { - assert_eq!(elem_dtype.nullability(), Nullability::NonNullable); - } - _ => panic!("Expected FixedSizeList"), - } - } - - #[test] - fn test_is_null_vs_has_null_elements() { - // Distinguish between a null container and a container with null elements. - - // Case 1: Null FixedSizeList. - let null_list = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), + let null_list_diff_size = Scalar::null(DType::FixedSizeList( + Arc::clone(&elem), 3, Nullability::Nullable, )); - assert!(null_list.is_null()); - - // Case 2: Non-null FixedSizeList with all null elements. - let list_all_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), + let list_of_nulls = Scalar::fixed_size_list( + elem, vec![ Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), ], Nullability::Nullable, ); - assert!(!list_all_nulls.is_null()); // Container is not null. - assert!(list_all_nulls.as_list().element(0).unwrap().is_null()); - assert!(list_all_nulls.as_list().element(1).unwrap().is_null()); - assert!(list_all_nulls.as_list().element(2).unwrap().is_null()); - // Case 3: Non-null FixedSizeList with some null elements. - let list_some_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Scalar::primitive(3i32, Nullability::Nullable), - ], - Nullability::NonNullable, - ); - assert!(!list_some_nulls.is_null()); - assert!(!list_some_nulls.as_list().element(0).unwrap().is_null()); - assert!(list_some_nulls.as_list().element(1).unwrap().is_null()); - assert!(!list_some_nulls.as_list().element(2).unwrap().is_null()); + assert!(null_list.is_null()); + assert!(!null_list.is_valid()); + assert!(list_of_nulls.is_valid()); + assert_ne!(null_list, list_of_nulls); + assert_ne!(null_list, null_list_diff_size); } #[test] fn test_default_values_with_nullable_nested() { - // Test default value creation for nullable nested structures. - - // Default value for nullable FixedSizeList should be null. - let nullable_fixed_list_dtype = DType::FixedSizeList( + let nullable_fsl = DType::FixedSizeList( Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), 3, Nullability::Nullable, ); - let default_nullable_list = Scalar::default_value(&nullable_fixed_list_dtype); - assert!(default_nullable_list.is_null()); - assert_eq!(default_nullable_list.dtype(), &nullable_fixed_list_dtype); + let default_nullable = Scalar::default_value(&nullable_fsl); + assert!(default_nullable.is_null()); + assert_eq!(default_nullable.dtype(), &nullable_fsl); - // Default value for non-nullable FixedSizeList should be empty (if size=0) or have default elements. - let nonnull_fixed_list_dtype = DType::FixedSizeList( + let nonnull_fsl = DType::FixedSizeList( Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), 2, Nullability::NonNullable, ); - let default_nonnull_list = Scalar::default_value(&nonnull_fixed_list_dtype); - assert!(!default_nonnull_list.is_null()); - assert_eq!(default_nonnull_list.as_list().len(), 2); - // Elements should be default values (0 for I32). + let default_nonnull = Scalar::default_value(&nonnull_fsl); + assert!(!default_nonnull.is_null()); + assert_eq!(default_nonnull.as_list().len(), 2); assert_eq!( - default_nonnull_list + default_nonnull .as_list() .element(0) .unwrap() @@ -548,280 +211,5 @@ mod tests { .typed_value::(), Some(0) ); - - // Default value for struct with nullable FixedSizeList field. - let struct_dtype = DType::struct_( - [ - ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), - ( - "b", - DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - 2, - Nullability::Nullable, - ), - ), - ], - Nullability::NonNullable, - ); - let default_struct = Scalar::default_value(&struct_dtype); - let struct_view = default_struct.as_struct(); - assert_eq!( - struct_view - .field("a") - .unwrap() - .as_primitive() - .typed_value::(), - Some(0) - ); - assert!(struct_view.field("b").unwrap().is_null()); - } - - #[test] - fn test_deeply_nested_nullability() { - // Test nullability at 3+ levels of nesting. - // FixedSizeList[2] of List of FixedSizeList[2] with nulls at various levels. - - let innermost_dtype = Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - let middle_dtype = Arc::new(DType::List( - Arc::clone(&innermost_dtype), - Nullability::Nullable, - )); - - // Create innermost FixedSizeLists with different null patterns. - let inner1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::Nullable, - ); - - let inner2 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - // Create middle Lists. - let middle1 = Scalar::list( - Arc::clone(&innermost_dtype), - vec![inner1, inner2], - Nullability::Nullable, - ); - - let middle2 = Scalar::null(DType::List(innermost_dtype, Nullability::Nullable)); - - // Create outer FixedSizeList. - let outer = Scalar::fixed_size_list( - middle_dtype, - vec![middle1, middle2], - Nullability::NonNullable, - ); - - assert!(!outer.is_null()); - - let outer_list = outer.as_list(); - - // First middle list is not null but contains a null element. - let first_middle = outer_list.element(0).unwrap(); - assert!(!first_middle.is_null()); - assert!(first_middle.as_list().element(1).unwrap().is_null()); - - // Second middle list is null. - let second_middle = outer_list.element(1).unwrap(); - assert!(second_middle.is_null()); - } - - #[test] - fn test_fixed_size_list_null_equality() { - // Test equality comparisons with null FixedSizeLists. - let null_list1 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - let null_list2 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - assert_eq!(null_list1, null_list2); - - // Different sizes should still be equal if both null. - let null_list3 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 3, - Nullability::Nullable, - )); - - // These have different types, so they should not be equal. - assert_ne!(null_list1, null_list3); - - // Non-null list with null elements vs null list. - let list_with_nulls = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::Nullable, - ); - - assert_ne!(null_list1, list_with_nulls); - } - - #[test] - fn test_struct_with_multiple_nullable_lists() { - // Test struct with multiple nullable list fields. - let struct_dtype = DType::struct_( - [ - ( - "fixed_list", - DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - 2, - Nullability::Nullable, - ), - ), - ( - "var_list", - DType::List( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - Nullability::Nullable, - ), - ), - ( - "nested_fixed", - DType::FixedSizeList( - Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - 2, - Nullability::Nullable, - )), - 2, - Nullability::Nullable, - ), - ), - ], - Nullability::NonNullable, - ); - - // Create struct with mixed null patterns. - let fixed_list_field = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(10i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::Nullable, - ); - - let var_list_field = Scalar::null(DType::List( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - Nullability::Nullable, - )); - - let inner_fixed1 = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - vec![ - Scalar::primitive(1u8, Nullability::Nullable), - Scalar::primitive(2u8, Nullability::Nullable), - ], - Nullability::Nullable, - ); - - let inner_fixed2 = Scalar::null(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - 2, - Nullability::Nullable, - )); - - let nested_fixed_field = Scalar::fixed_size_list( - Arc::new(DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - 2, - Nullability::Nullable, - )), - vec![inner_fixed1, inner_fixed2], - Nullability::Nullable, - ); - - let struct_scalar = Scalar::struct_( - struct_dtype, - vec![fixed_list_field, var_list_field, nested_fixed_field], - ); - - let struct_view = struct_scalar.as_struct(); - - // Check fixed_list field: not null, but has null element. - let fixed_field = struct_view.field("fixed_list").unwrap(); - assert!(!fixed_field.is_null()); - assert!(fixed_field.as_list().element(1).unwrap().is_null()); - - // Check var_list field: is null. - assert!(struct_view.field("var_list").unwrap().is_null()); - - // Check nested_fixed field: not null, but second element is null. - let nested_field = struct_view.field("nested_fixed").unwrap(); - assert!(!nested_field.is_null()); - assert!(nested_field.as_list().element(1).unwrap().is_null()); - } - - #[test] - fn test_casting_preserves_null_positions() { - // Ensure that casting preserves the positions of null elements. - let fixed_list = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)), - vec![ - Scalar::primitive(1i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Scalar::primitive(3i32, Nullability::Nullable), - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - ], - Nullability::NonNullable, - ); - - // Cast to I64. - let target = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)), - 4, - Nullability::NonNullable, - ); - - let casted = fixed_list.cast(&target).unwrap(); - let casted_list = casted.as_list(); - - // Verify null positions are preserved. - assert!(!casted_list.element(0).unwrap().is_null()); - assert!(casted_list.element(1).unwrap().is_null()); - assert!(!casted_list.element(2).unwrap().is_null()); - assert!(casted_list.element(3).unwrap().is_null()); - - // Verify non-null values were cast correctly. - assert_eq!( - casted_list - .element(0) - .unwrap() - .as_primitive() - .typed_value::(), - Some(1) - ); - assert_eq!( - casted_list - .element(2) - .unwrap() - .as_primitive() - .typed_value::(), - Some(3) - ); } } diff --git a/vortex-array/src/scalar/tests/primitives.rs b/vortex-array/src/scalar/tests/primitives.rs index ba9840ee617..6c8099cf5c2 100644 --- a/vortex-array/src/scalar/tests/primitives.rs +++ b/vortex-array/src/scalar/tests/primitives.rs @@ -1,10 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for primitive scalar types, utility functions, and basic operations. +//! Tests for scalar utility methods (`default_value`, `zero_value`, `is_zero`, `approx_nbytes`, +//! `From` conversions, and union identity/ordering semantics). #[cfg(test)] mod tests { + use std::cmp::Ordering; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; @@ -12,7 +14,6 @@ mod tests { use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; - use vortex_utils::aliases::hash_set::HashSet; use crate::dtype::DType; use crate::dtype::DecimalDType; @@ -68,79 +69,61 @@ mod tests { let scalar = Scalar::default_value(&struct_dtype); assert_eq!(scalar.dtype(), &struct_dtype); - - let scalar = scalar.as_struct(); - - let a_field = scalar.field("a").unwrap(); - assert_eq!(a_field.as_primitive().pvalue().unwrap(), PValue::I32(0)); - - let b_field = scalar.field("b").unwrap(); - assert!(b_field.as_list().is_empty()); - - let c_field = scalar.field("c").unwrap(); - assert!(c_field.is_null()); + let s = scalar.as_struct(); + assert_eq!( + s.field("a").unwrap().as_primitive().pvalue(), + Some(PValue::I32(0)) + ); + assert!(s.field("b").unwrap().as_list().is_empty()); + assert!(s.field("c").unwrap().is_null()); } #[test] - fn default_value_for_nullable_union_is_null() -> VortexResult<()> { + fn union_default_zero_and_is_zero() -> VortexResult<()> { let nullable = DType::Union( union_variants(Nullability::Nullable, Nullability::NonNullable)?, Nullability::Nullable, ); + let default_nullable = Scalar::default_value(&nullable); + assert!(default_nullable.is_null()); + assert_eq!(default_nullable.is_zero(), None); - let scalar = Scalar::default_value(&nullable); - assert!(scalar.is_null()); - assert_eq!(scalar.dtype(), &nullable); - - Ok(()) - } - - #[test] - fn default_value_for_non_nullable_union_selects_first_variant() -> VortexResult<()> { let non_nullable = DType::Union( union_variants(Nullability::Nullable, Nullability::NonNullable)?, Nullability::NonNullable, ); - - let scalar = Scalar::default_value(&non_nullable); - assert_eq!(scalar.dtype(), &non_nullable); - let union = scalar.as_union(); - - assert!(!scalar.is_null()); - assert!(!union.is_null()); - assert_eq!(union.type_id(), Some(5)); - assert!(union.child().is_some_and(|child| child.is_null())); - assert_eq!(scalar.is_zero(), None); - - Ok(()) - } - - #[test] - fn union_zero_value_selects_first_variant() -> VortexResult<()> { - let dtype = DType::Union( - union_variants(Nullability::Nullable, Nullability::NonNullable)?, - Nullability::Nullable, + let default_nonnull = Scalar::default_value(&non_nullable); + assert!(!default_nonnull.is_null()); + assert_eq!(default_nonnull.as_union().type_id(), Some(5)); + assert!( + default_nonnull + .as_union() + .child() + .is_some_and(|c| c.is_null()) ); + assert_eq!(default_nonnull.is_zero(), None); - let scalar = Scalar::zero_value(&dtype); - assert_eq!(scalar.dtype(), &dtype); - let union = scalar.as_union(); - - assert!(!scalar.is_null()); - assert!(!union.is_null()); - assert_eq!(union.type_id(), Some(5)); + let zero = Scalar::zero_value(&nullable); + assert!(!zero.is_null()); + assert_eq!(zero.as_union().type_id(), Some(5)); assert_eq!( - union.child(), + zero.as_union().child(), Some(Scalar::primitive(0_i32, Nullability::Nullable)) ); - assert_eq!(scalar.is_zero(), Some(true)); + assert_eq!(zero.is_zero(), Some(true)); - Ok(()) - } + let variants = union_variants(Nullability::NonNullable, Nullability::NonNullable)?; + let first_nonzero = Scalar::union( + variants.clone(), + 5, + Scalar::from(1_i32), + Nullability::NonNullable, + )?; + let second_zero = Scalar::union(variants, 9, Scalar::from(""), Nullability::NonNullable)?; + assert_eq!(first_nonzero.is_zero(), Some(false)); + assert_eq!(second_zero.is_zero(), Some(false)); - #[test] - fn union_has_no_zero_value_when_first_variant_is_null() -> VortexResult<()> { - let variants = UnionVariants::try_new( + let null_first = UnionVariants::try_new( ["null", "int"].into(), vec![ DType::Null, @@ -148,95 +131,66 @@ mod tests { ], vec![5, 9], )?; - let dtype = DType::Union(variants.clone(), Nullability::NonNullable); - let scalar = Scalar::union( - variants, + let null_first_dtype = DType::Union(null_first.clone(), Nullability::NonNullable); + assert_eq!(ScalarValue::try_zero_value(&null_first_dtype), None); + let null_first_scalar = Scalar::union( + null_first, 5, Scalar::null(DType::Null), Nullability::NonNullable, )?; - - assert_eq!(ScalarValue::try_zero_value(&dtype), None); - assert_eq!(scalar.is_zero(), None); - - Ok(()) - } - - #[test] - fn union_is_zero_requires_first_variant_and_zero_child() -> VortexResult<()> { - let variants = union_variants(Nullability::NonNullable, Nullability::NonNullable)?; - let first_zero = Scalar::union( - variants.clone(), - 5, - Scalar::from(0_i32), - Nullability::NonNullable, - )?; - let first_nonzero = Scalar::union( - variants.clone(), - 5, - Scalar::from(1_i32), - Nullability::NonNullable, - )?; - let second_zero = Scalar::union( - variants.clone(), - 9, - Scalar::from(""), - Nullability::NonNullable, - )?; - let null = Scalar::null(DType::Union(variants, Nullability::Nullable)); - - assert_eq!(first_zero.is_zero(), Some(true)); - assert_eq!(first_nonzero.is_zero(), Some(false)); - assert_eq!(second_zero.is_zero(), Some(false)); - assert_eq!(null.is_zero(), None); - + assert_eq!(null_first_scalar.is_zero(), None); Ok(()) } #[test] fn test_scalar_nbytes() -> VortexResult<()> { - // Test null scalar - should be 0 bytes - let null_scalar = Scalar::null(DType::Null); - assert_eq!(null_scalar.approx_nbytes(), 0); - - // Test bool scalar - should be 1 byte - let bool_scalar = Scalar::bool(true, Nullability::NonNullable); - assert_eq!(bool_scalar.approx_nbytes(), 1); - - // Test primitive scalars - let u8_scalar = Scalar::primitive(42u8, Nullability::NonNullable); - assert_eq!(u8_scalar.approx_nbytes(), 1); - - let u16_scalar = Scalar::primitive(1000u16, Nullability::NonNullable); - assert_eq!(u16_scalar.approx_nbytes(), 2); - - let u32_scalar = Scalar::primitive(100000u32, Nullability::NonNullable); - assert_eq!(u32_scalar.approx_nbytes(), 4); - - let u64_scalar = Scalar::primitive(10000000000u64, Nullability::NonNullable); - assert_eq!(u64_scalar.approx_nbytes(), 8); - - let f32_scalar = Scalar::primitive(3.5f32, Nullability::NonNullable); - assert_eq!(f32_scalar.approx_nbytes(), 4); - - let f64_scalar = Scalar::primitive(3.5f64, Nullability::NonNullable); - assert_eq!(f64_scalar.approx_nbytes(), 8); - - // Test UTF-8 scalar - let utf8_scalar = Scalar::utf8("hello", Nullability::NonNullable); - assert_eq!(utf8_scalar.approx_nbytes(), 5); - - let empty_utf8 = Scalar::utf8("", Nullability::NonNullable); - assert_eq!(empty_utf8.approx_nbytes(), 0); - - // Test binary scalar - let binary_scalar = Scalar::binary( - ByteBuffer::from(vec![1u8, 2, 3, 4]), - Nullability::NonNullable, + assert_eq!(Scalar::null(DType::Null).approx_nbytes(), 0); + assert_eq!( + Scalar::bool(true, Nullability::NonNullable).approx_nbytes(), + 1 + ); + assert_eq!( + Scalar::primitive(42u8, Nullability::NonNullable).approx_nbytes(), + 1 + ); + assert_eq!( + Scalar::primitive(1000u16, Nullability::NonNullable).approx_nbytes(), + 2 + ); + assert_eq!( + Scalar::primitive(100_000u32, Nullability::NonNullable).approx_nbytes(), + 4 + ); + assert_eq!( + Scalar::primitive(10_000_000_000u64, Nullability::NonNullable).approx_nbytes(), + 8 + ); + assert_eq!( + Scalar::primitive(3.5f32, Nullability::NonNullable).approx_nbytes(), + 4 + ); + assert_eq!( + Scalar::primitive(3.5f64, Nullability::NonNullable).approx_nbytes(), + 8 + ); + assert_eq!( + Scalar::utf8("hello", Nullability::NonNullable).approx_nbytes(), + 5 + ); + assert_eq!( + Scalar::utf8("", Nullability::NonNullable).approx_nbytes(), + 0 + ); + assert_eq!( + Scalar::binary( + ByteBuffer::from(vec![1u8, 2, 3, 4]), + Nullability::NonNullable + ) + .approx_nbytes(), + 4 ); - assert_eq!(binary_scalar.approx_nbytes(), 4); - // Test struct scalar let struct_scalar = Scalar::struct_( DType::struct_( [ @@ -250,9 +204,8 @@ mod tests { Scalar::primitive(100i64, Nullability::NonNullable), ], ); - assert_eq!(struct_scalar.approx_nbytes(), 4 + 8); // i32 + i64 + assert_eq!(struct_scalar.approx_nbytes(), 12); - // Test list scalar let list_scalar = Scalar::list( Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), vec![ @@ -262,16 +215,14 @@ mod tests { ], Nullability::NonNullable, ); - assert_eq!(list_scalar.approx_nbytes(), 3 * 4); // 3 * i32 + assert_eq!(list_scalar.approx_nbytes(), 12); - // Test extension scalar let ext_scalar = Scalar::extension::( TimeUnit::Days, Scalar::primitive(42i32, Nullability::NonNullable), ); - assert_eq!(ext_scalar.approx_nbytes(), 4); // i32 storage + assert_eq!(ext_scalar.approx_nbytes(), 4); - // Test union scalar: one-byte type ID plus selected child. let variants = union_variants(Nullability::Nullable, Nullability::NonNullable)?; let union_scalar = Scalar::union( variants.clone(), @@ -279,7 +230,6 @@ mod tests { Scalar::primitive(42_i32, Nullability::Nullable), Nullability::Nullable, )?; - assert_eq!( union_scalar.approx_nbytes(), size_of::() + size_of::() @@ -298,327 +248,110 @@ mod tests { Scalar::null(DType::Union(variants, Nullability::Nullable)).approx_nbytes(), 0 ); - Ok(()) } #[test] fn test_decimal_nbytes() { - // Test decimal with precision <= 38 (should use i128 = 16 bytes) - let decimal_low_precision = Scalar::decimal( - DecimalValue::I128(123456789), - DecimalDType::new(i128::MAX_PRECISION, 2), // precision 38 - Nullability::NonNullable, - ); - assert_eq!( - decimal_low_precision.approx_nbytes(), - 16, - "Decimals with precision <= 38 should be 16 bytes (i128)" - ); - - // Test decimal with precision > 38 (should use i256 = 32 bytes) - let decimal_high_precision = Scalar::decimal( - DecimalValue::I128(123456789), - DecimalDType::new(i128::MAX_PRECISION + 1, 2), // precision 39 - Nullability::NonNullable, - ); - assert_eq!( - decimal_high_precision.approx_nbytes(), - 32, - "Decimals with precision > 38 should be 32 bytes (i256)" - ); - - // Test various precision boundaries - let decimal_p10 = Scalar::decimal( - DecimalValue::I32(12345), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - assert_eq!( - decimal_p10.approx_nbytes(), - 16, - "Decimal with precision 10 should be 16 bytes" - ); - - let decimal_p38 = Scalar::decimal( - DecimalValue::I64(123456789), - DecimalDType::new(38, 4), - Nullability::NonNullable, - ); - assert_eq!( - decimal_p38.approx_nbytes(), - 16, - "Decimal with precision 38 should be 16 bytes" - ); - - let decimal_p50 = Scalar::decimal( - DecimalValue::I128(123456789), - DecimalDType::new(50, 5), - Nullability::NonNullable, - ); - assert_eq!( - decimal_p50.approx_nbytes(), - 32, - "Decimal with precision 50 should be 32 bytes" - ); - - // Test null decimal - should still report size based on precision - let null_decimal_low = Scalar::null(DType::Decimal( - DecimalDType::new(20, 2), - Nullability::Nullable, - )); - assert_eq!( - null_decimal_low.approx_nbytes(), - 16, - "Null decimal with low precision should still report 16 bytes" - ); - - let null_decimal_high = Scalar::null(DType::Decimal( - DecimalDType::new(40, 2), - Nullability::Nullable, - )); - assert_eq!( - null_decimal_high.approx_nbytes(), - 32, - "Null decimal with high precision should still report 32 bytes" - ); + for (precision, expected) in [ + (10, 16), + (i128::MAX_PRECISION, 16), + (i128::MAX_PRECISION + 1, 32), + (50, 32), + ] { + let s = Scalar::decimal( + DecimalValue::I128(12345), + DecimalDType::new(precision, 2), + Nullability::NonNullable, + ); + assert_eq!(s.approx_nbytes(), expected); + let null_s = Scalar::null(DType::Decimal( + DecimalDType::new(precision, 2), + Nullability::Nullable, + )); + assert_eq!(null_s.approx_nbytes(), expected); + } } #[test] - fn test_scalar_into_parts() { - let scalar = Scalar::primitive(42i32, Nullability::NonNullable); - let (dtype, value) = scalar.into_parts(); - + fn test_scalar_conversions_and_parts() -> VortexResult<()> { + let (dtype, value) = Scalar::primitive(42i32, Nullability::NonNullable).into_parts(); assert_eq!( dtype, DType::Primitive(PType::I32, Nullability::NonNullable) ); - match value { - Some(ScalarValue::Primitive(PValue::I32(v))) => { - assert_eq!(v, 42); - } - _ => panic!("Expected I32 primitive value"), - } - } - - #[test] - fn test_scalar_into_value() { - let scalar = Scalar::primitive(42i32, Nullability::NonNullable); - let value = scalar.into_value(); - - match value { - Some(ScalarValue::Primitive(PValue::I32(v))) => { - assert_eq!(v, 42); - } - _ => panic!("Expected I32 primitive value"), - } - } - - #[test] - fn test_scalar_from_option() { - // Test Some value - let some_value: Option = Some(42); - let scalar = Scalar::from(some_value); + assert_eq!(value, Some(ScalarValue::Primitive(PValue::I32(42)))); assert_eq!( - scalar.dtype(), - &DType::Primitive(PType::I32, Nullability::Nullable) + Scalar::primitive(42i32, Nullability::NonNullable).into_value(), + Some(ScalarValue::Primitive(PValue::I32(42))) ); - assert_eq!(scalar.as_primitive().typed_value::(), Some(42)); - // Test None value - let none_value: Option = None; - let null_scalar = Scalar::from(none_value); + let pscalar = + PrimitiveScalar::try_new(&dtype, Some(&ScalarValue::Primitive(PValue::I32(42))))?; assert_eq!( - null_scalar.dtype(), - &DType::Primitive(PType::I32, Nullability::Nullable) + Scalar::from(pscalar).as_primitive().typed_value::(), + Some(42) ); - assert!(null_scalar.is_null()); - } - - #[test] - fn test_scalar_from_primitive_scalar() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let pscalar = - PrimitiveScalar::try_new(&dtype, Some(&ScalarValue::Primitive(PValue::I32(42)))) - .unwrap(); - let scalar = Scalar::from(pscalar); - assert_eq!(scalar.dtype(), &dtype); - assert_eq!(scalar.as_primitive().typed_value::(), Some(42)); - } - - #[test] - fn test_scalar_from_decimal_scalar() { - let decimal_dtype = DecimalDType::new(10, 2); - let dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable); + let dec_dtype = DType::Decimal(DecimalDType::new(10, 2), Nullability::NonNullable); let dscalar = DecimalScalar::try_new( - &dtype, + &dec_dtype, Some(&ScalarValue::Decimal(DecimalValue::I32(12345))), - ) - .unwrap(); - - let scalar = Scalar::from(dscalar); - assert_eq!(scalar.dtype(), &dtype); + )?; assert_eq!( - scalar.as_decimal().decimal_value(), + Scalar::from(dscalar).as_decimal().decimal_value(), Some(DecimalValue::I32(12345)) ); - } - #[test] - fn test_scalar_from_vec_macros() -> VortexResult<()> { - let scalar = Scalar::from(vec![1u16, 2, 3]); assert_eq!( - scalar.dtype(), - &DType::list( - DType::Primitive(PType::U16, Nullability::NonNullable), - Nullability::NonNullable, - ) + Vec::::try_from(&Scalar::from(vec![1u16, 2, 3]))?, + vec![1, 2, 3] ); - assert_eq!(Vec::::try_from(&scalar)?, vec![1, 2, 3]); - - let scalar = Scalar::from(vec![10i32, 20, 30]); assert_eq!( - scalar.dtype(), - &DType::list( - DType::Primitive(PType::I32, Nullability::NonNullable), - Nullability::NonNullable, - ) + Vec::::try_from(&Scalar::from(vec![10i32, 20, 30]))?, + vec![10, 20, 30] ); - assert_eq!(Vec::::try_from(&scalar)?, vec![10, 20, 30]); - - let scalar = Scalar::from(vec![1.1f64, 2.2, 3.3]); assert_eq!( - scalar.dtype(), - &DType::list( - DType::Primitive(PType::F64, Nullability::NonNullable), - Nullability::NonNullable, - ) + Vec::::try_from(&Scalar::from(vec![1.1f64, 2.2, 3.3]))?, + vec![1.1, 2.2, 3.3] ); - assert_eq!(Vec::::try_from(&scalar)?, vec![1.1, 2.2, 3.3]); - - let scalar = Scalar::from(vec!["hello".to_string(), "world".to_string()]); assert_eq!( - scalar.dtype(), - &DType::list( - DType::Utf8(Nullability::NonNullable), - Nullability::NonNullable, - ) + Vec::::try_from(&Scalar::from(vec![ + "hello".to_string(), + "world".to_string() + ]))?, + vec!["hello", "world"] ); - assert_eq!(Vec::::try_from(&scalar)?, vec!["hello", "world"]); + assert_eq!(Scalar::from(42i32).partial_cmp(&Scalar::from(true)), None); Ok(()) } #[test] - fn test_scalar_hash() { - let mut set = HashSet::new(); - - // Add various scalar types - set.insert(Scalar::null(DType::Null)); - set.insert(Scalar::bool(true, Nullability::NonNullable)); - set.insert(Scalar::primitive(42i32, Nullability::NonNullable)); - set.insert(Scalar::utf8("test", Nullability::NonNullable)); - - // Test that duplicates are not added - assert_eq!(set.len(), 4); - set.insert(Scalar::primitive(42i32, Nullability::NonNullable)); - assert_eq!(set.len(), 4); // Should still be 4 - - // Distinct values remain distinct set entries even if their hashes collide. - set.insert(Scalar::primitive(43i32, Nullability::NonNullable)); - assert_eq!(set.len(), 5); - } - - #[test] - fn test_scalar_hash_ignores_nested_nullability() { - let nullable = Scalar::list( - DType::Primitive(PType::I32, Nullability::Nullable), - vec![Scalar::primitive(42_i32, Nullability::Nullable)], - Nullability::NonNullable, - ); - let non_nullable = Scalar::list( - DType::Primitive(PType::I32, Nullability::NonNullable), - vec![Scalar::primitive(42_i32, Nullability::NonNullable)], - Nullability::NonNullable, - ); - - assert_eq!(nullable, non_nullable); - assert_eq!(scalar_hash(&nullable), scalar_hash(&non_nullable)); - } - - #[test] - fn test_union_scalar_equality_ignores_variant_nullability() -> VortexResult<()> { + fn test_union_identity_nullability_and_ordering() -> VortexResult<()> { let lhs_variants = union_variants(Nullability::Nullable, Nullability::NonNullable)?; let rhs_variants = union_variants(Nullability::NonNullable, Nullability::Nullable)?; - let lhs = Scalar::union( lhs_variants.clone(), 5, Scalar::primitive(42_i32, Nullability::Nullable), Nullability::Nullable, )?; - let rhs = Scalar::union( rhs_variants.clone(), 5, Scalar::primitive(42_i32, Nullability::NonNullable), Nullability::NonNullable, )?; - assert_eq!(lhs, rhs); - - let lhs_null = Scalar::null(DType::Union(lhs_variants, Nullability::Nullable)); - let rhs_null = Scalar::null(DType::Union(rhs_variants, Nullability::Nullable)); - - assert_eq!(lhs_null, rhs_null); - - Ok(()) - } - - #[test] - fn test_scalar_partial_ord_incompatible_types() { - let int_scalar = Scalar::primitive(42i32, Nullability::NonNullable); - let bool_scalar = Scalar::bool(true, Nullability::NonNullable); - - // Different types should return None for partial_cmp - assert_eq!(int_scalar.partial_cmp(&bool_scalar), None); - assert_eq!(bool_scalar.partial_cmp(&int_scalar), None); - } - - #[test] - fn test_scalar_partial_ord_same_type() { - let scalar1 = Scalar::primitive(10i32, Nullability::NonNullable); - let scalar2 = Scalar::primitive(20i32, Nullability::NonNullable); - let scalar3 = Scalar::primitive(10i32, Nullability::NonNullable); - - assert_eq!( - scalar1.partial_cmp(&scalar2), - Some(std::cmp::Ordering::Less) - ); - assert_eq!( - scalar2.partial_cmp(&scalar1), - Some(std::cmp::Ordering::Greater) - ); + assert_eq!(scalar_hash(&lhs), scalar_hash(&rhs)); assert_eq!( - scalar1.partial_cmp(&scalar3), - Some(std::cmp::Ordering::Equal) + Scalar::null(DType::Union(lhs_variants, Nullability::Nullable)), + Scalar::null(DType::Union(rhs_variants, Nullability::Nullable)) ); - } - #[test] - fn test_scalar_eq() { - let scalar1 = Scalar::primitive(42i32, Nullability::NonNullable); - let scalar2 = Scalar::primitive(42i32, Nullability::NonNullable); - let scalar3 = Scalar::primitive(43i32, Nullability::NonNullable); - - assert_eq!(scalar1, scalar2); - assert_ne!(scalar1, scalar3); - } - - #[test] - fn test_union_type_id_is_part_of_value_identity() -> VortexResult<()> { - let variants = UnionVariants::try_new( + // Distinct type IDs with identical child values are not equal or orderable. + let dup_variants = UnionVariants::try_new( ["left", "right"].into(), vec![ DType::Primitive(PType::I32, Nullability::NonNullable), @@ -627,95 +360,45 @@ mod tests { vec![3, 8], )?; let left = Scalar::union( - variants.clone(), + dup_variants.clone(), 3, - Scalar::primitive(42_i32, Nullability::NonNullable), + Scalar::from(10_i32), + Nullability::NonNullable, + )?; + let left_hi = Scalar::union( + dup_variants.clone(), + 3, + Scalar::from(20_i32), Nullability::NonNullable, )?; - let right = Scalar::union( - variants, + dup_variants, 8, - Scalar::primitive(42_i32, Nullability::NonNullable), + Scalar::from(10_i32), Nullability::NonNullable, )?; - assert_ne!(left, right); assert_eq!(left.partial_cmp(&right), None); + assert_eq!(left.partial_cmp(&left_hi), Some(Ordering::Less)); - Ok(()) - } - - #[test] - fn union_values_with_same_type_id_are_ordered_by_selected_child() -> VortexResult<()> { - let variants = UnionVariants::try_new( - ["int"].into(), - vec![DType::Primitive(PType::I32, Nullability::NonNullable)], - vec![3], - )?; - let smaller = Scalar::union( - variants.clone(), - 3, - Scalar::primitive(10_i32, Nullability::NonNullable), - Nullability::NonNullable, - )?; - let larger = Scalar::union( - variants, - 3, - Scalar::primitive(20_i32, Nullability::NonNullable), - Nullability::NonNullable, - )?; - - assert_eq!(smaller.partial_cmp(&larger), Some(std::cmp::Ordering::Less)); - assert_eq!( - larger.partial_cmp(&smaller), - Some(std::cmp::Ordering::Greater) - ); - - Ok(()) - } - - #[test] - fn selected_null_union_children_preserve_type_id() -> VortexResult<()> { - let variants = UnionVariants::try_new( - ["int", "string"].into(), - vec![ - DType::Primitive(PType::I32, Nullability::Nullable), - DType::Utf8(Nullability::Nullable), - ], - vec![3, 8], - )?; + // Selected null children preserve their type ID and differ from outer null. + let nullable_variants = union_variants(Nullability::Nullable, Nullability::Nullable)?; let int_null = Scalar::union( - variants.clone(), - 3, - Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), - Nullability::NonNullable, - )?; - let same_int_null = Scalar::union( - variants.clone(), - 3, + nullable_variants.clone(), + 5, Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), Nullability::NonNullable, )?; - let string_null = Scalar::union( - variants.clone(), - 8, + let str_null = Scalar::union( + nullable_variants.clone(), + 9, Scalar::null(DType::Utf8(Nullability::Nullable)), Nullability::NonNullable, )?; - let outer_null = Scalar::null(DType::Union(variants, Nullability::Nullable)); - - assert_eq!(int_null, same_int_null); - assert_eq!( - int_null.partial_cmp(&same_int_null), - Some(std::cmp::Ordering::Equal) - ); - assert_eq!(scalar_hash(&int_null), scalar_hash(&same_int_null)); - - assert_ne!(int_null, string_null); - assert_eq!(int_null.partial_cmp(&string_null), None); + let outer_null = Scalar::null(DType::Union(nullable_variants, Nullability::Nullable)); + assert_ne!(int_null, str_null); + assert_eq!(int_null.partial_cmp(&str_null), None); assert_ne!(int_null, outer_null); - Ok(()) } } diff --git a/vortex-array/src/scalar/tests/round_trip.rs b/vortex-array/src/scalar/tests/round_trip.rs index d983ce6609c..ae6adde7472 100644 --- a/vortex-array/src/scalar/tests/round_trip.rs +++ b/vortex-array/src/scalar/tests/round_trip.rs @@ -1,57 +1,24 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for internal consistency and round-tripping of scalar types. +//! Focused tests for `From`/`TryFrom` conversions, `null_native`, and large-payload proto roundtrip. //! -//! These tests ensure that conversions between different representations -//! (Scalar, ScalarValue, specialized types, protobuf) maintain consistency -//! and preserve data integrity. +//! General `Scalar`/`ScalarValue` and protobuf roundtrips are covered by `scalar::tests::hegel`. #[cfg(test)] mod tests { - use std::f32; - use std::f64; - use std::sync::Arc; - use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; use crate::dtype::DType; - use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::dtype::i256; use crate::proto::scalar as pb; - use crate::scalar::DecimalValue; use crate::scalar::Scalar; use crate::scalar::tests::SESSION; - // Test that primitive scalars round-trip through ScalarValue - #[test] - fn test_primitive_scalar_to_scalar_value_round_trip() { - let values: Vec = vec![ - Scalar::primitive(42i8, Nullability::NonNullable), - Scalar::primitive(1000i16, Nullability::NonNullable), - Scalar::primitive(100000i32, Nullability::NonNullable), - Scalar::primitive(10000000000i64, Nullability::NonNullable), - Scalar::primitive(200u8, Nullability::NonNullable), - Scalar::primitive(50000u16, Nullability::NonNullable), - Scalar::primitive(4000000000u32, Nullability::NonNullable), - Scalar::primitive(18446744073709551615u64, Nullability::NonNullable), - Scalar::primitive(f32::consts::PI, Nullability::NonNullable), - Scalar::primitive(f64::consts::E, Nullability::NonNullable), - ]; - - for scalar in values { - let value = scalar.value().cloned(); - let dtype = scalar.dtype().clone(); - let reconstructed = Scalar::new(dtype, value); - assert_eq!(scalar.dtype(), reconstructed.dtype()); - assert_eq!(scalar, reconstructed); - } - } - #[test] - fn test_null_scalar_type_preservation() { + fn test_null_native_type_preservation() { let cases = [ ( Scalar::null_native::(), @@ -106,207 +73,44 @@ mod tests { for (scalar, expected_dtype) in cases { assert!(scalar.is_null()); assert_eq!(scalar.dtype(), &expected_dtype); - let reconstructed = Scalar::new(expected_dtype.clone(), scalar.value().cloned()); - assert!(reconstructed.is_null()); - assert_eq!(reconstructed.dtype(), &expected_dtype); - } - } - - // Test that From and TryFrom<&Scalar> for T are consistent - #[test] - fn test_from_try_from_consistency() { - // Test with various primitive types - let value_i32 = 42i32; - let scalar_i32 = Scalar::from(value_i32); - let extracted_i32: i32 = i32::try_from(&scalar_i32).unwrap(); - assert_eq!(value_i32, extracted_i32); - - let value_u64 = 1000000u64; - let scalar_u64 = Scalar::from(value_u64); - let extracted_u64: u64 = u64::try_from(&scalar_u64).unwrap(); - assert_eq!(value_u64, extracted_u64); - - let value_bool = true; - let scalar_bool = Scalar::from(value_bool); - let extracted_bool: bool = bool::try_from(&scalar_bool).unwrap(); - assert_eq!(value_bool, extracted_bool); - - let value_str = "test string"; - let scalar_str = Scalar::from(value_str); - let extracted_str: String = String::try_from(&scalar_str).unwrap(); - assert_eq!(value_str, extracted_str); - } - - // Test Option conversions - #[test] - fn test_option_conversions() { - // Test Some values - let some_value = Some(42i32); - let scalar_some = Scalar::from(some_value); - let extracted_some: Option = Option::try_from(&scalar_some).unwrap(); - assert_eq!(some_value, extracted_some); - - // Test None values - let none_value: Option = None; - let scalar_none = Scalar::from(none_value); - let extracted_none: Option = Option::try_from(&scalar_none).unwrap(); - assert_eq!(none_value, extracted_none); - } - - // Test decimal scalar round-trips - #[test] - fn test_decimal_scalar_round_trip() { - let decimal_dtype = DecimalDType::new(10, 2); - - // Test various decimal value types. - let decimal_values = vec![ - DecimalValue::I8(100), - DecimalValue::I16(10000), - DecimalValue::I32(1000000), - DecimalValue::I64(10000000), - DecimalValue::I128(100000000), - DecimalValue::I256(i256::from_i128(1000000000)), - ]; - - for value in decimal_values { - let scalar = Scalar::decimal(value, decimal_dtype, Nullability::NonNullable); - let decimal_specialized = scalar.as_decimal(); - - match decimal_specialized.decimal_value() { - Some(extracted) => assert_eq!(extracted, value), - None => panic!("Expected decimal value, got None"), - } - - // Test round-trip through ScalarValue - let scalar_value = scalar.value().cloned(); - let dtype = scalar.dtype().clone(); - let reconstructed = Scalar::new(dtype, scalar_value); - assert_eq!(scalar.dtype(), reconstructed.dtype()); - assert_eq!(scalar, reconstructed); } } - // Test protobuf round-trips with edge cases #[test] - fn test_protobuf_edge_cases() { - // Test empty list - let empty_list = Scalar::list( - Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), - vec![], - Nullability::NonNullable, - ); - let pb_empty = pb::Scalar::from(&empty_list); - let round_tripped = Scalar::from_proto(&pb_empty, &SESSION).unwrap(); - assert_eq!(empty_list.dtype(), round_tripped.dtype()); - assert_eq!(empty_list, round_tripped); - - // Test nested lists - let inner_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let outer_dtype = Arc::new(DType::List( - Arc::clone(&inner_dtype), - Nullability::NonNullable, - )); - - let inner_list1 = Scalar::list( - inner_dtype, - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let nested_list = Scalar::list(outer_dtype, vec![inner_list1], Nullability::NonNullable); - - let pb_nested = pb::Scalar::from(&nested_list); - let round_tripped_nested = Scalar::from_proto(&pb_nested, &SESSION).unwrap(); - assert_eq!(nested_list.dtype(), round_tripped_nested.dtype()); - assert_eq!(nested_list, round_tripped_nested); - - // Test large binary data - let large_binary = vec![42u8; 10000]; - let binary_scalar = Scalar::binary(large_binary.clone(), Nullability::NonNullable); - let pb_binary = pb::Scalar::from(&binary_scalar); - let round_tripped_binary = Scalar::from_proto(&pb_binary, &SESSION).unwrap(); - assert_eq!(binary_scalar.dtype(), round_tripped_binary.dtype()); - assert_eq!(binary_scalar, round_tripped_binary); - - // Verify the data is preserved - let extracted: ByteBuffer = ByteBuffer::try_from(&round_tripped_binary).unwrap(); - assert_eq!(extracted.as_slice(), &large_binary); - } - - // Test that fixed-size list scalars round-trip through protobuf. This is - // the path taken by a ConstantArray of a fixed-size list dtype (e.g. a - // UUID column stored as fixed_size_list(u8)[16]), whose scalar metadata - // is serialized as a protobuf ListValue. - #[test] - fn test_protobuf_fixed_size_list_round_trip() { - let fsl = Scalar::fixed_size_list( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - (0u8..16) - .map(|i| Scalar::primitive(i, Nullability::NonNullable)) - .collect(), - Nullability::NonNullable, - ); - - let pb_fsl = pb::Scalar::from(&fsl); - let round_tripped = Scalar::from_proto(&pb_fsl, &SESSION).unwrap(); - assert_eq!(fsl.dtype(), round_tripped.dtype()); - assert_eq!(fsl, round_tripped); - } - - // Test that nullable and non-nullable types are preserved - #[test] - fn test_nullability_preservation() { - let nullable_scalar = Scalar::primitive(42i32, Nullability::Nullable); - let non_nullable_scalar = Scalar::primitive(42i32, Nullability::NonNullable); - - assert_ne!(nullable_scalar.dtype(), non_nullable_scalar.dtype()); - - // Test through protobuf - let pb_nullable = pb::Scalar::from(&nullable_scalar); - let pb_non_nullable = pb::Scalar::from(&non_nullable_scalar); - - let recovered_nullable = Scalar::from_proto(&pb_nullable, &SESSION).unwrap(); - let recovered_non_nullable = Scalar::from_proto(&pb_non_nullable, &SESSION).unwrap(); - - assert_eq!(nullable_scalar.dtype(), recovered_nullable.dtype()); - assert_eq!(non_nullable_scalar.dtype(), recovered_non_nullable.dtype()); - assert_ne!(recovered_nullable.dtype(), recovered_non_nullable.dtype()); + fn test_from_try_from_roundtrip() -> VortexResult<()> { + assert_eq!(i32::try_from(&Scalar::from(42i32))?, 42); + assert_eq!(u64::try_from(&Scalar::from(1_000_000u64))?, 1_000_000); + assert_eq!(usize::try_from(&Scalar::from(12_345usize))?, 12_345); + assert!(bool::try_from(&Scalar::from(true))?); assert_eq!( - recovered_nullable.as_primitive().typed_value::(), - Some(42) + String::try_from(&Scalar::from("test string"))?, + "test string" ); assert_eq!( - recovered_non_nullable.as_primitive().typed_value::(), + Option::::try_from(&Scalar::from(Some(42i32)))?, Some(42) ); + assert_eq!(Option::::try_from(&Scalar::from(None::))?, None); + Ok(()) } - // Test usize conversions (which may be architecture-dependent) #[test] - fn test_usize_conversions() { - let value_usize = 12345usize; - let scalar_usize = Scalar::from(value_usize); - let extracted_usize: usize = usize::try_from(&scalar_usize).unwrap(); - assert_eq!(value_usize, extracted_usize); + fn test_large_binary_protobuf_roundtrip() -> VortexResult<()> { + let large_binary = vec![42u8; 10_000]; + let binary_scalar = Scalar::binary(large_binary.clone(), Nullability::NonNullable); + let pb_binary = pb::Scalar::from(&binary_scalar); + let round_tripped = Scalar::from_proto(&pb_binary, &SESSION)?; + assert_eq!(round_tripped, binary_scalar); + let extracted = ByteBuffer::try_from(&round_tripped)?; + assert_eq!(extracted.as_slice(), &large_binary); + Ok(()) } - // Test error cases for conversions #[test] fn test_conversion_errors() { - // Try to convert a string scalar to an integer let string_scalar = Scalar::utf8("not a number".to_string(), Nullability::NonNullable); - let result: Result = i32::try_from(&string_scalar); - assert!(result.is_err()); - - // Try to convert an integer scalar to a list. - let int_scalar = Scalar::primitive(42i32, Nullability::NonNullable); - assert!(int_scalar.as_list_opt().is_none()); - - // Try to convert a boolean to a decimal. - let bool_scalar = Scalar::bool(true, Nullability::NonNullable); - assert!(bool_scalar.as_decimal_opt().is_none()); + assert!(i32::try_from(&string_scalar).is_err()); + assert!(Scalar::from(42i32).as_list_opt().is_none()); + assert!(Scalar::from(true).as_decimal_opt().is_none()); } } diff --git a/vortex-array/src/scalar/typed_view/decimal/tests.rs b/vortex-array/src/scalar/typed_view/decimal/tests.rs index 2600256688e..fee77d69bf2 100644 --- a/vortex-array/src/scalar/typed_view/decimal/tests.rs +++ b/vortex-array/src/scalar/typed_view/decimal/tests.rs @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for decimal scalar casting functionality. +//! Focused tests for decimal scalar casting, checked arithmetic, conversions, and precision bounds. +//! +//! Cross-width `DecimalValue` `Eq`/`PartialOrd`/`Hash` coherence and general decimal casting are +//! covered by `scalar::tests::hegel`. use rstest::rstest; use vortex_error::VortexResult; use vortex_error::vortex_err; -use vortex_utils::aliases::hash_set::HashSet; use crate::dtype::DType; use crate::dtype::DecimalDType; @@ -16,6 +18,7 @@ use crate::dtype::MAX_SCALE; use crate::dtype::NativeDecimalType; use crate::dtype::Nullability; use crate::dtype::PType; +use crate::dtype::half::f16; use crate::dtype::i256; use crate::scalar::DecimalValue; use crate::scalar::NumericOperator; @@ -23,806 +26,263 @@ use crate::scalar::Scalar; use crate::scalar::decimal_numeric_result_dtype; #[rstest] -#[case(DecimalValue::I8(100), DecimalValue::I8(100))] -#[case(DecimalValue::I16(0), DecimalValue::I256(i256::ZERO))] -#[case(DecimalValue::I8(100), DecimalValue::I128(100))] -fn test_decimal_value_eq(#[case] left: DecimalValue, #[case] right: DecimalValue) { - assert_eq!(left, right); -} - -#[rstest] -#[case(DecimalValue::I128(10), DecimalValue::I8(11))] -#[case(DecimalValue::I256(i256::ZERO), DecimalValue::I16(10))] -#[case(DecimalValue::I128(-1_000), DecimalValue::I8(1))] -fn test_decimal_value_cmp(#[case] lower: DecimalValue, #[case] upper: DecimalValue) { - assert!(lower < upper, "expected {lower} < {upper}"); -} - -#[test] -fn test_hash() { - let mut set = HashSet::new(); - set.insert(DecimalValue::I8(100)); - set.insert(DecimalValue::I16(100)); - set.insert(DecimalValue::I32(100)); - set.insert(DecimalValue::I64(100)); - set.insert(DecimalValue::I128(100)); - set.insert(DecimalValue::I256(i256::from_i128(100))); - assert_eq!(set.len(), 1); -} - -#[test] -fn test_decimal_cast_to_primitive() { - // Create a decimal with value 123.45 (scale=2, so stored as 12345) - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(12345), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to f64 should give us 123.45 - let float_result = &decimal_scalar - .cast(&DType::Primitive(PType::F64, Nullability::NonNullable)) - .unwrap(); - let float_value: f64 = float_result.try_into().unwrap(); - assert_eq!(float_value, 123.45); - assert_eq!( - float_result.as_primitive().typed_value::(), - Some(123.45) - ); - - // Cast to i32 should give us 123 (truncated) - let int_result = &decimal_scalar - .cast(&DType::Primitive(PType::I32, Nullability::NonNullable)) - .unwrap(); - let int_value: i32 = int_result.try_into().unwrap(); - assert_eq!(int_value, 123); -} - -#[test] -fn test_decimal_cast_null_handling() { - // Null decimal - let null_decimal = Scalar::null(DType::Decimal( - DecimalDType::new(10, 2), - Nullability::Nullable, - )); - - // Cast null decimal to primitive should preserve null - let result = null_decimal - .cast(&DType::Primitive(PType::I32, Nullability::Nullable)) - .unwrap(); - assert!(result.is_null()); - assert_eq!( - result.dtype(), - &DType::Primitive(PType::I32, Nullability::Nullable) - ); - - // Cast null decimal to another decimal type should preserve null - let result = null_decimal - .cast(&DType::Decimal( - DecimalDType::new(20, 4), - Nullability::Nullable, - )) - .unwrap(); - assert!(result.is_null()); -} - -#[test] -fn test_decimal_cast_overflow() { - // Large decimal value that won't fit in i8 - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(100000), - DecimalDType::new(10, 0), - Nullability::NonNullable, - ); - - // Cast to i8 should fail due to overflow - let result = decimal_scalar.cast(&DType::Primitive(PType::I8, Nullability::NonNullable)); - assert!(result.is_err()); -} - -#[test] -fn test_decimal_cast_between_decimal_types() { - // Decimal with different precision/scale - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(12345), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to different decimal type. - let result = decimal_scalar - .cast(&DType::Decimal( - DecimalDType::new(20, 4), - Nullability::NonNullable, - )) - .unwrap(); - - // 123.45 with scale 2 is represented as 123.4500 with scale 4. - let decimal_value: Option = result.try_into().unwrap(); - assert_eq!(decimal_value, Some(DecimalValue::I128(1234500))); -} - -#[test] -fn test_decimal_cast_negative_values() { - // Negative decimal value - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(-5678), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to f64 should give us -56.78 - let float_result = &decimal_scalar - .cast(&DType::Primitive(PType::F64, Nullability::NonNullable)) - .unwrap(); - let float_value: f64 = float_result.try_into().unwrap(); - assert!((float_value - (-56.78)).abs() < 0.001); - - // Cast to unsigned should fail - let result = decimal_scalar.cast(&DType::Primitive(PType::U32, Nullability::NonNullable)); - assert!(result.is_err()); -} - -#[rstest] -#[case(DecimalValue::I8(i8::MAX), DecimalDType::new(3, 0), 127.0)] -#[case(DecimalValue::I8(i8::MIN), DecimalDType::new(3, 0), -128.0)] -#[case(DecimalValue::I16(i16::MAX), DecimalDType::new(5, 0), 32767.0)] -#[case(DecimalValue::I16(i16::MIN), DecimalDType::new(5, 0), -32768.0)] -#[case(DecimalValue::I32(i32::MAX), DecimalDType::new(10, 0), 2147483647.0)] -#[case(DecimalValue::I32(i32::MIN), DecimalDType::new(10, 0), -2147483648.0)] -fn test_decimal_cast_edge_values( +#[case::u16_max( + DecimalValue::I32(6_553_500), + DecimalDType::new(10, 2), + PType::U16, + true +)] +#[case::u16_overflow( + DecimalValue::I32(6_553_600), + DecimalDType::new(10, 2), + PType::U16, + false +)] +#[case::u8_overflow(DecimalValue::I32(25_600), DecimalDType::new(10, 2), PType::U8, false)] +#[case::i8_overflow(DecimalValue::I32(100_000), DecimalDType::new(10, 0), PType::I8, false)] +#[case::i16_max( + DecimalValue::I32(3_276_700), + DecimalDType::new(10, 2), + PType::I16, + true +)] +#[case::i16_min(DecimalValue::I32(-3_276_800), DecimalDType::new(10, 2), PType::I16, true)] +#[case::i16_overflow( + DecimalValue::I32(3_276_800), + DecimalDType::new(10, 2), + PType::I16, + false +)] +#[case::neg_to_unsigned(DecimalValue::I32(-5_000), DecimalDType::new(10, 2), PType::U32, false)] +#[case::u64_max( + DecimalValue::I128(i128::from(u64::MAX)), + DecimalDType::new(21, 0), + PType::U64, + true +)] +#[case::u64_overflow( + DecimalValue::I128(i128::MAX), + DecimalDType::new(39, 0), + PType::U64, + false +)] +#[case::i256_overflow( + DecimalValue::I256(i256::from_i128(i128::MAX) + i256::ONE), + DecimalDType::new(40, 0), + PType::I64, + false +)] +fn test_decimal_to_int_boundaries( #[case] value: DecimalValue, #[case] dtype: DecimalDType, - #[case] expected: f64, + #[case] target: PType, + #[case] should_succeed: bool, ) { - let decimal_scalar = Scalar::decimal(value, dtype, Nullability::NonNullable); - - // Cast to f64 should always work for these ranges - let result = decimal_scalar.cast(&DType::Primitive(PType::F64, Nullability::NonNullable)); - let result = result.unwrap(); - assert_eq!( - result.dtype(), - &DType::Primitive(PType::F64, Nullability::NonNullable) - ); - assert_eq!(result.as_primitive().typed_value::(), Some(expected)); -} - -#[rstest] -#[case(1234, 0, 1234.0)] // No scale -#[case(1234, 1, 123.4)] // Scale 1 -#[case(1234, 2, 12.34)] // Scale 2 -#[case(1234, 3, 1.234)] // Scale 3 -#[case(1234, 4, 0.1234)] // Scale 4 -fn test_decimal_cast_with_scale(#[case] value: i32, #[case] scale: i8, #[case] expected: f64) { - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(value), - DecimalDType::new(10, scale), - Nullability::NonNullable, - ); - - let float_result = &decimal_scalar - .cast(&DType::Primitive(PType::F64, Nullability::NonNullable)) - .unwrap(); - let float_value: f64 = float_result.try_into().unwrap(); - assert!( - (float_value - expected).abs() < 0.0001, - "Expected {expected} but got {float_value} for value={value} scale={scale}" - ); -} - -#[test] -fn test_decimal_cast_unsupported_types() { - let decimal_scalar = Scalar::decimal( - DecimalValue::I32(1234), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to unsupported types should fail - let result = decimal_scalar.cast(&DType::Bool(Nullability::NonNullable)); - assert!(result.is_err()); - - let result = decimal_scalar.cast(&DType::Utf8(Nullability::NonNullable)); - assert!(result.is_err()); - - let result = decimal_scalar.cast(&DType::Binary(Nullability::NonNullable)); - assert!(result.is_err()); + let scalar = Scalar::decimal(value, dtype, Nullability::NonNullable); + let res = scalar.cast(&DType::Primitive(target, Nullability::NonNullable)); + assert_eq!(res.is_ok(), should_succeed, "casting {value} to {target}"); } #[test] -fn test_decimal_to_primitive_i32() { - // Create a decimal with value 42.50 (scale=2, so internal value is 4250) - let decimal = Scalar::decimal( - DecimalValue::I32(4250), +fn test_decimal_cast_exact_and_lossy_and_unsupported() -> VortexResult<()> { + // Decimal truncation to int & scale-up / scale-down. + let d = Scalar::decimal( + DecimalValue::I32(12_345), DecimalDType::new(10, 2), Nullability::NonNullable, ); - - // Cast to i32 - should truncate to 42 - let result = decimal.cast(&DType::Primitive(PType::I32, Nullability::NonNullable)); - assert!(result.is_ok()); - let i32_scalar = result.unwrap(); - assert_eq!(i32_scalar.as_primitive().typed_value::().unwrap(), 42); -} - -#[test] -fn test_decimal_to_primitive_f32() { - // Create a decimal with value 99.99 (scale=2, so internal value is 9999) - let decimal = Scalar::decimal( - DecimalValue::I16(9999), - DecimalDType::new(4, 2), - Nullability::NonNullable, - ); - - // Cast to f32 - let result = decimal.cast(&DType::Primitive(PType::F32, Nullability::NonNullable)); - assert!(result.is_ok()); - let f32_scalar = result.unwrap(); - assert!((f32_scalar.as_primitive().typed_value::().unwrap() - 99.99).abs() < 0.01); -} - -#[test] -fn test_decimal_to_primitive_u8_overflow() { - // Create a decimal with value 256.00 (scale=2, so internal value is 25600) - let decimal = Scalar::decimal( - DecimalValue::I32(25600), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to u8 - should fail due to overflow - let result = decimal.cast(&DType::Primitive(PType::U8, Nullability::NonNullable)); - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("out of range for u8") - ); -} - -#[test] -fn test_decimal_to_decimal_same_type() { - // Create a decimal with specific precision and scale - let decimal = Scalar::decimal( - DecimalValue::I64(123456), - DecimalDType::new(10, 3), - Nullability::NonNullable, - ); - - // Cast to same decimal type but nullable - let target_dtype = DType::Decimal(DecimalDType::new(10, 3), Nullability::Nullable); - let result = decimal.cast(&target_dtype); - assert!(result.is_ok()); - - let casted = result.unwrap(); - assert_eq!(casted.dtype(), &target_dtype); assert_eq!( - casted.as_decimal().decimal_value(), - Some(DecimalValue::I64(123456)) + i32::try_from(&d.cast(&DType::Primitive(PType::I32, Nullability::NonNullable))?)?, + 123 ); -} - -#[test] -fn test_decimal_to_decimal_different_scale() { - // Create a decimal with scale=2 - let decimal = Scalar::decimal( - DecimalValue::I32(10000), // Represents 100.00 - DecimalDType::new(10, 2), + let widened = d.cast(&DType::Decimal( + DecimalDType::new(20, 4), Nullability::NonNullable, - ); - - // Cast to decimal with scale=4 - let target_dtype = DType::Decimal(DecimalDType::new(10, 4), Nullability::NonNullable); - let result = decimal.cast(&target_dtype); - assert!(result.is_ok()); - - let casted = result.unwrap(); + ))?; assert_eq!( - casted.as_decimal().decimal_value(), - Some(DecimalValue::I64(1000000)) + widened.as_decimal().decimal_value(), + Some(DecimalValue::I128(1_234_500)) ); -} - -#[test] -fn test_decimal_to_decimal_lower_scale_exact() { - let decimal = Scalar::decimal( - DecimalValue::I64(1234500), // 123.4500 - DecimalDType::new(10, 4), + let narrowed = widened.cast(&DType::Decimal( + DecimalDType::new(10, 2), Nullability::NonNullable, - ); - - let casted = decimal - .cast(&DType::Decimal( - DecimalDType::new(10, 2), - Nullability::NonNullable, - )) - .unwrap(); - + ))?; assert_eq!( - casted.as_decimal().decimal_value(), - Some(DecimalValue::I64(12345)) + narrowed.as_decimal().decimal_value(), + Some(DecimalValue::I64(12_345)) ); -} -#[test] -fn test_decimal_to_decimal_lower_scale_lossy_fails() { - let decimal = Scalar::decimal( - DecimalValue::I64(1234567), // 123.4567 + // Lossy scale reduction fails. + let lossy = Scalar::decimal( + DecimalValue::I64(1_234_567), DecimalDType::new(10, 4), Nullability::NonNullable, - ); - - let result = decimal.cast(&DType::Decimal( + ) + .cast(&DType::Decimal( DecimalDType::new(10, 2), Nullability::NonNullable, - )); - - assert!(result.is_err()); + )) + .unwrap_err(); assert!( - result - .unwrap_err() - .to_string() - .contains("would lose precision") + lossy.to_string().contains("would lose precision"), + "{lossy}" ); -} -#[test] -fn test_primitive_i64_to_decimal_rescales() { - let scalar = Scalar::primitive(42i64, Nullability::NonNullable); - - let casted = scalar + // Primitive -> Decimal rescaling and precision overflow. + let from_i64 = Scalar::from(42i64).cast(&DType::Decimal( + DecimalDType::new(21, 2), + Nullability::NonNullable, + ))?; + assert_eq!( + from_i64.as_decimal().decimal_value(), + Some(DecimalValue::I128(4_200)) + ); + let prec_err = Scalar::from(1000i32) .cast(&DType::Decimal( - DecimalDType::new(21, 2), + DecimalDType::new(2, 0), Nullability::NonNullable, )) - .unwrap(); - - assert_eq!( - casted.as_decimal().decimal_value(), - Some(DecimalValue::I128(4200)) - ); -} - -#[test] -fn test_primitive_to_decimal_precision_checked() { - let scalar = Scalar::primitive(1000i32, Nullability::NonNullable); - - let result = scalar.cast(&DType::Decimal( - DecimalDType::new(2, 0), - Nullability::NonNullable, - )); - - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("does not fit in precision") - ); -} - -#[test] -fn test_decimal_i256_to_primitive() { - // Create a decimal with i256 value - use crate::dtype::i256; - let large_value = i256::from_i128(1234567890); - let decimal = Scalar::decimal( - DecimalValue::I256(large_value), - DecimalDType::new(20, 6), // scale=6 - Nullability::NonNullable, - ); - - // Cast to f64 - value is 1234.567890 - let result = decimal.cast(&DType::Primitive(PType::F64, Nullability::NonNullable)); - assert!(result.is_ok()); - let f64_scalar = result.unwrap(); - assert!( - (f64_scalar.as_primitive().typed_value::().unwrap() - 1234.567890).abs() < 0.000001 - ); -} - -#[test] -fn test_decimal_negative_value_cast() { - // Create a negative decimal value - let decimal = Scalar::decimal( - DecimalValue::I32(-5000), // Represents -50.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to i32 - let result = decimal.cast(&DType::Primitive(PType::I32, Nullability::NonNullable)); - assert!(result.is_ok()); - let i32_scalar = result.unwrap(); - assert_eq!(i32_scalar.as_primitive().typed_value::().unwrap(), -50); - - // Cast to u32 - should fail due to negative value - let result = decimal.cast(&DType::Primitive(PType::U32, Nullability::NonNullable)); - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("out of range for u32") - ); -} - -#[test] -fn test_decimal_cast_preserves_nullability() { - // Non-nullable decimal - let decimal = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Cast to nullable i32 - let result = decimal.cast(&DType::Primitive(PType::I32, Nullability::Nullable)); - assert!(result.is_ok()); - let nullable_scalar = result.unwrap(); - assert_eq!(nullable_scalar.dtype().nullability(), Nullability::Nullable); - assert_eq!(nullable_scalar.as_primitive().typed_value::(), Some(1)); -} - -#[test] -fn test_decimal_to_unsupported_type() { - let decimal = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Try to cast to string - should fail - let result = decimal.cast(&DType::Utf8(Nullability::NonNullable)); - assert!(result.is_err()); + .unwrap_err(); assert!( - result - .unwrap_err() - .to_string() - .contains("Cannot cast decimal to") + prec_err.to_string().contains("does not fit in precision"), + "{prec_err}" ); -} -#[rstest] -#[case(PType::U8, 5u64)] -#[case(PType::U16, 5)] -#[case(PType::U32, 5)] -#[case(PType::U64, 5)] -#[case(PType::I8, 5)] -#[case(PType::I16, 5)] -#[case(PType::I32, 5)] -#[case(PType::I64, 5)] -fn test_decimal_i8_all_primitive_casts(#[case] ptype: PType, #[case] expected: u64) { - // Test casting from smallest decimal type to all primitive types - let decimal = Scalar::decimal( - DecimalValue::I8(50), // Represents 5.0 with scale=1 - DecimalDType::new(3, 1), - Nullability::NonNullable, - ); - - let result = decimal.cast(&DType::Primitive(ptype, Nullability::NonNullable)); - assert!(result.is_ok(), "Failed to cast to {ptype:?}"); - let scalar = result.unwrap(); - - // Check the value matches expected - match ptype { - PType::U8 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::U16 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::U32 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::U64 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap(), - expected - ), - PType::I8 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::I16 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::I32 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::I64 => assert_eq!( - scalar.as_primitive().typed_value::().unwrap() as u64, - expected - ), - PType::F16 | PType::F32 | PType::F64 => panic!("Unexpected type {ptype}"), - } -} - -#[test] -fn test_decimal_cast_f16() { - use crate::dtype::half::f16; - - // Create a decimal with value 12.5 (scale=1, so stored as 125) - let decimal = Scalar::decimal( + // Decimal -> f16. + let f16_cast = Scalar::decimal( DecimalValue::I16(125), DecimalDType::new(4, 1), Nullability::NonNullable, - ); - - // Cast to f16 - let result = decimal.cast(&DType::Primitive(PType::F16, Nullability::NonNullable)); - assert!(result.is_ok()); - let f16_scalar = result.unwrap(); - let f16_value: f16 = f16_scalar.as_primitive().typed_value::().unwrap(); - assert!((f16_value.to_f64() - 12.5).abs() < 0.01); -} - -#[test] -fn test_decimal_cast_boundary_values() { - // Test with U16 boundary - let decimal = Scalar::decimal( - DecimalValue::I32(6_553_500), // 65535.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - - // Should succeed for U16 - let result = decimal.cast(&DType::Primitive(PType::U16, Nullability::NonNullable)); - assert!(result.is_ok()); + ) + .cast(&DType::Primitive(PType::F16, Nullability::NonNullable))?; assert_eq!( - result.unwrap().as_primitive().typed_value::().unwrap(), - 65535 + f16_cast.as_primitive().typed_value::(), + Some(f16::from_f32(12.5)) ); - // Should fail for U16 with value 65536 - let decimal = Scalar::decimal( - DecimalValue::I32(6_553_600), // 65536.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let result = decimal.cast(&DType::Primitive(PType::U16, Nullability::NonNullable)); - assert!(result.is_err()); - - // Test with I16 boundaries - let decimal = Scalar::decimal( - DecimalValue::I32(3_276_700), // 32767.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let result = decimal.cast(&DType::Primitive(PType::I16, Nullability::NonNullable)); - assert!(result.is_ok()); - assert_eq!( - result.unwrap().as_primitive().typed_value::().unwrap(), - 32767 - ); - - let decimal = Scalar::decimal( - DecimalValue::I32(-3_276_800), // -32768.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let result = decimal.cast(&DType::Primitive(PType::I16, Nullability::NonNullable)); - assert!(result.is_ok()); - assert_eq!( - result.unwrap().as_primitive().typed_value::().unwrap(), - -32768 - ); - - // Should fail for I16 with value 32768 - let decimal = Scalar::decimal( - DecimalValue::I32(3_276_800), // 32768.00 with scale=2 - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let result = decimal.cast(&DType::Primitive(PType::I16, Nullability::NonNullable)); - assert!(result.is_err()); -} - -#[test] -fn test_decimal_partial_ord() { - let decimal1 = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let scalar1 = decimal1.as_decimal(); - - let decimal2 = Scalar::decimal( - DecimalValue::I32(200), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let scalar2 = decimal2.as_decimal(); - - // Same type comparison should work - assert!(scalar1 < scalar2); - assert!(scalar2 > scalar1); - assert_eq!( - scalar1.partial_cmp(&scalar1), - Some(std::cmp::Ordering::Equal) - ); - - // Different type comparison should return None - let decimal3 = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(20, 4), // Different precision/scale - Nullability::NonNullable, - ); - let scalar3 = decimal3.as_decimal(); - assert_eq!(scalar1.partial_cmp(&scalar3), None); -} - -#[test] -fn test_decimal_eq() { - let decimal1 = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let scalar1 = decimal1.as_decimal(); - - let decimal2 = Scalar::decimal( - DecimalValue::I32(100), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let scalar2 = decimal2.as_decimal(); - - assert_eq!(scalar1, scalar2); - - // Different values - let decimal3 = Scalar::decimal( - DecimalValue::I32(200), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let scalar3 = decimal3.as_decimal(); - assert_ne!(scalar1, scalar3); -} - -#[test] -fn test_decimal_value_from_unsigned() { - // Test From implementations for unsigned types - let v1: DecimalValue = 255u8.into(); - assert_eq!(v1, DecimalValue::I16(255)); - - let v2: DecimalValue = 65535u16.into(); - assert_eq!(v2, DecimalValue::I32(65535)); - - let v3: DecimalValue = 4294967295u32.into(); - assert_eq!(v3, DecimalValue::I64(4294967295)); - - let v4: DecimalValue = 18446744073709551615u64.into(); - assert_eq!(v4, DecimalValue::I128(18446744073709551615)); - assert_eq!(v1.decimal_type(), DecimalType::I16); - assert_eq!(v2.decimal_type(), DecimalType::I32); - assert_eq!(v3.decimal_type(), DecimalType::I64); - assert_eq!(v4.decimal_type(), DecimalType::I128); + // Unsupported target types fail. + for target in [ + DType::Bool(Nullability::NonNullable), + DType::Utf8(Nullability::NonNullable), + DType::Binary(Nullability::NonNullable), + ] { + assert!(d.cast(&target).is_err()); + } + Ok(()) } -#[test] -fn test_decimal_scalar_try_from_errors() { - // Test error cases for TryFrom for primitive types - let decimal = Scalar::decimal( - DecimalValue::I16(1234), - DecimalDType::new(5, 2), +#[rstest] +#[case::negative_scale(5, -5, 1, 100_000.0)] +#[case::extreme_negative_scale(1, -30, 1, 1e30)] +#[case::scale_past_i128(MAX_PRECISION, 39, 1, 1e-39)] +#[case::max_scale(MAX_PRECISION, MAX_SCALE, 1, 1e-76)] +#[case::negative_value_negative_scale(5, -5, -1, -100_000.0)] +#[case::common_scale(10, 2, 12_345, 123.45)] +#[case::zero_scale(10, 0, -7, -7.0)] +#[case::six_scale(20, 6, 1_500_000, 1.5)] +fn cast_decimal_to_f64_spans_the_scale_domain( + #[case] precision: u8, + #[case] scale: i8, + #[case] stored: i64, + #[case] expected: f64, +) -> VortexResult<()> { + let scalar = Scalar::decimal( + DecimalValue::I64(stored), + DecimalDType::new(precision, scale), Nullability::NonNullable, ); - let scalar = decimal.as_decimal(); - - // Try to extract as wrong type - let result: Result = scalar.try_into(); - assert!(result.is_err()); - - // Try to extract from null - let null_decimal = Scalar::null(DType::Decimal( - DecimalDType::new(10, 2), - Nullability::Nullable, - )); - let null_scalar = null_decimal.as_decimal(); - let result: Result = null_scalar.try_into(); - assert!(result.is_err()); - - // Extract as Option from null should succeed - let result: Result, _> = null_scalar.try_into(); - assert!(result.is_ok()); - assert_eq!(result.unwrap(), None); + let value: f64 = + (&scalar.cast(&DType::Primitive(PType::F64, Nullability::NonNullable))?).try_into()?; + assert!( + (value - expected).abs() <= expected.abs() * 1e-15, + "decimal({precision},{scale}) storing {stored} cast to {value}, expected {expected}" + ); + Ok(()) } #[test] -fn test_decimal_cast_large_scale() { - // Test with very large scale factors - let decimal = Scalar::decimal( - DecimalValue::I64(123456789012345), // 1234.56789012345 with scale=11 - DecimalDType::new(20, 11), +fn cast_decimal_to_narrow_float_and_wide_i256_to_f64() -> VortexResult<()> { + let neg_scale = Scalar::decimal( + DecimalValue::I64(1), + DecimalDType::new(5, -5), Nullability::NonNullable, ); + let f32_value: f32 = + (&neg_scale.cast(&DType::Primitive(PType::F32, Nullability::NonNullable))?).try_into()?; + assert_eq!(f32_value, 100_000.0); - // Cast to f64 - let result = decimal.cast(&DType::Primitive(PType::F64, Nullability::NonNullable)); - assert!(result.is_ok()); - let f64_value: f64 = (&result.unwrap()).try_into().unwrap(); - assert!((f64_value - 1234.56789012345).abs() < 0.0000000001); -} - -#[test] -fn test_decimal_cast_zero_scale() { - // Test with zero scale (integer values) - let decimal = Scalar::decimal( - DecimalValue::I32(123456), - DecimalDType::new(10, 0), + let beyond_i128 = i256::from_i128(i128::MAX) + i256::ONE; + let wide = Scalar::decimal( + DecimalValue::I256(beyond_i128), + DecimalDType::new(MAX_PRECISION, 2), Nullability::NonNullable, ); - - // Cast to i32 should give exact value - let result = decimal.cast(&DType::Primitive(PType::I32, Nullability::NonNullable)); - assert!(result.is_ok()); - let i32_value: i32 = (&result.unwrap()).try_into().unwrap(); - assert_eq!(i32_value, 123456); -} - -#[test] -fn test_native_decimal_type_values_type() { - // Test DECIMAL_TYPE constant for each type - assert_eq!(i8::DECIMAL_TYPE, DecimalType::I8); - assert_eq!(i16::DECIMAL_TYPE, DecimalType::I16); - assert_eq!(i32::DECIMAL_TYPE, DecimalType::I32); - assert_eq!(i64::DECIMAL_TYPE, DecimalType::I64); - assert_eq!(i128::DECIMAL_TYPE, DecimalType::I128); - assert_eq!(i256::DECIMAL_TYPE, DecimalType::I256); + let value: f64 = + (&wide.cast(&DType::Primitive(PType::F64, Nullability::NonNullable))?).try_into()?; + assert_eq!(value, 2f64.powi(127) / 100.0); + Ok(()) } #[test] -fn test_decimal_cast_u64_boundary() { - // Test U64 boundary case - let decimal = Scalar::decimal( - DecimalValue::I128(18446744073709551615_i128), // U64::MAX - DecimalDType::new(21, 0), - Nullability::NonNullable, +fn test_decimal_conversions_and_partial_ord_mismatch() -> VortexResult<()> { + // Unsigned From -> wider signed DecimalValue. + assert_eq!(DecimalValue::from(255u8).decimal_type(), DecimalType::I16); + assert_eq!( + DecimalValue::from(65535u16).decimal_type(), + DecimalType::I32 + ); + assert_eq!( + DecimalValue::from(u32::MAX).decimal_type(), + DecimalType::I64 ); - - let result = decimal.cast(&DType::Primitive(PType::U64, Nullability::NonNullable)); - assert!(result.is_ok()); assert_eq!( - result.unwrap().as_primitive().typed_value::().unwrap(), - u64::MAX + DecimalValue::from(u64::MAX).decimal_type(), + DecimalType::I128 ); - // Test overflow - This value exceeds U64::MAX when cast - // Note: The cast logic checks the float value against U64::MAX - let decimal = Scalar::decimal( - DecimalValue::I128(i128::MAX), // Much larger than U64::MAX - DecimalDType::new(39, 0), + // Scalar::from(DecimalValue) / TryFrom roundtrip across widths. + for value in [ + DecimalValue::I8(127), + DecimalValue::I16(32_767), + DecimalValue::I32(1_000_000), + DecimalValue::I64(1_000_000_000_000), + DecimalValue::I128(123_456_789_012_345_678_901_234_567_890), + DecimalValue::I256(i256::from_i128(987_654_321)), + ] { + let scalar = Scalar::from(value); + assert_eq!(DecimalValue::try_from(&scalar)?, value); + assert_eq!(Option::::try_from(&scalar)?, Some(value)); + assert_eq!(DecimalValue::try_from(scalar)?, value); + } + + // Wrong target type & null extraction errors. + let d1 = Scalar::decimal( + DecimalValue::I16(1234), + DecimalDType::new(5, 2), Nullability::NonNullable, ); + assert!(i8::try_from(d1.as_decimal()).is_err()); - let result = decimal.cast(&DType::Primitive(PType::U64, Nullability::NonNullable)); - assert!(result.is_err()); -} + let null_d = Scalar::null(DType::Decimal( + DecimalDType::new(10, 2), + Nullability::Nullable, + )); + assert!(i32::try_from(null_d.as_decimal()).is_err()); + assert_eq!(Option::::try_from(null_d.as_decimal())?, None); + assert_eq!(Option::::try_from(&null_d)?, None); -#[test] -fn test_decimal_i256_overflow_cast() { - // Test that decimal values too large for i128 are properly handled - let large_value = i256::from_i128(i128::MAX) + i256::from_i128(1); - let decimal = Scalar::decimal( - DecimalValue::I256(large_value), - DecimalDType::new(40, 0), + // Different precision/scale are incomparable via PartialOrd. + let d2 = Scalar::decimal( + DecimalValue::I32(1234), + DecimalDType::new(20, 4), Nullability::NonNullable, ); - - // This should fail when trying to convert to primitive types - let result = decimal.cast(&DType::Primitive(PType::I64, Nullability::NonNullable)); - assert!(result.is_err()); + assert_eq!(d1.as_decimal().partial_cmp(&d2.as_decimal()), None); + Ok(()) } -// Tests for checked_binary_numeric +// Tests for checked_binary_numeric and DecimalValue arithmetic -/// Applies `op` to two non-null operands of `dtype`, returning the result value and its dtype. fn checked_op( lhs: DecimalValue, rhs: DecimalValue, @@ -884,9 +344,7 @@ fn checked_op( Some(DecimalDType::new(MAX_PRECISION, 4)) )] #[case::mul_scale_exceeds_max(NumericOperator::Mul, DecimalDType::new(MAX_PRECISION, 39), None)] -// -70 + -70 is -140, which is not representable as an i8 scale. #[case::mul_scale_underflows(NumericOperator::Mul, DecimalDType::new(10, -70), None)] -// -64 + -64 is exactly i8::MIN, the most negative scale that is still representable. #[case::mul_scale_reaches_min( NumericOperator::Mul, DecimalDType::new(10, -64), @@ -904,11 +362,8 @@ fn test_decimal_numeric_result_dtype( #[rstest] #[case::add(DecimalDType::new(10, 2), 100, 200, NumericOperator::Add, Some(300))] #[case::sub(DecimalDType::new(10, 2), 500, 200, NumericOperator::Sub, Some(300))] -// 0.50 * 0.10 = 0.0500, exact at the doubled result scale. #[case::mul(DecimalDType::new(10, 2), 50, 10, NumericOperator::Mul, Some(500))] -// 0.15 * 0.17 = 0.0255, which a result pinned to scale 2 would have had to round away. #[case::mul_keeps_every_digit(DecimalDType::new(10, 2), 15, 17, NumericOperator::Mul, Some(255))] -// 10.00 / 0.10 = 100.000000 #[case::div( DecimalDType::new(10, 2), 1_000, @@ -916,7 +371,6 @@ fn test_decimal_numeric_result_dtype( NumericOperator::Div, Some(100_000_000) )] -// 10.00 / 3.00 = 3.333333, truncated toward zero at the result scale. #[case::div_truncates( DecimalDType::new(10, 2), 1_000, @@ -924,7 +378,7 @@ fn test_decimal_numeric_result_dtype( NumericOperator::Div, Some(3_333_333) )] -#[case::div_truncates_toward_zero( +#[case::div_truncates_neg( DecimalDType::new(10, 2), -1_000, 300, @@ -932,11 +386,8 @@ fn test_decimal_numeric_result_dtype( Some(-3_333_333) )] #[case::div_by_zero(DecimalDType::new(10, 2), 1_000, 0, NumericOperator::Div, None)] -// 500 * 300 = 150000, stored at scale -4. #[case::mul_negative_scale(DecimalDType::new(10, -2), 5, 3, NumericOperator::Mul, Some(15))] -// 60000 / 300 = 200.00 #[case::div_negative_scale(DecimalDType::new(10, -2), 600, 3, NumericOperator::Div, Some(20_000))] -// 5e12 / 2e8 = 25000, truncated to the result scale of -4. #[case::div_negative_result_scale( DecimalDType::new(10, -8), 50_000, @@ -960,289 +411,156 @@ fn test_decimal_scalar_checked_binary_numeric( } #[test] -fn test_decimal_scalar_mul_widens_beyond_operand_storage() -> VortexResult<()> { - // 1e17 * 1e17 needs 35 digits, so widening only to the operands' i64 storage would report a - // spurious overflow. - let dtype = DecimalDType::new(18, 0); +fn test_decimal_scalar_checked_binary_numeric_edge_cases() -> VortexResult<()> { + // Mul widens beyond operand storage (1e17 * 1e17 -> i128). let operand = DecimalValue::I64(100_000_000_000_000_000); - - let (value, result_dtype) = checked_op(operand, operand, dtype, NumericOperator::Mul)? - .ok_or_else(|| vortex_err!("expected an in-precision product"))?; - assert_eq!(result_dtype, DecimalDType::new(37, 0)); + let (prod, prod_dtype) = checked_op( + operand, + operand, + DecimalDType::new(18, 0), + NumericOperator::Mul, + )? + .ok_or_else(|| vortex_err!("expected in-precision product"))?; + assert_eq!(prod_dtype, DecimalDType::new(37, 0)); + assert_eq!(prod.decimal_type(), DecimalType::I128); assert_eq!( - value, + prod, DecimalValue::I128(10_000_000_000_000_000_000_000_000_000_000_000) ); - assert_eq!(value.decimal_type(), DecimalType::I128); - Ok(()) -} - -#[test] -fn test_decimal_scalar_add_reserves_carry_digit() -> VortexResult<()> { - // 999 + 2 = 1001 exceeds precision 3, but the result reserves a carry digit for it. - let dtype = DecimalDType::new(3, 0); - let (value, result_dtype) = checked_op( + // Add reserves a carry digit (999 + 2 = 1001 in precision 4). + let (sum, sum_dtype) = checked_op( DecimalValue::I16(999), DecimalValue::I16(2), - dtype, + DecimalDType::new(3, 0), NumericOperator::Add, )? - .ok_or_else(|| vortex_err!("expected the carry digit to absorb the result"))?; - assert_eq!(result_dtype, DecimalDType::new(4, 0)); - assert_eq!(value, DecimalValue::I16(1_001)); - assert_eq!(value.decimal_type(), DecimalType::I16); - Ok(()) -} + .ok_or_else(|| vortex_err!("expected carry digit"))?; + assert_eq!(sum_dtype, DecimalDType::new(4, 0)); + assert_eq!(sum, DecimalValue::I16(1_001)); -#[rstest] -#[case::add(NumericOperator::Add)] -#[case::mul(NumericOperator::Mul)] -fn test_decimal_scalar_overflows_saturated_precision( - #[case] op: NumericOperator, -) -> VortexResult<()> { - // At MAX_PRECISION the result precision cannot widen any further, so an out-of-range result - // is a genuine overflow. - let dtype = DecimalDType::new(MAX_PRECISION, 0); - let max = DecimalValue::I256( + // Saturated precision overflow for Add and Mul. + let max_dtype = DecimalDType::new(MAX_PRECISION, 0); + let max_val = DecimalValue::I256( ::MAX_BY_PRECISION[usize::from(MAX_PRECISION)], ); + assert_eq!( + checked_op(max_val, max_val, max_dtype, NumericOperator::Add)?, + None + ); + assert_eq!( + checked_op(max_val, max_val, max_dtype, NumericOperator::Mul)?, + None + ); - assert_eq!(checked_op(max, max, dtype, op)?, None); - Ok(()) -} - -#[test] -fn test_decimal_scalar_div_reports_unrepresentable_intermediate() -> VortexResult<()> { - // Div scales the dividend by 10^result_scale, which needs p + result_scale digits. Past - // MAX_PRECISION there is no wider width to compute in, so 1e79 overflows i256 and the - // operation reports overflow even though the quotient 1e9 would have fit the result - // precision. The array kernels size their working width identically. - let dtype = DecimalDType::new(MAX_PRECISION, 0); + // Unrepresentable intermediate dividend in Div at MAX_PRECISION reports overflow. let pow10 = |exp: u32| { i256::from_i128(10) .checked_pow(exp) .ok_or_else(|| vortex_err!("10^{exp} is representable as i256")) }; - let lhs = DecimalValue::I256(pow10(75)?); - let rhs = DecimalValue::I256(pow10(70)?); - assert_eq!( - decimal_numeric_result_dtype(dtype, NumericOperator::Div)?, - DecimalDType::new(MAX_PRECISION, 4) + checked_op( + DecimalValue::I256(pow10(75)?), + DecimalValue::I256(pow10(70)?), + max_dtype, + NumericOperator::Div, + )?, + None ); - assert_eq!(checked_op(lhs, rhs, dtype, NumericOperator::Div)?, None); - Ok(()) -} -#[test] -fn test_decimal_scalar_null_handling() -> VortexResult<()> { - let dtype = DecimalDType::new(10, 2); - let null = Scalar::null(DType::Decimal(dtype, Nullability::Nullable)); - let value = Scalar::decimal(DecimalValue::I64(200), dtype, Nullability::NonNullable); - - let result = null + // Null operand yields a null result with widened precision. + let d10_2 = DecimalDType::new(10, 2); + let null_res = Scalar::null(DType::Decimal(d10_2, Nullability::Nullable)) .as_decimal() - .checked_binary_numeric(&value.as_decimal(), NumericOperator::Add)? - .ok_or_else(|| vortex_err!("a null operand yields a null result, not an overflow"))?; - assert!(result.is_null()); + .checked_binary_numeric( + &Scalar::decimal(DecimalValue::I64(200), d10_2, Nullability::NonNullable).as_decimal(), + NumericOperator::Add, + )? + .ok_or_else(|| vortex_err!("null operand yields null"))?; + assert!(null_res.is_null()); assert_eq!( - result.dtype(), + null_res.dtype(), &DType::Decimal(DecimalDType::new(11, 2), Nullability::Nullable) ); - Ok(()) -} - -#[test] -fn test_decimal_scalar_mul_rejects_unrepresentable_scale() { - // 2e70 * 3e70 is 6e140, and a scale of -140 has no i8 representation. Saturating it to -128 - // would have silently returned the raw product 6 as 6e128. - let dtype = DecimalDType::new(10, -70); - let lhs = Scalar::decimal(DecimalValue::I64(2), dtype, Nullability::NonNullable); - let rhs = Scalar::decimal(DecimalValue::I64(3), dtype, Nullability::NonNullable); + // Unrepresentable scale and mismatched decimal types return Err. + let neg70 = Scalar::decimal( + DecimalValue::I64(2), + DecimalDType::new(10, -70), + Nullability::NonNullable, + ); assert!( - lhs.as_decimal() - .checked_binary_numeric(&rhs.as_decimal(), NumericOperator::Mul) + neg70 + .as_decimal() + .checked_binary_numeric(&neg70.as_decimal(), NumericOperator::Mul) .is_err() ); -} - -#[test] -fn test_decimal_scalar_mismatched_decimal_types() { - let lhs = Scalar::decimal( - DecimalValue::I64(1), - DecimalDType::new(10, 2), - Nullability::NonNullable, - ); - let rhs = Scalar::decimal( + let d10_3 = Scalar::decimal( DecimalValue::I64(1), DecimalDType::new(10, 3), Nullability::NonNullable, ); - assert!( - lhs.as_decimal() - .checked_binary_numeric(&rhs.as_decimal(), NumericOperator::Add) + Scalar::decimal(DecimalValue::I64(1), d10_2, Nullability::NonNullable) + .as_decimal() + .checked_binary_numeric(&d10_3.as_decimal(), NumericOperator::Add) .is_err() ); + Ok(()) } #[test] -fn test_decimal_value_from_scalar() { - let value = DecimalValue::I32(12345); - let scalar = Scalar::from(value); - - // Test extraction - let extracted: DecimalValue = DecimalValue::try_from(&scalar).unwrap(); - assert_eq!(extracted, value); - - // Test owned extraction - let extracted_owned: DecimalValue = DecimalValue::try_from(scalar).unwrap(); - assert_eq!(extracted_owned, value); -} - -#[test] -fn test_decimal_value_option_from_scalar() { - // Non-null case - let value = DecimalValue::I64(999999); - let scalar = Scalar::from(value); - - let extracted: Option = Option::try_from(&scalar).unwrap(); - assert_eq!(extracted, Some(value)); - - // Null case - let null_scalar = Scalar::null(DType::Decimal( - DecimalDType::new(10, 2), - Nullability::Nullable, - )); - - let extracted_null: Option = Option::try_from(&null_scalar).unwrap(); - assert_eq!(extracted_null, None); -} - -#[test] -fn test_decimal_value_from_conversion() { - // Test that From creates reasonable defaults - let values = vec![ - DecimalValue::I8(127), - DecimalValue::I16(32767), - DecimalValue::I32(1000000), - DecimalValue::I64(1000000000000), - DecimalValue::I128(123456789012345678901234567890), - DecimalValue::I256(i256::from_i128(987654321)), - ]; - - for value in values { - let scalar = Scalar::from(value); - assert!(!scalar.is_null()); - - // Verify we can extract it back - let extracted: DecimalValue = DecimalValue::try_from(&scalar).unwrap(); - assert_eq!(extracted, value); - } -} - -#[test] -fn test_decimal_value_checked_add() { - let a = DecimalValue::I64(100); - let b = DecimalValue::I64(200); - let result = a.checked_add(&b).unwrap(); - assert_eq!(result, DecimalValue::I64(300)); -} - -#[test] -fn test_decimal_value_checked_sub() { - let a = DecimalValue::I64(500); - let b = DecimalValue::I64(200); - let result = a.checked_sub(&b).unwrap(); - assert_eq!(result, DecimalValue::I64(300)); -} - -#[test] -fn test_decimal_value_checked_mul() { - let a = DecimalValue::I32(50); - let b = DecimalValue::I32(10); - let result = a.checked_mul(&b).unwrap(); - assert_eq!(result, DecimalValue::I32(500)); -} - -#[test] -fn test_decimal_value_checked_div() { - let a = DecimalValue::I64(1000); - let b = DecimalValue::I64(10); - let result = a.checked_div(&b).unwrap(); - assert_eq!(result, DecimalValue::I64(100)); -} - -#[test] -fn test_decimal_value_checked_div_by_zero() { - let a = DecimalValue::I64(1000); - let b = DecimalValue::I64(0); - let result = a.checked_div(&b); - assert_eq!(result, None); -} - -#[test] -fn test_decimal_value_mixed_types() { - // Test operations with different underlying types - let a = DecimalValue::I8(10); - let b = DecimalValue::I128(20); - let result = a.checked_add(&b).unwrap(); - assert_eq!(result, DecimalValue::I128(30)); -} - -#[test] -fn test_checked_ops_preserve_type() { - // Operations should return the wider of the two operand types, not unconditionally upcast to I256 +fn test_decimal_value_checked_ops_width_and_overflow() { let add = DecimalValue::I32(5) .checked_add(&DecimalValue::I32(3)) .unwrap(); - assert_eq!(add.decimal_type(), DecimalType::I32); + assert_eq!( + (add.decimal_type(), add), + (DecimalType::I32, DecimalValue::I32(8)) + ); let sub = DecimalValue::I64(10) .checked_sub(&DecimalValue::I64(3)) .unwrap(); - assert_eq!(sub.decimal_type(), DecimalType::I64); + assert_eq!( + (sub.decimal_type(), sub), + (DecimalType::I64, DecimalValue::I64(7)) + ); let mul = DecimalValue::I8(2) .checked_mul(&DecimalValue::I8(3)) .unwrap(); - assert_eq!(mul.decimal_type(), DecimalType::I8); + assert_eq!( + (mul.decimal_type(), mul), + (DecimalType::I8, DecimalValue::I8(6)) + ); let div = DecimalValue::I128(10) .checked_div(&DecimalValue::I128(2)) .unwrap(); - assert_eq!(div.decimal_type(), DecimalType::I128); - - let add_i256 = DecimalValue::I256(i256::from_i128(1)) - .checked_add(&DecimalValue::I256(i256::from_i128(2))) - .unwrap(); - assert_eq!(add_i256.decimal_type(), DecimalType::I256); - assert_eq!(add.as_i256(), i256::from_i128(8)); - assert_eq!(sub.as_i256(), i256::from_i128(7)); - assert_eq!(mul.as_i256(), i256::from_i128(6)); - assert_eq!(div.as_i256(), i256::from_i128(5)); - assert_eq!(add_i256.as_i256(), i256::from_i128(3)); -} + assert_eq!( + (div.decimal_type(), div), + (DecimalType::I128, DecimalValue::I128(5)) + ); -#[test] -fn test_checked_ops_mixed_types_use_wider() { - let add = DecimalValue::I8(1) + let mixed = DecimalValue::I8(1) .checked_add(&DecimalValue::I64(2)) .unwrap(); - assert_eq!(add.decimal_type(), DecimalType::I64); + assert_eq!( + (mixed.decimal_type(), mixed), + (DecimalType::I64, DecimalValue::I64(3)) + ); - let sub = DecimalValue::I32(10) - .checked_sub(&DecimalValue::I128(3)) + let wide = DecimalValue::I256(i256::from_i128(1)) + .checked_add(&DecimalValue::I256(i256::from_i128(2))) .unwrap(); - assert_eq!(sub.decimal_type(), DecimalType::I128); - assert_eq!(add.as_i256(), i256::from_i128(3)); - assert_eq!(sub.as_i256(), i256::from_i128(7)); -} + assert_eq!(wide.decimal_type(), DecimalType::I256); -#[test] -fn test_checked_ops_overflow_at_target_width() { + assert_eq!( + DecimalValue::I64(1000).checked_div(&DecimalValue::I64(0)), + None + ); assert_eq!( DecimalValue::I8(i8::MAX).checked_add(&DecimalValue::I8(1)), None @@ -1261,226 +579,39 @@ fn test_checked_ops_overflow_at_target_width() { ); } -#[test] -fn test_fits_in_precision_exact_boundary() { - use crate::dtype::DecimalDType; - - // Precision 3 means max value is 10^3 - 1 = 999 - let dtype = DecimalDType::new(3, 0); - - // Test exact upper boundary: 999 should fit - let value = DecimalValue::I16(999); - assert!(value.fits_in_precision(dtype)); - - // Test just beyond upper boundary: 1000 should NOT fit - let value = DecimalValue::I16(1000); - assert!(!value.fits_in_precision(dtype)); - - // Test exact lower boundary: -999 should fit - let value = DecimalValue::I16(-999); - assert!(value.fits_in_precision(dtype)); - - // Test just beyond lower boundary: -1000 should NOT fit - let value = DecimalValue::I16(-1000); - assert!(!value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_zero() { - use crate::dtype::DecimalDType; - - let dtype = DecimalDType::new(5, 2); - - // Zero should always fit - let value = DecimalValue::I8(0); - assert!(value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_small_precision() { - use crate::dtype::DecimalDType; - - // Precision 1 means max value is 10^1 - 1 = 9 - let dtype = DecimalDType::new(1, 0); - - // Test values within range - for i in -9..=9 { - let value = DecimalValue::I8(i); - assert!( - value.fits_in_precision(dtype), - "value {} should fit in precision 1", - i - ); - } - - // Test values outside range - let value = DecimalValue::I8(10); - assert!(!value.fits_in_precision(dtype)); - let value = DecimalValue::I8(-10); - assert!(!value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_large_precision() { - use crate::dtype::DecimalDType; - - // Precision 38 means max value is 10^38 - 1 - let dtype = DecimalDType::new(38, 0); - - // Test i128::MAX which is approximately 1.7e38 - // This should NOT fit because 10^38 - 1 < i128::MAX - let value = DecimalValue::I128(i128::MAX); - assert!(!value.fits_in_precision(dtype)); - - // Test a large value that should fit: 10^37 - let value = DecimalValue::I128(10_i128.pow(37)); - assert!(value.fits_in_precision(dtype)); - - // Test 10^38 - 1 (the exact maximum) - let max_val = i256::from_i128(10).wrapping_pow(38) - i256::from_i128(1); - let value = DecimalValue::I256(max_val); - assert!(value.fits_in_precision(dtype)); - - // Test 10^38 (just over the maximum) - let over_max = i256::from_i128(10).wrapping_pow(38); - let value = DecimalValue::I256(over_max); - assert!(!value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_max_precision() { - use crate::dtype::DecimalDType; - - // Maximum precision is 76 - let dtype = DecimalDType::new(76, 0); - - // Test that reasonable i256 values fit - let value = DecimalValue::I256(i256::from_i128(i128::MAX)); - assert!(value.fits_in_precision(dtype)); - - // Test negative - let value = DecimalValue::I256(i256::from_i128(i128::MIN)); - assert!(value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_different_scales() { - use crate::dtype::DecimalDType; - - // Scale doesn't affect the precision check - it's only about the stored value - let value = DecimalValue::I32(12345); - - // Precision 5 with different scales - assert!(value.fits_in_precision(DecimalDType::new(5, 0))); - assert!(value.fits_in_precision(DecimalDType::new(5, 2))); - assert!(value.fits_in_precision(DecimalDType::new(5, -2))); - - // Precision 4 should fail (max value 9999, we have 12345) - assert!(!value.fits_in_precision(DecimalDType::new(4, 0))); - assert!(!value.fits_in_precision(DecimalDType::new(4, 2))); -} - -#[test] -fn test_fits_in_precision_negative_values() { - use crate::dtype::DecimalDType; - - let dtype = DecimalDType::new(4, 2); - - // Test negative values at boundaries - // Precision 4 means max magnitude is 9999 - let value = DecimalValue::I16(-9999); - assert!(value.fits_in_precision(dtype)); - - let value = DecimalValue::I16(-10000); - assert!(!value.fits_in_precision(dtype)); - - let value = DecimalValue::I16(-1); - assert!(value.fits_in_precision(dtype)); -} - -#[test] -fn test_fits_in_precision_mixed_decimal_value_types() { - use crate::dtype::DecimalDType; - - let dtype = DecimalDType::new(5, 0); - - // Test that different DecimalValue types work correctly - assert!(DecimalValue::I8(99).fits_in_precision(dtype)); - assert!(DecimalValue::I16(9999).fits_in_precision(dtype)); - assert!(DecimalValue::I32(99999).fits_in_precision(dtype)); - assert!(!DecimalValue::I64(100000).fits_in_precision(dtype)); - assert!(DecimalValue::I128(99999).fits_in_precision(dtype)); - assert!(!DecimalValue::I256(i256::from_i128(100000)).fits_in_precision(dtype)); -} - -fn cast_decimal_to_f64(precision: u8, scale: i8, stored: i64) -> VortexResult { - let scalar = Scalar::decimal( - DecimalValue::I64(stored), - DecimalDType::new(precision, scale), - Nullability::NonNullable, - ); - let casted = scalar.cast(&DType::Primitive(PType::F64, Nullability::NonNullable))?; - (&casted).try_into() -} - -#[rstest] -#[case::negative_scale(5, -5, 1, 100_000.0)] -#[case::extreme_negative_scale(1, -30, 1, 1e30)] -#[case::scale_past_i128(MAX_PRECISION, 39, 1, 1e-39)] -#[case::max_scale(MAX_PRECISION, MAX_SCALE, 1, 1e-76)] -#[case::negative_value_negative_scale(5, -5, -1, -100_000.0)] -fn cast_decimal_to_f64_spans_the_scale_domain( - #[case] precision: u8, - #[case] scale: i8, - #[case] stored: i64, - #[case] expected: f64, -) -> VortexResult<()> { - let value = cast_decimal_to_f64(precision, scale, stored)?; - // `10^scale` is not exact in `f64` above `10^22`. - assert!( - (value - expected).abs() <= expected.abs() * 1e-15, - "decimal({precision},{scale}) storing {stored} cast to {value}, expected {expected}" - ); - Ok(()) -} - #[rstest] -#[case(10, 2, 12345, 123.45)] -#[case(10, 0, -7, -7.0)] -#[case(20, 6, 1_500_000, 1.5)] -fn cast_decimal_to_f64_is_exact_for_common_scales( - #[case] precision: u8, - #[case] scale: i8, - #[case] stored: i64, - #[case] expected: f64, -) -> VortexResult<()> { - assert_eq!(cast_decimal_to_f64(precision, scale, stored)?, expected); - Ok(()) -} - -#[test] -fn cast_decimal_to_narrow_float_uses_the_same_scale_factor() -> VortexResult<()> { - let scalar = Scalar::decimal( - DecimalValue::I64(1), - DecimalDType::new(5, -5), - Nullability::NonNullable, - ); - let f32_value: f32 = - (&scalar.cast(&DType::Primitive(PType::F32, Nullability::NonNullable))?).try_into()?; - assert_eq!(f32_value, 100_000.0); - Ok(()) -} - -#[test] -fn cast_wide_i256_decimal_to_f64() -> VortexResult<()> { - let beyond_i128 = i256::from_i128(i128::MAX) + i256::ONE; - let scalar = Scalar::decimal( - DecimalValue::I256(beyond_i128), - DecimalDType::new(MAX_PRECISION, 2), - Nullability::NonNullable, - ); - let value: f64 = - (&scalar.cast(&DType::Primitive(PType::F64, Nullability::NonNullable))?).try_into()?; - assert_eq!(value, 2f64.powi(127) / 100.0); - Ok(()) +#[case::p1_max(DecimalValue::I8(9), DecimalDType::new(1, 0), true)] +#[case::p1_min(DecimalValue::I8(-9), DecimalDType::new(1, 0), true)] +#[case::p1_over(DecimalValue::I8(10), DecimalDType::new(1, 0), false)] +#[case::p1_under(DecimalValue::I8(-10), DecimalDType::new(1, 0), false)] +#[case::p3_max(DecimalValue::I16(999), DecimalDType::new(3, 0), true)] +#[case::p3_over(DecimalValue::I16(1000), DecimalDType::new(3, 0), false)] +#[case::p3_min(DecimalValue::I16(-999), DecimalDType::new(3, 0), true)] +#[case::p3_under(DecimalValue::I16(-1000), DecimalDType::new(3, 0), false)] +#[case::scale_invariance_pos(DecimalValue::I32(12_345), DecimalDType::new(5, 2), true)] +#[case::scale_invariance_neg(DecimalValue::I32(12_345), DecimalDType::new(5, -2), true)] +#[case::scale_invariance_fail(DecimalValue::I32(12_345), DecimalDType::new(4, 2), false)] +#[case::p38_i128_max_fails(DecimalValue::I128(i128::MAX), DecimalDType::new(38, 0), false)] +#[case::p38_exact_max( + DecimalValue::I256(i256::from_i128(10).wrapping_pow(38) - i256::ONE), + DecimalDType::new(38, 0), + true +)] +#[case::p38_over_max( + DecimalValue::I256(i256::from_i128(10).wrapping_pow(38)), + DecimalDType::new(38, 0), + false +)] +#[case::p76_i128_min( + DecimalValue::I256(i256::from_i128(i128::MIN)), + DecimalDType::new(76, 0), + true +)] +#[case::zero_fits(DecimalValue::I8(0), DecimalDType::new(5, 2), true)] +fn test_fits_in_precision_boundaries( + #[case] value: DecimalValue, + #[case] dtype: DecimalDType, + #[case] expected: bool, +) { + assert_eq!(value.fits_in_precision(dtype), expected); } diff --git a/vortex-array/src/scalar/typed_view/extension/tests.rs b/vortex-array/src/scalar/typed_view/extension/tests.rs index 7aae12229a1..b96fcfcc26c 100644 --- a/vortex-array/src/scalar/typed_view/extension/tests.rs +++ b/vortex-array/src/scalar/typed_view/extension/tests.rs @@ -1,10 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::collections::hash_map::DefaultHasher; -use std::hash::Hash; -use std::hash::Hasher; - use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -20,6 +16,7 @@ use crate::scalar::ScalarValue; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] struct TestI32Ext; + impl ExtVTable for TestI32Ext { type Metadata = EmptyMetadata; type StoredMetadata = Self::Metadata; @@ -58,193 +55,78 @@ impl ExtVTable for TestI32Ext { } } -impl TestI32Ext { - fn new_non_nullable() -> ExtDType { - ExtDType::try_new(EmptyMetadata, Nullability::NonNullable).unwrap() - } -} - -#[test] -fn test_ext_scalar_equality() { - let scalar1 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - let scalar2 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - let scalar3 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(43i32, Nullability::NonNullable), - ); - - let ext1 = scalar1.as_extension(); - let ext2 = scalar2.as_extension(); - let ext3 = scalar3.as_extension(); - - assert_eq!(ext1, ext2); - assert_ne!(ext1, ext3); -} - -#[test] -fn test_ext_scalar_partial_ord() { - let scalar1 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(10i32, Nullability::NonNullable), - ); - let scalar2 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(20i32, Nullability::NonNullable), - ); - - let ext1 = scalar1.as_extension(); - let ext2 = scalar2.as_extension(); - - assert!(ext1 < ext2); - assert!(ext2 > ext1); -} - -#[test] -fn test_ext_scalar_partial_ord_different_types() { - #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] - struct TestExt2; - impl ExtVTable for TestExt2 { - type Metadata = EmptyMetadata; - type StoredMetadata = Self::Metadata; - type NativeValue<'a> = &'a str; - - #[expect(clippy::disallowed_methods, reason = "test-only id")] - fn id(&self) -> ExtId { - ExtId::new("test_ext_2") - } - - fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { - Ok(vec![]) - } - - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { - Ok(EmptyMetadata) - } - - fn metadata_from_storage( - &self, - stored_metadata: Self::StoredMetadata, - _storage_dtype: &DType, - ) -> VortexResult { - Ok(stored_metadata) - } +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct TestExtMetadata; - fn storage_dtype(_metadata: &Self::Metadata) -> DType { - DType::Primitive(PType::I32, Nullability::NonNullable) - } +impl ExtVTable for TestExtMetadata { + type Metadata = usize; + type StoredMetadata = Self::Metadata; + type NativeValue<'a> = &'a str; - fn unpack_native<'a>( - _ext_dtype: &'a ExtDType, - _storage_value: &'a ScalarValue, - ) -> VortexResult> { - Ok("") - } + #[expect(clippy::disallowed_methods, reason = "test-only id")] + fn id(&self) -> ExtId { + ExtId::new("test_ext_metadata") } - let scalar1 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(10i32, Nullability::NonNullable), - ); - let scalar2 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(20i32, Nullability::NonNullable), - ); - - let ext1 = scalar1.as_extension(); - let ext2 = scalar2.as_extension(); - - // Different extension types should not be comparable - assert_eq!(ext1.partial_cmp(&ext2), None); -} - -#[test] -fn test_ext_scalar_hash() { - use vortex_utils::aliases::hash_set::HashSet; - - let scalar1 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - let scalar2 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - - let mut set = HashSet::new(); - set.insert(scalar2); - set.insert(scalar1); - - // Same value should hash the same - assert_eq!(set.len(), 1); + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + vortex_bail!("not implemented") + } - // Different value should hash differently - let scalar3 = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(43i32, Nullability::NonNullable), - ); - set.insert(scalar3); - assert_eq!(set.len(), 2); -} + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + Ok(0) + } -#[test] -fn test_ext_scalar_hash_ignores_storage_nullability() { - let nullable = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42_i32, Nullability::Nullable), - ); - let non_nullable = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42_i32, Nullability::NonNullable), - ); - let nullable = nullable.as_extension(); - let non_nullable = non_nullable.as_extension(); + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } - assert_eq!(nullable, non_nullable); + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } - let mut nullable_hasher = DefaultHasher::new(); - nullable.hash(&mut nullable_hasher); - let mut non_nullable_hasher = DefaultHasher::new(); - non_nullable.hash(&mut non_nullable_hasher); - assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + _storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok("") + } } #[test] -fn test_ext_scalar_storage() { - let storage_scalar = Scalar::primitive(42i32, Nullability::NonNullable); - let ext_scalar = Scalar::extension::(EmptyMetadata, storage_scalar.clone()); - +fn test_ext_scalar_accessors_and_different_types_ord() -> VortexResult<()> { + let storage = Scalar::primitive(42i32, Nullability::NonNullable); + let ext_scalar = Scalar::extension::(EmptyMetadata, storage.clone()); let ext = ext_scalar.as_extension(); - let storage = ext.to_storage_scalar(); - assert_eq!(storage.dtype(), storage_scalar.dtype()); - assert_eq!(storage, storage_scalar); -} -#[test] -fn test_ext_scalar_ext_dtype() { - let ext_dtype = TestI32Ext::new_non_nullable(); - let scalar = Scalar::extension::( - EmptyMetadata.clone(), + let expected_dtype = ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable)?; + assert_eq!(ext.ext_dtype(), &expected_dtype.erased()); + assert_eq!(ext.to_storage_scalar(), storage); + + let meta_scalar = Scalar::extension::( + 1234, Scalar::primitive(42i32, Nullability::NonNullable), ); - - let ext = scalar.as_extension(); - assert_eq!(ext.ext_dtype().id(), ext_dtype.id()); - assert_eq!(ext.ext_dtype(), &ext_dtype.erased()); + assert_eq!( + meta_scalar + .as_extension() + .ext_dtype() + .metadata::(), + &1234 + ); + assert_eq!(ext.partial_cmp(&meta_scalar.as_extension()), None); + Ok(()) } #[test] -fn test_ext_scalar_rejects_storage_cast() { +fn test_ext_scalar_cast_errors() { let scalar = Scalar::extension::( EmptyMetadata, Scalar::primitive(42i32, Nullability::NonNullable), ); - assert!( scalar .cast(&DType::Primitive(PType::I32, Nullability::NonNullable)) @@ -255,102 +137,15 @@ fn test_ext_scalar_rejects_storage_cast() { .cast(&DType::Primitive(PType::I32, Nullability::Nullable)) .is_err() ); -} - -#[test] -fn test_ext_scalar_cast_to_self() { - let ext_dtype = TestI32Ext::new_non_nullable(); - - let scalar = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - - let ext_dtype = ext_dtype.erased(); - - // Cast to same extension type - let casted = scalar.cast(&DType::Extension(ext_dtype.clone())).unwrap(); - assert_eq!(casted.dtype(), &DType::Extension(ext_dtype.clone())); - assert_eq!(casted.value(), scalar.value()); - - // Cast to nullable version of same extension type - let nullable_ext = DType::Extension(ext_dtype).as_nullable(); - let casted_nullable = scalar.cast(&nullable_ext).unwrap(); - assert_eq!(casted_nullable.dtype(), &nullable_ext); - assert_eq!(casted_nullable.value(), scalar.value()); -} + assert!(scalar.cast(&DType::Utf8(Nullability::NonNullable)).is_err()); -#[test] -fn test_ext_scalar_cast_incompatible() { - let scalar = Scalar::extension::( - EmptyMetadata, - Scalar::primitive(42i32, Nullability::NonNullable), - ); - - // Cast to incompatible type should fail - let result = scalar.cast(&DType::Utf8(Nullability::NonNullable)); - assert!(result.is_err()); -} - -#[test] -fn test_ext_scalar_cast_null_to_non_nullable() { - let scalar = Scalar::extension::( + let null_ext = Scalar::extension::( EmptyMetadata, Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), ); - - // Cast null to non-nullable should fail - let result = scalar.cast(&DType::Primitive(PType::I32, Nullability::NonNullable)); - assert!(result.is_err()); -} - -#[test] -fn test_ext_scalar_with_metadata() { - #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] - struct TestExtMetadata; - impl ExtVTable for TestExtMetadata { - type Metadata = usize; - type StoredMetadata = Self::Metadata; - type NativeValue<'a> = &'a str; - - #[expect(clippy::disallowed_methods, reason = "test-only id")] - fn id(&self) -> ExtId { - ExtId::new("test_ext_metadata") - } - - fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { - vortex_bail!("not implemented") - } - - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { - vortex_bail!("not implemented") - } - - fn metadata_from_storage( - &self, - stored_metadata: Self::StoredMetadata, - _storage_dtype: &DType, - ) -> VortexResult { - Ok(stored_metadata) - } - - fn storage_dtype(_metadata: &Self::Metadata) -> DType { - DType::Primitive(PType::I32, Nullability::NonNullable) - } - - fn unpack_native<'a>( - _ext_dtype: &'a ExtDType, - _storage_value: &'a ScalarValue, - ) -> VortexResult> { - Ok("") - } - } - - let scalar = Scalar::extension::( - 1234, - Scalar::primitive(42i32, Nullability::NonNullable), + assert!( + null_ext + .cast(&DType::Primitive(PType::I32, Nullability::NonNullable)) + .is_err() ); - - let ext = scalar.as_extension(); - assert_eq!(ext.ext_dtype().metadata::(), &1234); } diff --git a/vortex-array/src/scalar/typed_view/list.rs b/vortex-array/src/scalar/typed_view/list.rs index 35b24012771..6674b459513 100644 --- a/vortex-array/src/scalar/typed_view/list.rs +++ b/vortex-array/src/scalar/typed_view/list.rs @@ -233,9 +233,6 @@ impl<'a> ListScalar<'a> { #[cfg(test)] mod tests { - use std::collections::hash_map::DefaultHasher; - use std::hash::Hash; - use std::hash::Hasher; use std::sync::Arc; use super::*; @@ -244,323 +241,60 @@ mod tests { use crate::dtype::PType; #[test] - fn test_empty_list() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let list_scalar = Scalar::list_empty(element_dtype, Nullability::NonNullable); + fn test_list_accessors_display_and_vec_conversions() -> VortexResult<()> { + let elem = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let list = list_scalar.as_list(); - assert_eq!(list.len(), 0); - assert!(list.is_empty()); - assert!(!list.is_null()); - } - - #[test] - fn test_null_list() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)); - let null = Scalar::null(DType::List(element_dtype, Nullability::Nullable)); + let empty = Scalar::list_empty(Arc::clone(&elem), Nullability::NonNullable); + assert!(empty.as_list().is_empty()); + assert!(!empty.as_list().is_null()); + assert!(Vec::::try_from(&empty)?.is_empty()); - let list = null.as_list(); - assert!(list.is_empty()); - assert!(list.is_null()); - } - - #[test] - fn test_list_element_access() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(10i32, Nullability::NonNullable), - Scalar::primitive(20i32, Nullability::NonNullable), - Scalar::primitive(30i32, Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); + let null = Scalar::null(DType::List(Arc::clone(&elem), Nullability::Nullable)); + assert!(null.as_list().is_empty()); + assert!(null.as_list().is_null()); + let list_scalar = Scalar::list( + Arc::clone(&elem), + vec![ + Scalar::primitive(10i32, Nullability::NonNullable), + Scalar::primitive(20i32, Nullability::NonNullable), + Scalar::primitive(30i32, Nullability::NonNullable), + ], + Nullability::NonNullable, + ); let list = list_scalar.as_list(); assert_eq!(list.len(), 3); - assert!(!list.is_empty()); - assert!(!list.is_null()); - - // Test element access - let elem0 = list.element(0).unwrap(); - assert_eq!(elem0.as_primitive().typed_value::().unwrap(), 10); - - let elem1 = list.element(1).unwrap(); - assert_eq!(elem1.as_primitive().typed_value::().unwrap(), 20); - - let elem2 = list.element(2).unwrap(); - assert_eq!(elem2.as_primitive().typed_value::().unwrap(), 30); - - // Test out of bounds - assert!(list.element(3).is_none()); - } - - #[test] - fn test_list_elements() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(100i32, Nullability::NonNullable), - Scalar::primitive(200i32, Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); - - let list = list_scalar.as_list(); - let elements = list.elements().unwrap(); - - assert_eq!(elements.len(), 2); assert_eq!( - elements[0].as_primitive().typed_value::().unwrap(), - 100 + list.element(0).unwrap().as_primitive().typed_value::(), + Some(10) ); assert_eq!( - elements[1].as_primitive().typed_value::().unwrap(), - 200 - ); - } - - #[test] - fn test_list_display() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); - - let list = list_scalar.as_list(); - let display = format!("{list}"); - assert_eq!(display, "[1i32, 2i32]"); - } - - #[test] - fn test_list_equality() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children1 = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ]; - let list_scalar1 = Scalar::list( - Arc::clone(&element_dtype), - children1, - Nullability::NonNullable, - ); - - let children2 = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ]; - let list_scalar2 = Scalar::list(element_dtype, children2, Nullability::NonNullable); - - let list1 = list_scalar1.as_list(); - let list2 = list_scalar2.as_list(); - - assert_eq!(list1, list2); - } - - #[test] - fn test_list_inequality() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children1 = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ]; - let list_scalar1 = Scalar::list( - Arc::clone(&element_dtype), - children1, - Nullability::NonNullable, - ); - - let children2 = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(3i32, Nullability::NonNullable), - ]; - let list_scalar2 = Scalar::list(element_dtype, children2, Nullability::NonNullable); - - let list1 = list_scalar1.as_list(); - let list2 = list_scalar2.as_list(); - - assert_ne!(list1, list2); - } - - #[test] - fn test_list_partial_ord() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - - let children1 = vec![Scalar::primitive(1i32, Nullability::NonNullable)]; - let list_scalar1 = Scalar::list( - Arc::clone(&element_dtype), - children1, - Nullability::NonNullable, - ); - - let children2 = vec![Scalar::primitive(2i32, Nullability::NonNullable)]; - let list_scalar2 = Scalar::list(element_dtype, children2, Nullability::NonNullable); - - let list1 = list_scalar1.as_list(); - let list2 = list_scalar2.as_list(); - - assert!(list1 < list2); - } - - #[test] - fn test_list_partial_ord_different_types() { - let element_dtype1 = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let element_dtype2 = Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)); - - let children1 = vec![Scalar::primitive(1i32, Nullability::NonNullable)]; - let list_scalar1 = Scalar::list(element_dtype1, children1, Nullability::NonNullable); - - let children2 = vec![Scalar::primitive(1i64, Nullability::NonNullable)]; - let list_scalar2 = Scalar::list(element_dtype2, children2, Nullability::NonNullable); - - let list1 = list_scalar1.as_list(); - let list2 = list_scalar2.as_list(); - - assert!(list1.partial_cmp(&list2).is_none()); - } - - #[test] - fn test_list_hash_ignores_nested_nullability() { - let nullable = Scalar::list( - DType::Primitive(PType::I32, Nullability::Nullable), - vec![Scalar::primitive(42_i32, Nullability::Nullable)], - Nullability::NonNullable, - ); - let non_nullable = Scalar::list( - DType::Primitive(PType::I32, Nullability::NonNullable), - vec![Scalar::primitive(42_i32, Nullability::NonNullable)], - Nullability::NonNullable, + list.element(2).unwrap().as_primitive().typed_value::(), + Some(30) ); - let nullable = nullable.as_list(); - let non_nullable = non_nullable.as_list(); - - assert_eq!(nullable, non_nullable); - - let mut nullable_hasher = DefaultHasher::new(); - nullable.hash(&mut nullable_hasher); - let mut non_nullable_hasher = DefaultHasher::new(); - non_nullable.hash(&mut non_nullable_hasher); - assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); - } - - #[test] - fn test_vec_conversion() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(10i32, Nullability::NonNullable), - Scalar::primitive(20i32, Nullability::NonNullable), - Scalar::primitive(30i32, Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); - - let vec: Vec = Vec::try_from(&list_scalar).unwrap(); - assert_eq!(vec, vec![10, 20, 30]); - } - - #[test] - fn test_vec_conversion_empty_list() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)); - let list_scalar = Scalar::list_empty(element_dtype, Nullability::Nullable); - - let result: VortexResult> = Vec::try_from(&list_scalar); - assert!(result.unwrap().is_empty()); - } - - #[test] - fn test_list_cast() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); - - let list = list_scalar.as_list(); + assert!(list.element(3).is_none()); + assert_eq!(list.elements().unwrap().len(), 3); + assert_eq!(format!("{list}"), "[10i32, 20i32, 30i32]"); + assert_eq!(Vec::::try_from(&list_scalar)?, vec![10, 20, 30]); - // Cast to list with i64 elements - let target_dtype = DType::List( + // Different element dtypes are incomparable via PartialOrd. + let i64_list = Scalar::list( Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), + vec![Scalar::primitive(1i64, Nullability::NonNullable)], Nullability::NonNullable, ); - - let casted = list.cast(&target_dtype).unwrap(); - let casted_list = casted.as_list(); - - assert_eq!(casted_list.len(), 2); - let elem0 = casted_list.element(0).unwrap(); - assert_eq!(elem0.as_primitive().typed_value::().unwrap(), 1); + assert!(list.partial_cmp(&i64_list.as_list()).is_none()); + assert!(Scalar::from(42i32).as_list_opt().is_none()); + Ok(()) } #[test] #[should_panic(expected = "tried to create list of i32 with values of type i64")] fn test_list_wrong_element_type_panic() { - let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let children = vec![ - Scalar::primitive(1i64, Nullability::NonNullable), // Wrong type! - ]; - Scalar::list(element_dtype, children, Nullability::NonNullable); - } - - #[test] - fn test_try_from_wrong_dtype() { - let scalar = Scalar::primitive(42i32, Nullability::NonNullable); - assert!(scalar.as_list_opt().is_none()); - } - - #[test] - fn test_string_list() { - let element_dtype = Arc::new(DType::Utf8(Nullability::NonNullable)); - let children = vec![ - Scalar::utf8("hello".to_string(), Nullability::NonNullable), - Scalar::utf8("world".to_string(), Nullability::NonNullable), - ]; - let list_scalar = Scalar::list(element_dtype, children, Nullability::NonNullable); - - let list = list_scalar.as_list(); - assert_eq!(list.len(), 2); - - let elem0 = list.element(0).unwrap(); - assert_eq!(elem0.as_utf8().value().unwrap().as_str(), "hello"); - - let elem1 = list.element(1).unwrap(); - assert_eq!(elem1.as_utf8().value().unwrap().as_str(), "world"); - } - - #[test] - fn test_nested_lists() { - let inner_element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); - let inner_list_dtype = Arc::new(DType::List( - Arc::clone(&inner_element_dtype), - Nullability::NonNullable, - )); - - let inner_list1 = Scalar::list( - Arc::clone(&inner_element_dtype), - vec![ - Scalar::primitive(1i32, Nullability::NonNullable), - Scalar::primitive(2i32, Nullability::NonNullable), - ], + Scalar::list( + Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), + vec![Scalar::primitive(1i64, Nullability::NonNullable)], Nullability::NonNullable, ); - - let inner_list2 = Scalar::list( - inner_element_dtype, - vec![ - Scalar::primitive(3i32, Nullability::NonNullable), - Scalar::primitive(4i32, Nullability::NonNullable), - ], - Nullability::NonNullable, - ); - - let outer_list = Scalar::list( - inner_list_dtype, - vec![inner_list1, inner_list2], - Nullability::NonNullable, - ); - - let list = outer_list.as_list(); - assert_eq!(list.len(), 2); - - let nested_list = list.element(0).unwrap(); - let nested = nested_list.as_list(); - assert_eq!(nested.len(), 2); } } diff --git a/vortex-array/src/scalar/typed_view/primitive/tests.rs b/vortex-array/src/scalar/typed_view/primitive/tests.rs index 957d32af846..d412f2533ea 100644 --- a/vortex-array/src/scalar/typed_view/primitive/tests.rs +++ b/vortex-array/src/scalar/typed_view/primitive/tests.rs @@ -6,6 +6,7 @@ use std::cmp::Ordering; use num_traits::CheckedSub; use rstest::rstest; use vortex_error::VortexExpect; +use vortex_error::VortexResult; use vortex_utils::aliases::hash_set::HashSet; use super::pvalue::CoercePValue; @@ -21,87 +22,34 @@ use crate::scalar::PrimitiveScalar; use crate::scalar::ScalarValue; #[test] -fn test_integer_subtract() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(5)); - let value2 = ScalarValue::Primitive(PValue::I32(4)); - let p_scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let p_scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - let pscalar_or_overflow = p_scalar1.checked_sub(&p_scalar2); - let value_or_null_or_type_error = pscalar_or_overflow.unwrap().as_::(); - assert_eq!(value_or_null_or_type_error.unwrap(), 1); +fn test_subtract_and_overflow() -> VortexResult<()> { + let i32_dt = DType::Primitive(PType::I32, Nullability::NonNullable); + let v5 = ScalarValue::Primitive(PValue::I32(5)); + let v4 = ScalarValue::Primitive(PValue::I32(4)); + let a = PrimitiveScalar::try_new(&i32_dt, Some(&v5))?; + let b = PrimitiveScalar::try_new(&i32_dt, Some(&v4))?; + assert_eq!(a.checked_sub(&b).unwrap().as_::(), Some(1)); + assert_eq!((a - b).as_::(), Some(1)); - assert_eq!((p_scalar1 - p_scalar2).as_::().unwrap(), 1); + let f32_dt = DType::Primitive(PType::F32, Nullability::NonNullable); + let f1 = ScalarValue::Primitive(PValue::F32(1.99f32)); + let f2 = ScalarValue::Primitive(PValue::F32(1.0f32)); + let fa = PrimitiveScalar::try_new(&f32_dt, Some(&f1))?; + let fb = PrimitiveScalar::try_new(&f32_dt, Some(&f2))?; + assert_eq!(fa.checked_sub(&fb).unwrap().as_::(), Some(0.99f32)); + assert_eq!((fa - fb).as_::(), Some(0.99f32)); + Ok(()) } #[test] #[should_panic(expected = "PrimitiveScalar subtract: overflow or underflow")] fn test_integer_subtract_overflow() { let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(i32::MIN)); - let value2 = ScalarValue::Primitive(PValue::I32(i32::MAX)); - let p_scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let p_scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - let _ = p_scalar1 - p_scalar2; -} - -#[test] -fn test_float_subtract() { - let dtype = DType::Primitive(PType::F32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::F32(1.99f32)); - let value2 = ScalarValue::Primitive(PValue::F32(1.0f32)); - let p_scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let p_scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - let pscalar_or_overflow = p_scalar1.checked_sub(&p_scalar2).unwrap(); - let value_or_null_or_type_error = pscalar_or_overflow.as_::(); - assert_eq!(value_or_null_or_type_error.unwrap(), 0.99f32); - - assert_eq!((p_scalar1 - p_scalar2).as_::().unwrap(), 0.99f32); -} - -#[test] -fn test_primitive_scalar_equality() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(42)); - let value2 = ScalarValue::Primitive(PValue::I32(42)); - let value3 = ScalarValue::Primitive(PValue::I32(43)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - let scalar3 = PrimitiveScalar::try_new(&dtype, Some(&value3)).unwrap(); - - assert_eq!(scalar1, scalar2); - assert_ne!(scalar1, scalar3); -} - -#[test] -fn test_primitive_scalar_partial_ord() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(10)); - let value2 = ScalarValue::Primitive(PValue::I32(20)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - - assert!(scalar1 < scalar2); - assert!(scalar2 > scalar1); - assert_eq!(scalar1.partial_cmp(&scalar1), Some(Ordering::Equal)); -} - -#[test] -fn test_primitive_scalar_null_handling() { - let dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let null_scalar = PrimitiveScalar::try_new(&dtype, None).unwrap(); - - assert_eq!(null_scalar.pvalue(), None); - assert_eq!(null_scalar.typed_value::(), None); -} - -#[test] -fn test_typed_value_correct_type() { - let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); - let value = ScalarValue::Primitive(PValue::F64(3.5)); - let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - - assert_eq!(scalar.typed_value::(), Some(3.5)); + let v1 = ScalarValue::Primitive(PValue::I32(i32::MIN)); + let v2 = ScalarValue::Primitive(PValue::I32(i32::MAX)); + let a = PrimitiveScalar::try_new(&dtype, Some(&v1)).unwrap(); + let b = PrimitiveScalar::try_new(&dtype, Some(&v2)).unwrap(); + let _ = a - b; } #[test] @@ -110,280 +58,173 @@ fn test_typed_value_wrong_type() { let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); let value = ScalarValue::Primitive(PValue::F64(3.5)); let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - let _ = scalar.typed_value::(); } #[rstest] #[case(PType::I8, 127i32, PType::I16, true)] -#[case(PType::I8, 127i32, PType::I32, true)] -#[case(PType::I8, 127i32, PType::I64, true)] -#[case(PType::U8, 255i32, PType::U16, true)] #[case(PType::U8, 255i32, PType::U32, true)] -#[case(PType::I32, 42i32, PType::F32, true)] #[case(PType::I32, 42i32, PType::F64, true)] -// Overflow cases #[case(PType::I32, 300i32, PType::U8, false)] #[case(PType::I32, -1i32, PType::U32, false)] #[case(PType::I32, 256i32, PType::I8, false)] #[case(PType::U16, 65535i32, PType::I8, false)] -fn test_primitive_cast( +fn test_primitive_cast_boundaries( #[case] source_type: PType, #[case] source_value: i32, #[case] target_type: PType, #[case] should_succeed: bool, -) { +) -> VortexResult<()> { let source_pvalue = match source_type { - PType::I8 => PValue::I8(i8::try_from(source_value).vortex_expect("cannot cast")), - PType::U8 => PValue::U8(u8::try_from(source_value).vortex_expect("cannot cast")), - PType::U16 => PValue::U16(u16::try_from(source_value).vortex_expect("cannot cast")), + PType::I8 => PValue::I8(i8::try_from(source_value).vortex_expect("i8")), + PType::U8 => PValue::U8(u8::try_from(source_value).vortex_expect("u8")), + PType::U16 => PValue::U16(u16::try_from(source_value).vortex_expect("u16")), PType::I32 => PValue::I32(source_value), - _ => unreachable!("Test case uses unexpected source type"), + _ => unreachable!(), }; - let dtype = DType::Primitive(source_type, Nullability::NonNullable); let value = ScalarValue::Primitive(source_pvalue); - let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - - let target_dtype = DType::Primitive(target_type, Nullability::NonNullable); - let result = scalar.cast(&target_dtype); - + let scalar = PrimitiveScalar::try_new(&dtype, Some(&value))?; + let target = DType::Primitive(target_type, Nullability::NonNullable); + let result = scalar.cast(&target); if should_succeed { - let casted = result.expect("representable cast should succeed"); - assert_eq!(casted.dtype(), &target_dtype); assert_eq!( - casted.as_primitive().as_::(), + result?.as_primitive().as_::(), Some(f64::from(source_value)) ); } else { - assert!( - result.is_err(), - "Cast from {:?} to {:?} should fail due to overflow", - source_type, - target_type - ); + assert!(result.is_err()); } + Ok(()) } #[test] -fn test_as_conversion_success() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value = ScalarValue::Primitive(PValue::I32(42)); - let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - - assert_eq!(scalar.as_::(), Some(42i64)); - assert_eq!(scalar.as_::(), Some(42.0)); -} - -#[test] -fn test_as_conversion_overflow() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value = ScalarValue::Primitive(PValue::I32(-1)); - let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - - // Converting -1 to u32 should fail - let result = scalar.as_opt::(); - assert!(result.is_none()); -} - -#[test] -fn test_as_conversion_null() { - let dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let scalar = PrimitiveScalar::try_new(&dtype, None).unwrap(); - - assert_eq!(scalar.as_::(), None); - assert_eq!(scalar.as_::(), None); -} - -#[test] -fn test_checked_binary_numeric_add() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(10)); - let value2 = ScalarValue::Primitive(PValue::I32(20)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); +fn test_checked_binary_numeric_int_and_float() -> VortexResult<()> { + let i32_dt = DType::Primitive(PType::I32, Nullability::NonNullable); + let v = |x: i32| ScalarValue::Primitive(PValue::I32(x)); + let (v10, v20, v4, v0, vmax, v1) = (v(10), v(20), v(4), v(0), v(i32::MAX), v(1)); + let s10 = PrimitiveScalar::try_new(&i32_dt, Some(&v10))?; + let s20 = PrimitiveScalar::try_new(&i32_dt, Some(&v20))?; + let s4 = PrimitiveScalar::try_new(&i32_dt, Some(&v4))?; + let s0 = PrimitiveScalar::try_new(&i32_dt, Some(&v0))?; + let smax = PrimitiveScalar::try_new(&i32_dt, Some(&vmax))?; + let s1 = PrimitiveScalar::try_new(&i32_dt, Some(&v1))?; - let result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Add) - .unwrap(); - assert_eq!(result.typed_value::(), Some(30)); -} + assert_eq!( + s10.checked_binary_numeric(&s20, NumericOperator::Add) + .unwrap() + .typed_value::(), + Some(30) + ); + assert_eq!( + s10.checked_binary_numeric(&s4, NumericOperator::Mul) + .unwrap() + .typed_value::(), + Some(40) + ); + assert_eq!( + s20.checked_binary_numeric(&s4, NumericOperator::Div) + .unwrap() + .typed_value::(), + Some(5) + ); + assert!( + smax.checked_binary_numeric(&s1, NumericOperator::Add) + .is_none() + ); + assert!( + s10.checked_binary_numeric(&s0, NumericOperator::Div) + .is_none() + ); -#[test] -fn test_checked_binary_numeric_overflow() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(i32::MAX)); - let value2 = ScalarValue::Primitive(PValue::I32(1)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); + let nullable_dt = DType::Primitive(PType::I32, Nullability::Nullable); + let sn10 = PrimitiveScalar::try_new(&nullable_dt, Some(&v10))?; + let snull = PrimitiveScalar::try_new(&nullable_dt, None)?; + assert_eq!( + sn10.checked_binary_numeric(&snull, NumericOperator::Add) + .unwrap() + .pvalue(), + None + ); - // Add should overflow and return None - let result = scalar1.checked_binary_numeric(&scalar2, NumericOperator::Add); - assert!(result.is_none()); + let f32_dt = DType::Primitive(PType::F32, Nullability::NonNullable); + let (fv1, fv2) = ( + ScalarValue::Primitive(PValue::F32(10.0)), + ScalarValue::Primitive(PValue::F32(2.5)), + ); + let f1 = PrimitiveScalar::try_new(&f32_dt, Some(&fv1))?; + let f2 = PrimitiveScalar::try_new(&f32_dt, Some(&fv2))?; + assert_eq!( + f1.checked_binary_numeric(&f2, NumericOperator::Add) + .unwrap() + .typed_value::(), + Some(12.5) + ); + assert_eq!( + f1.checked_binary_numeric(&f2, NumericOperator::Sub) + .unwrap() + .typed_value::(), + Some(7.5) + ); + assert_eq!( + f1.checked_binary_numeric(&f2, NumericOperator::Mul) + .unwrap() + .typed_value::(), + Some(25.0) + ); + assert_eq!( + f1.checked_binary_numeric(&f2, NumericOperator::Div) + .unwrap() + .typed_value::(), + Some(4.0) + ); + Ok(()) } #[test] -fn test_checked_binary_numeric_with_null() { +fn test_as_and_try_from_pvalue_conversions() -> VortexResult<()> { let dtype = DType::Primitive(PType::I32, Nullability::Nullable); - let value = ScalarValue::Primitive(PValue::I32(10)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - let null_scalar = PrimitiveScalar::try_new(&dtype, None).unwrap(); - - // Operation with null should return null - let result = scalar1 - .checked_binary_numeric(&null_scalar, NumericOperator::Add) - .unwrap(); - assert_eq!(result.pvalue(), None); -} - -#[test] -fn test_checked_binary_numeric_mul() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(5)); - let value2 = ScalarValue::Primitive(PValue::I32(6)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - - let result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Mul) - .unwrap(); - assert_eq!(result.typed_value::(), Some(30)); -} - -#[test] -fn test_checked_binary_numeric_div() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(20)); - let value2 = ScalarValue::Primitive(PValue::I32(4)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - - let result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Div) - .unwrap(); - assert_eq!(result.typed_value::(), Some(5)); -} + let v42 = ScalarValue::Primitive(PValue::I32(42)); + let vneg = ScalarValue::Primitive(PValue::I32(-1)); + let s42 = PrimitiveScalar::try_new(&dtype, Some(&v42))?; + let sneg = PrimitiveScalar::try_new(&dtype, Some(&vneg))?; + let snull = PrimitiveScalar::try_new(&dtype, None)?; + + assert_eq!(s42.as_::(), Some(42)); + assert_eq!(s42.as_::(), Some(42.0)); + assert_eq!(sneg.as_opt::(), None); + assert_eq!(snull.as_::(), None); + assert_eq!(snull.pvalue(), None); -#[test] -fn test_checked_binary_numeric_div_by_zero() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::I32(10)); - let value2 = ScalarValue::Primitive(PValue::I32(0)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - - // Division by zero should return None for integers - let result = scalar1.checked_binary_numeric(&scalar2, NumericOperator::Div); - assert!(result.is_none()); -} - -#[test] -fn test_checked_binary_numeric_float_ops() { - let dtype = DType::Primitive(PType::F32, Nullability::NonNullable); - let value1 = ScalarValue::Primitive(PValue::F32(10.0)); - let value2 = ScalarValue::Primitive(PValue::F32(2.5)); - let scalar1 = PrimitiveScalar::try_new(&dtype, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype, Some(&value2)).unwrap(); - - // Test all operations with floats - let add_result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Add) - .unwrap(); - assert_eq!(add_result.typed_value::(), Some(12.5)); - - let sub_result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Sub) - .unwrap(); - assert_eq!(sub_result.typed_value::(), Some(7.5)); - - let mul_result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Mul) - .unwrap(); - assert_eq!(mul_result.typed_value::(), Some(25.0)); + assert_eq!(PValue::U16(255).as_u8(), Some(255)); + assert_eq!(PValue::U16(256).as_u8(), None); + assert_eq!(PValue::U64(u64::MAX).as_i32(), None); + assert_eq!(PValue::F32(42.5).as_f64(), Some(42.5)); - let div_result = scalar1 - .checked_binary_numeric(&scalar2, NumericOperator::Div) - .unwrap(); - assert_eq!(div_result.typed_value::(), Some(4.0)); -} + assert_eq!(u8::try_from(PValue::I8(42))?, 42); + assert!(u8::try_from(PValue::I8(-1)).is_err()); + assert!(i32::try_from(PValue::F32(42.5)).is_err()); + assert_eq!(f32::try_from(PValue::U8(255))?, 255.0); + assert_eq!(f64::try_from(PValue::I64(-100))?, -100.0); -#[test] -fn test_from_primitive_or_f16() { - // Test f16 to f32 conversion let f16_val = f16::from_f32(3.5); assert_eq!(f32::from_f16(f16_val), Some(3.5)); - - // Test f16 to f64 conversion assert_eq!(f64::from_f16(f16_val), Some(3.5)); - - // Test PValue::F16(f16) to integer conversion (should fail) assert!(i32::try_from(PValue::from(f16_val)).is_err()); - assert!(u32::try_from(PValue::from(f16_val)).is_err()); -} -#[test] -fn test_partial_ord_different_types() { - let dtype1 = DType::Primitive(PType::I32, Nullability::NonNullable); - let dtype2 = DType::Primitive(PType::F32, Nullability::NonNullable); - - let value1 = ScalarValue::Primitive(PValue::I32(10)); - let value2 = ScalarValue::Primitive(PValue::F32(10.0)); - let scalar1 = PrimitiveScalar::try_new(&dtype1, Some(&value1)).unwrap(); - let scalar2 = PrimitiveScalar::try_new(&dtype2, Some(&value2)).unwrap(); - - // Different types should not be comparable - assert_eq!(scalar1.partial_cmp(&scalar2), None); + let from_usize: PValue = usize::MAX.into(); + assert_eq!(from_usize, PValue::U64(usize::MAX as u64)); + assert_eq!(from_usize.ptype(), PType::U64); + assert!(matches!( + ScalarValue::from(42usize), + ScalarValue::Primitive(PValue::U64(42)) + )); + Ok(()) } #[test] -fn test_scalar_value_from_usize() { - let value: ScalarValue = 42usize.into(); - assert!(matches!(value, ScalarValue::Primitive(PValue::U64(42)))); -} - -#[test] -fn test_getters() { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let value = ScalarValue::Primitive(PValue::I32(42)); - let scalar = PrimitiveScalar::try_new(&dtype, Some(&value)).unwrap(); - - assert_eq!(scalar.dtype(), &dtype); - assert_eq!(scalar.ptype(), PType::I32); - assert_eq!(scalar.pvalue(), Some(PValue::I32(42))); -} - -#[test] -pub fn test_is_instance_of() { - assert!(PValue::U8(10).is_instance_of(&PType::U8)); - assert!(!PValue::U8(10).is_instance_of(&PType::U16)); - assert!(!PValue::U8(10).is_instance_of(&PType::I8)); - assert!(!PValue::U8(10).is_instance_of(&PType::F16)); - - assert!(PValue::I8(10).is_instance_of(&PType::I8)); - assert!(!PValue::I8(10).is_instance_of(&PType::I16)); - assert!(!PValue::I8(10).is_instance_of(&PType::U8)); - assert!(!PValue::I8(10).is_instance_of(&PType::F16)); - - assert!(PValue::F16(f16::from_f32(10.0)).is_instance_of(&PType::F16)); - assert!(!PValue::F16(f16::from_f32(10.0)).is_instance_of(&PType::F32)); - assert!(!PValue::F16(f16::from_f32(10.0)).is_instance_of(&PType::U16)); - assert!(!PValue::F16(f16::from_f32(10.0)).is_instance_of(&PType::I16)); -} - -#[test] -fn test_compare_different_types() { - assert_eq!( - PValue::I8(4).partial_cmp(&PValue::I8(5)), - Some(Ordering::Less) - ); - assert_eq!( - PValue::I8(4).partial_cmp(&PValue::I64(5)), - Some(Ordering::Less) - ); -} - -#[test] -fn test_hash() { +fn test_pvalue_cross_type_eq_ord_hash_zero_and_bytes() { + // Cross-width integer equality, ordering, and hashing. let set = HashSet::from([ PValue::U8(1), PValue::U16(1), @@ -399,388 +240,111 @@ fn test_hash() { PValue::I64(-1), ]); assert_eq!(set.len(), 2); -} - -#[test] -fn test_zero_values() { - assert_eq!(PValue::zero(&PType::U8), PValue::U8(0)); - assert_eq!(PValue::zero(&PType::U8).ptype(), PType::U8); - assert_eq!(PValue::zero(&PType::U16), PValue::U16(0)); - assert_eq!(PValue::zero(&PType::U16).ptype(), PType::U16); - assert_eq!(PValue::zero(&PType::U32), PValue::U32(0)); - assert_eq!(PValue::zero(&PType::U32).ptype(), PType::U32); - assert_eq!(PValue::zero(&PType::U64), PValue::U64(0)); - assert_eq!(PValue::zero(&PType::U64).ptype(), PType::U64); - assert_eq!(PValue::zero(&PType::I8), PValue::I8(0)); - assert_eq!(PValue::zero(&PType::I8).ptype(), PType::I8); - assert_eq!(PValue::zero(&PType::I16), PValue::I16(0)); - assert_eq!(PValue::zero(&PType::I16).ptype(), PType::I16); - assert_eq!(PValue::zero(&PType::I32), PValue::I32(0)); - assert_eq!(PValue::zero(&PType::I32).ptype(), PType::I32); - assert_eq!(PValue::zero(&PType::I64), PValue::I64(0)); - assert_eq!(PValue::zero(&PType::I64).ptype(), PType::I64); - assert_eq!(PValue::zero(&PType::F16), PValue::F16(f16::from_f32(0.0))); - assert_eq!(PValue::zero(&PType::F16).ptype(), PType::F16); - assert_eq!(PValue::zero(&PType::F32), PValue::F32(0.0)); - assert_eq!(PValue::zero(&PType::F32).ptype(), PType::F32); - assert_eq!(PValue::zero(&PType::F64), PValue::F64(0.0)); - assert_eq!(PValue::zero(&PType::F64).ptype(), PType::F64); -} - -#[test] -fn test_ptype() { - assert_eq!(PValue::U8(10).ptype(), PType::U8); - assert_eq!(PValue::U16(10).ptype(), PType::U16); - assert_eq!(PValue::U32(10).ptype(), PType::U32); - assert_eq!(PValue::U64(10).ptype(), PType::U64); - assert_eq!(PValue::I8(10).ptype(), PType::I8); - assert_eq!(PValue::I16(10).ptype(), PType::I16); - assert_eq!(PValue::I32(10).ptype(), PType::I32); - assert_eq!(PValue::I64(10).ptype(), PType::I64); - assert_eq!(PValue::F16(f16::from_f32(10.0)).ptype(), PType::F16); - assert_eq!(PValue::F32(10.0).ptype(), PType::F32); - assert_eq!(PValue::F64(10.0).ptype(), PType::F64); -} - -#[test] -fn test_reinterpret_cast_same_type() { - let value = PValue::U32(42); - assert_eq!(value.reinterpret_cast(PType::U32), value); - assert_eq!(value.reinterpret_cast(PType::U32).ptype(), PType::U32); -} - -#[test] -fn test_reinterpret_cast_u8_i8() { - let value = PValue::U8(255); - let casted = value.reinterpret_cast(PType::I8); - assert_eq!(casted, PValue::I8(-1)); - assert_eq!(casted.ptype(), PType::I8); -} - -#[test] -fn test_reinterpret_cast_u16_types() { - let value = PValue::U16(12345); - - // U16 -> I16 - let as_i16 = value.reinterpret_cast(PType::I16); - assert_eq!(as_i16, PValue::I16(12345)); - - // U16 -> F16 - let as_f16 = value.reinterpret_cast(PType::F16); - assert_eq!(as_f16, PValue::F16(f16::from_bits(12345))); - assert_eq!(as_i16.ptype(), PType::I16); - assert_eq!(as_f16.ptype(), PType::F16); -} - -#[test] -fn test_reinterpret_cast_u32_types() { - let value = PValue::U32(0x3f800000); // 1.0 in float bits - - // U32 -> F32 - let as_f32 = value.reinterpret_cast(PType::F32); - assert_eq!(as_f32, PValue::F32(1.0)); - - // U32 -> I32 - let value2 = PValue::U32(0x80000000); - let as_i32 = value2.reinterpret_cast(PType::I32); - assert_eq!(as_i32, PValue::I32(i32::MIN)); - assert_eq!(as_f32.ptype(), PType::F32); - assert_eq!(as_i32.ptype(), PType::I32); -} - -#[test] -fn test_reinterpret_cast_f32_to_u32() { - let value = PValue::F32(1.0); - let as_u32 = value.reinterpret_cast(PType::U32); - assert_eq!(as_u32, PValue::U32(0x3f800000)); - assert_eq!(as_u32.ptype(), PType::U32); -} - -#[test] -fn test_reinterpret_cast_f64_to_i64() { - let value = PValue::F64(1.0); - let as_i64 = value.reinterpret_cast(PType::I64); - assert_eq!(as_i64, PValue::I64(0x3ff0000000000000_i64)); - assert_eq!(as_i64.ptype(), PType::I64); -} - -#[test] -#[should_panic(expected = "Cannot reinterpret cast between types of different widths")] -fn test_reinterpret_cast_different_widths() { - let value = PValue::U8(42); - let _ = value.reinterpret_cast(PType::U16); -} - -#[test] -fn test_as_primitive_conversions() { - // Test as_u8 - assert_eq!(PValue::U8(42).as_u8(), Some(42)); - assert_eq!(PValue::I8(42).as_u8(), Some(42)); - assert_eq!(PValue::U16(255).as_u8(), Some(255)); - assert_eq!(PValue::U16(256).as_u8(), None); // Overflow - - // Test as_i32 - assert_eq!(PValue::I32(42).as_i32(), Some(42)); - assert_eq!(PValue::U32(42).as_i32(), Some(42)); - assert_eq!(PValue::I64(42).as_i32(), Some(42)); - assert_eq!(PValue::U64(u64::MAX).as_i32(), None); // Overflow - - // Test as_f64 - assert_eq!(PValue::F64(42.5).as_f64(), Some(42.5)); - assert_eq!(PValue::F32(42.5).as_f64(), Some(42.5f64)); - assert_eq!(PValue::I32(42).as_f64(), Some(42.0)); -} - -#[test] -fn test_try_from_pvalue_integers() { - // Test u8 conversion - assert_eq!(u8::try_from(PValue::U8(42)).unwrap(), 42); - assert_eq!(u8::try_from(PValue::I8(42)).unwrap(), 42); - assert!(u8::try_from(PValue::I8(-1)).is_err()); - assert!(u8::try_from(PValue::U16(256)).is_err()); - - // Test i32 conversion - assert_eq!(i32::try_from(PValue::I32(42)).unwrap(), 42); - assert_eq!(i32::try_from(PValue::I16(-100)).unwrap(), -100); - assert!(i32::try_from(PValue::U64(u64::MAX)).is_err()); - - // Float to int should fail - assert!(i32::try_from(PValue::F32(42.5)).is_err()); -} - -#[test] -fn test_try_from_pvalue_floats() { - // Test f32 conversion - assert_eq!(f32::try_from(PValue::F32(42.5)).unwrap(), 42.5); - assert_eq!(f32::try_from(PValue::I32(42)).unwrap(), 42.0); - assert_eq!(f32::try_from(PValue::U8(255)).unwrap(), 255.0); - - // Test f64 conversion - assert_eq!(f64::try_from(PValue::F64(42.5)).unwrap(), 42.5); - assert_eq!(f64::try_from(PValue::F32(42.5)).unwrap(), 42.5f64); - assert_eq!(f64::try_from(PValue::I64(-100)).unwrap(), -100.0); -} - -#[test] -fn test_from_usize() { - let value: PValue = 42usize.into(); - assert_eq!(value, PValue::U64(42)); - assert_eq!(value.ptype(), PType::U64); - - let max_value: PValue = usize::MAX.into(); - assert_eq!(max_value, PValue::U64(usize::MAX as u64)); - assert_eq!(max_value.ptype(), PType::U64); -} - -#[test] -fn test_equality_cross_types() { - // Same numeric value, different types - assert_eq!(PValue::U8(42), PValue::U16(42)); - assert_eq!(PValue::U8(42), PValue::U32(42)); - assert_eq!(PValue::U8(42), PValue::U64(42)); - assert_eq!(PValue::I8(42), PValue::I16(42)); - assert_eq!(PValue::I8(42), PValue::I32(42)); - assert_eq!(PValue::I8(42), PValue::I64(42)); - - // Unsigned vs signed with same value (they compare equal even though different categories) - assert_eq!(PValue::U8(42), PValue::I8(42)); - assert_eq!(PValue::U32(42), PValue::I32(42)); - - // Float equality - assert_eq!(PValue::F32(42.0), PValue::F32(42.0)); - assert_eq!(PValue::F64(42.0), PValue::F64(42.0)); - assert_ne!(PValue::F32(42.0), PValue::F64(42.0)); // Different types - - // Float vs int should not be equal - assert_ne!(PValue::F32(42.0), PValue::I32(42)); -} - -#[test] -fn test_partial_ord_cross_types() { - // Unsigned comparisons - assert_eq!( - PValue::U8(10).partial_cmp(&PValue::U16(20)), - Some(Ordering::Less) - ); - assert_eq!( - PValue::U32(30).partial_cmp(&PValue::U8(20)), - Some(Ordering::Greater) - ); - - // Signed comparisons assert_eq!( PValue::I8(-10).partial_cmp(&PValue::I64(0)), Some(Ordering::Less) ); - assert_eq!( - PValue::I32(10).partial_cmp(&PValue::I16(10)), - Some(Ordering::Equal) - ); - - // Float comparisons (same type only) - assert_eq!( - PValue::F32(1.0).partial_cmp(&PValue::F32(2.0)), - Some(Ordering::Less) - ); - assert_eq!( - PValue::F64(2.0).partial_cmp(&PValue::F64(1.0)), - Some(Ordering::Greater) - ); - - // Cross-category comparisons - unsigned vs signed work, float vs int don't assert_eq!( PValue::U32(42).partial_cmp(&PValue::I32(42)), Some(Ordering::Equal) - ); // Actually works + ); + assert_ne!(PValue::F32(42.0), PValue::F64(42.0)); + assert_ne!(PValue::F32(42.0), PValue::I32(42)); assert_eq!(PValue::F32(42.0).partial_cmp(&PValue::I32(42)), None); assert_eq!(PValue::F32(42.0).partial_cmp(&PValue::F64(42.0)), None); -} -#[test] -fn test_to_le_bytes() { + // Zero values and is_instance_of across all PTypes. + for ptype in [ + PType::U8, + PType::U16, + PType::U32, + PType::U64, + PType::I8, + PType::I16, + PType::I32, + PType::I64, + PType::F16, + PType::F32, + PType::F64, + ] { + let z = PValue::zero(&ptype); + assert_eq!(z.ptype(), ptype); + assert!(z.is_instance_of(&ptype)); + } + assert!(!PValue::U8(10).is_instance_of(&PType::U16)); + assert!(!PValue::F16(f16::ONE).is_instance_of(&PType::F32)); + + // Little-endian bytes. assert_eq!(PValue::U8(0x12).to_le_bytes(), &[0x12]); assert_eq!(PValue::U16(0x1234).to_le_bytes(), &[0x34, 0x12]); assert_eq!( PValue::U32(0x12345678).to_le_bytes(), &[0x78, 0x56, 0x34, 0x12] ); - assert_eq!(PValue::I8(-1).to_le_bytes(), &[0xFF]); - assert_eq!(PValue::I16(-1).to_le_bytes(), &[0xFF, 0xFF]); - - let f32_bytes = PValue::F32(1.0).to_le_bytes(); - assert_eq!(f32_bytes, &[0x00, 0x00, 0x80, 0x3f]); - - let f64_bytes = PValue::F64(1.0).to_le_bytes(); - assert_eq!(f64_bytes, &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]); -} - -#[test] -fn test_f16_special_values() { - // Test F16 NaN handling - let nan = f16::NAN; - let nan_value = PValue::F16(nan); - assert!(nan_value.as_f16().unwrap().is_nan()); - - // Test F16 infinity - let inf = f16::INFINITY; - let inf_value = PValue::F16(inf); - assert!(inf_value.as_f16().unwrap().is_infinite()); - - // Test F16 comparison with NaN + assert_eq!(PValue::F32(1.0).to_le_bytes(), &[0x00, 0x00, 0x80, 0x3f]); assert_eq!( - PValue::F16(nan).partial_cmp(&PValue::F16(nan)), - Some(Ordering::Equal) + PValue::F64(1.0).to_le_bytes(), + &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f] ); -} - -#[test] -fn test_coerce_pvalue() { - // Test integer coercion - assert_eq!(u32::coerce(PValue::U16(42)).unwrap(), 42u32); - assert_eq!(i64::coerce(PValue::I32(-42)).unwrap(), -42i64); - // Test float coercion from bits - assert_eq!(f32::coerce(PValue::U32(0x3f800000)).unwrap(), 1.0f32); + // f16 NaN bit preservation & total ordering equality. + let nan = f16::from_le_bytes([154, 253]); + assert!(nan.is_nan()); + assert_eq!(f16::from_f16(nan).unwrap().to_bits(), nan.to_bits()); assert_eq!( - f64::coerce(PValue::U64(0x3ff0000000000000)).unwrap(), - 1.0f64 + PValue::F16(f16::NAN).partial_cmp(&PValue::F16(f16::NAN)), + Some(Ordering::Equal) ); } -#[test] -fn test_coerce_f16_beyond_u16_max() { - // Test U32 to f16 coercion within valid range - assert_eq!( - f16::coerce(PValue::U32(u16::MAX as u32)).unwrap().to_bits(), - u16::MAX - ); - assert_eq!( - f16::coerce(PValue::U32(0x3C00)).unwrap(), - f16::from_bits(0x3C00) // 1.0 in f16 - ); - - // Test U32 to f16 coercion beyond u16::MAX - should fail - assert!(f16::coerce(PValue::U32((u16::MAX as u32) + 1)).is_err()); - assert!(f16::coerce(PValue::U32(u32::MAX)).is_err()); - - // Test U64 to f16 coercion within valid range - assert_eq!( - f16::coerce(PValue::U64(u16::MAX as u64)).unwrap().to_bits(), - u16::MAX - ); - assert_eq!( - f16::coerce(PValue::U64(0x3C00)).unwrap(), - f16::from_bits(0x3C00) // 1.0 in f16 - ); - - // Test U64 to f16 coercion beyond u16::MAX - should fail - assert!(f16::coerce(PValue::U64((u16::MAX as u64) + 1)).is_err()); - assert!(f16::coerce(PValue::U64(u32::MAX as u64)).is_err()); - assert!(f16::coerce(PValue::U64(u64::MAX)).is_err()); +#[rstest] +#[case::same(PValue::U32(42), PType::U32, PValue::U32(42))] +#[case::u8_to_i8(PValue::U8(255), PType::I8, PValue::I8(-1))] +#[case::u16_to_i16(PValue::U16(12345), PType::I16, PValue::I16(12345))] +#[case::u16_to_f16(PValue::U16(12345), PType::F16, PValue::F16(f16::from_bits(12345)))] +#[case::u32_to_f32(PValue::U32(0x3f80_0000), PType::F32, PValue::F32(1.0))] +#[case::u32_to_i32(PValue::U32(0x8000_0000), PType::I32, PValue::I32(i32::MIN))] +#[case::f32_to_u32(PValue::F32(1.0), PType::U32, PValue::U32(0x3f80_0000))] +#[case::f64_to_i64(PValue::F64(1.0), PType::I64, PValue::I64(0x3ff0_0000_0000_0000))] +fn test_reinterpret_cast(#[case] src: PValue, #[case] target: PType, #[case] expected: PValue) { + let casted = src.reinterpret_cast(target); + assert_eq!(casted, expected); + assert_eq!(casted.ptype(), target); } #[test] -fn test_coerce_f32_beyond_u32_max() { - // Test U64 to f32 coercion within valid range - assert_eq!( - f32::coerce(PValue::U64(u32::MAX as u64)).unwrap().to_bits(), - u32::MAX - ); - assert_eq!( - f32::coerce(PValue::U64(0x3f800000)).unwrap(), - 1.0f32 // 0x3f800000 is 1.0 in f32 - ); - - // Test U64 to f32 coercion beyond u32::MAX - should fail - assert!(f32::coerce(PValue::U64((u32::MAX as u64) + 1)).is_err()); - assert!(f32::coerce(PValue::U64(u64::MAX)).is_err()); - - // Test smaller types still work - assert_eq!(f32::coerce(PValue::U8(255)).unwrap().to_bits(), 255u32); - assert_eq!( - f32::coerce(PValue::U16(u16::MAX)).unwrap().to_bits(), - u16::MAX as u32 - ); - assert_eq!( - f32::coerce(PValue::U32(u32::MAX)).unwrap().to_bits(), - u32::MAX - ); +#[should_panic(expected = "Cannot reinterpret cast between types of different widths")] +fn test_reinterpret_cast_different_widths() { + let _ = PValue::U8(42).reinterpret_cast(PType::U16); } #[test] -fn test_coerce_f64_all_unsigned() { - // Test f64 can accept all unsigned integer values as bit patterns - assert_eq!( - f64::coerce(PValue::U8(u8::MAX)).unwrap().to_bits(), - u8::MAX as u64 - ); - assert_eq!( - f64::coerce(PValue::U16(u16::MAX)).unwrap().to_bits(), - u16::MAX as u64 - ); - assert_eq!( - f64::coerce(PValue::U32(u32::MAX)).unwrap().to_bits(), - u32::MAX as u64 - ); +fn test_coerce_pvalue_and_bounds() -> VortexResult<()> { + assert_eq!(u32::coerce(PValue::U16(42))?, 42u32); + assert_eq!(i64::coerce(PValue::I32(-42))?, -42i64); + + // f16 bit coercion bounds. assert_eq!( - f64::coerce(PValue::U64(u64::MAX)).unwrap().to_bits(), - u64::MAX + f16::coerce(PValue::U32(u32::from(u16::MAX)))?.to_bits(), + u16::MAX ); + assert_eq!(f16::coerce(PValue::U64(0x3C00))?, f16::from_bits(0x3C00)); + assert!(f16::coerce(PValue::U32(u32::from(u16::MAX) + 1)).is_err()); + assert!(f16::coerce(PValue::U64(u64::from(u16::MAX) + 1)).is_err()); - // Verify specific bit patterns + // f32 bit coercion bounds. + assert_eq!(f32::coerce(PValue::U32(0x3f80_0000))?, 1.0f32); assert_eq!( - f64::coerce(PValue::U64(0x3ff0000000000000)).unwrap(), - 1.0f64 // 0x3ff0000000000000 is 1.0 in f64 + f32::coerce(PValue::U64(u64::from(u32::MAX)))?.to_bits(), + u32::MAX ); -} + assert!(f32::coerce(PValue::U64(u64::from(u32::MAX) + 1)).is_err()); -#[test] -fn test_f16_nans_equal() { - let nan1 = f16::from_le_bytes([154, 253]); - assert!(nan1.is_nan()); - let nan3 = f16::from_f16(nan1).unwrap(); - assert_eq!(nan1.to_bits(), nan3.to_bits(),); + // f64 accepts all unsigned widths as bit patterns. + assert_eq!(f64::coerce(PValue::U64(0x3ff0_0000_0000_0000))?, 1.0f64); + assert_eq!(f64::coerce(PValue::U64(u64::MAX))?.to_bits(), u64::MAX); + Ok(()) } #[rstest] diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index c1903b9f1a4..b9c59781610 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -13,6 +13,7 @@ use itertools::Itertools; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_error::vortex_panic; @@ -198,9 +199,15 @@ impl<'a> StructScalar<'a> { /// Casts this struct scalar to another struct type. /// + /// When the source and target have identical field names in the same order, fields are cast + /// positionally. Otherwise, fields are matched by name (reordering, dropping extra source + /// fields, and filling missing nullable target fields with null), matching `StructArray` cast + /// semantics. + /// /// # Errors /// - /// Returns an error if the target type is not a struct or if the number of fields don't match. + /// Returns an error if the target type is not a struct, if an added target field is + /// non-nullable, or if any matched field cast fails. pub fn cast(&self, dtype: &DType) -> VortexResult { let DType::Struct(st, _) = dtype else { vortex_bail!( @@ -210,17 +217,12 @@ impl<'a> StructScalar<'a> { }; let own_st = self.struct_fields(); - if st.fields().len() != own_st.fields().len() { - vortex_bail!( - "Cannot cast between structs with different number of fields: {} and {}", - own_st.fields().len(), - st.fields().len() - ); - } + let Some(fs) = self.fields else { + return Scalar::try_new(dtype.clone(), None); + }; - if let Some(fs) = self.fields { - let fields = fs - .iter() + let fields = if own_st.names() == st.names() { + fs.iter() .enumerate() .map(|(i, f)| { Scalar::try_new( @@ -235,11 +237,33 @@ impl<'a> StructScalar<'a> { ) .map(|s| s.into_value()) }) - .collect::>>()?; - Scalar::try_new(dtype.clone(), Some(ScalarValue::Tuple(fields))) + .collect::>>()? } else { - Ok(Scalar::null(dtype.clone())) - } + st.names() + .iter() + .zip(st.fields()) + .map( + |(target_name, target_dtype)| match own_st.find(target_name) { + None => { + vortex_ensure!( + target_dtype.is_nullable(), + "CAST for struct only supports added nullable fields" + ); + Ok(None) + } + Some(src_idx) => Scalar::try_new( + own_st + .field_by_index(src_idx) + .vortex_expect("valid source field index"), + fs[src_idx].clone(), + )? + .cast(&target_dtype) + .map(|s| s.into_value()), + }, + ) + .collect::>>()? + }; + Scalar::try_new(dtype.clone(), Some(ScalarValue::Tuple(fields))) } /// Projects this struct scalar to include only the specified fields. @@ -330,404 +354,234 @@ impl Scalar { #[cfg(test)] mod tests { - use std::collections::hash_map::DefaultHasher; - use std::hash::Hash; - use std::hash::Hasher; + use vortex_error::VortexResult; + use vortex_session::VortexSession; use super::*; + use crate::IntoArray; + use crate::VortexSessionExecute; + use crate::arrays::ConstantArray; + use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::Nullability; - use crate::dtype::PType::I32; + use crate::dtype::PType; use crate::dtype::StructFields; use crate::scalar::PValue; fn setup_types() -> (DType, DType, DType) { - let f0_dt = DType::Primitive(I32, Nullability::NonNullable); + let f0_dt = DType::Primitive(PType::I32, Nullability::NonNullable); let f1_dt = DType::Utf8(Nullability::NonNullable); - let dtype = DType::Struct( StructFields::new(["a", "b"].into(), vec![f0_dt.clone(), f1_dt.clone()]), Nullability::Nullable, ); - (f0_dt, f1_dt, dtype) } #[test] #[should_panic(expected = "Can't take field out of null struct scalar")] - fn test_struct_scalar_null() { + fn test_struct_scalar_null_field_access_panics() { let (_, _, dtype) = setup_types(); - - let scalar = Scalar::null(dtype); - - drop(scalar.as_struct().field_by_idx(0)); - } - - #[test] - fn test_struct_scalar_non_null() { - let (f0_dt, f1_dt, dtype) = setup_types(); - - let f0_val = Scalar::primitive::(1, Nullability::NonNullable); - let f1_val = Scalar::utf8("hello", Nullability::NonNullable); - - let f0_val_null = Scalar::primitive::(1, Nullability::Nullable); - let f1_val_null = Scalar::utf8("hello", Nullability::Nullable); - - let scalar = Scalar::struct_(dtype, vec![f0_val, f1_val]); - - let scalar_f0 = scalar.as_struct().field_by_idx(0); - assert!(scalar_f0.is_some()); - let scalar_f0 = scalar_f0.unwrap(); - assert_eq!(scalar_f0.value(), f0_val_null.value()); - assert_eq!(scalar_f0.dtype(), &f0_dt); - - let scalar_f1 = scalar.as_struct().field_by_idx(1); - assert!(scalar_f1.is_some()); - let scalar_f1 = scalar_f1.unwrap(); - assert_eq!(scalar_f1.value(), f1_val_null.value()); - assert_eq!(scalar_f1.dtype(), &f1_dt); + drop(Scalar::null(dtype).as_struct().field_by_idx(0)); } #[test] #[should_panic(expected = "Expected struct dtype")] fn test_struct_scalar_wrong_dtype() { - let dtype = DType::Primitive(I32, Nullability::NonNullable); - let scalar = Scalar::primitive::(1, Nullability::NonNullable); - - Scalar::struct_(dtype, vec![scalar]); + Scalar::struct_( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::primitive::(1, Nullability::NonNullable)], + ); } #[test] #[should_panic(expected = "Struct has 2 fields but 1 children were provided")] fn test_struct_scalar_wrong_child_count() { let (_, _, dtype) = setup_types(); - let f0_val = Scalar::primitive::(1, Nullability::NonNullable); - - Scalar::struct_(dtype, vec![f0_val]); + Scalar::struct_( + dtype, + vec![Scalar::primitive::(1, Nullability::NonNullable)], + ); } #[test] #[should_panic(expected = "Field 0 expected dtype i32 but got utf8")] fn test_struct_scalar_wrong_child_dtype() { let (_, _, dtype) = setup_types(); - let f0_val = Scalar::utf8("wrong", Nullability::NonNullable); - let f1_val = Scalar::utf8("hello", Nullability::NonNullable); - - Scalar::struct_(dtype, vec![f0_val, f1_val]); - } - - #[test] - fn test_struct_field_by_name() { - let (_, _, dtype) = setup_types(); - let f0_val = Scalar::primitive::(42, Nullability::NonNullable); - let f1_val = Scalar::utf8("world", Nullability::NonNullable); - - let scalar = Scalar::struct_(dtype, vec![f0_val, f1_val]); - - // Get field by name - let field_a = scalar.as_struct().field("a"); - assert!(field_a.is_some()); - assert_eq!( - field_a - .unwrap() - .as_primitive() - .typed_value::() - .unwrap(), - 42 - ); - - let field_b = scalar.as_struct().field("b"); - assert!(field_b.is_some()); - assert_eq!( - field_b.unwrap().as_utf8().value().cloned().unwrap(), - "world".into() - ); - - // Non-existent field - let field_c = scalar.as_struct().field("c"); - assert!(field_c.is_none()); - } - - #[test] - fn test_struct_fields() { - let (_, _, dtype) = setup_types(); - let f0_val = Scalar::primitive::(100, Nullability::NonNullable); - let f1_val = Scalar::utf8("test", Nullability::NonNullable); - - let scalar = Scalar::struct_(dtype, vec![f0_val, f1_val]); - - let fields = scalar - .as_struct() - .fields_iter() - .unwrap() - .collect::>(); - assert_eq!(fields.len(), 2); - assert_eq!(fields[0].as_primitive().typed_value::().unwrap(), 100); - assert_eq!(fields[1].as_utf8().value().cloned().unwrap(), "test".into()); - } - - #[test] - fn test_struct_null_fields() { - let (_, _, dtype) = setup_types(); - let null_scalar = Scalar::null(dtype); - - assert!(null_scalar.as_struct().is_null()); - assert!(null_scalar.as_struct().fields_iter().is_none()); - } - - #[test] - fn test_struct_cast_to_struct() { - // Create source struct - let source_fields = StructFields::new( - ["x", "y"].into(), - vec![ - DType::Primitive(I32, Nullability::NonNullable), - DType::Primitive(I32, Nullability::NonNullable), - ], - ); - let source_dtype = DType::Struct(source_fields, Nullability::NonNullable); - - // Create target struct with different field types - let target_fields = StructFields::new( - ["x", "y"].into(), + Scalar::struct_( + dtype, vec![ - DType::Primitive(crate::dtype::PType::I64, Nullability::NonNullable), - DType::Primitive(crate::dtype::PType::I64, Nullability::NonNullable), + Scalar::utf8("wrong", Nullability::NonNullable), + Scalar::utf8("hello", Nullability::NonNullable), ], ); - let target_dtype = DType::Struct(target_fields, Nullability::NonNullable); - - let f0 = Scalar::primitive::(42, Nullability::NonNullable); - let f1 = Scalar::primitive::(123, Nullability::NonNullable); - let source_scalar = Scalar::struct_(source_dtype, vec![f0, f1]); - - // Cast to target type - let result = source_scalar.as_struct().cast(&target_dtype).unwrap(); - assert_eq!(result.dtype(), &target_dtype); - - let fields = result - .as_struct() - .fields_iter() - .unwrap() - .collect::>(); - assert_eq!(fields[0].as_primitive().typed_value::().unwrap(), 42); - assert_eq!(fields[1].as_primitive().typed_value::().unwrap(), 123); } #[test] - fn test_struct_cast_mismatched_fields() { - let source_fields = StructFields::new( - ["a"].into(), - vec![DType::Primitive(I32, Nullability::NonNullable)], - ); - let source_dtype = DType::Struct(source_fields, Nullability::NonNullable); - - let target_fields = StructFields::new( - ["a", "b"].into(), + fn test_struct_accessors_project_and_errors() -> VortexResult<()> { + let (f0_dt, f1_dt, dtype) = setup_types(); + let scalar = Scalar::struct_( + dtype.clone(), vec![ - DType::Primitive(I32, Nullability::NonNullable), - DType::Primitive(I32, Nullability::NonNullable), + Scalar::primitive::(42, Nullability::NonNullable), + Scalar::utf8("hello", Nullability::NonNullable), ], ); - let target_dtype = DType::Struct(target_fields, Nullability::NonNullable); - let scalar = Scalar::struct_( - source_dtype, - vec![Scalar::primitive::(1, Nullability::NonNullable)], + let s = scalar.as_struct(); + assert_eq!(s.field_by_idx(0).unwrap().dtype(), &f0_dt); + assert_eq!(s.field_by_idx(1).unwrap().dtype(), &f1_dt); + assert!(s.field_by_idx(10).is_none()); + assert_eq!( + s.field("a").unwrap().as_primitive().typed_value::(), + Some(42) ); - - let result = scalar.as_struct().cast(&target_dtype); - assert!(result.is_err()); - } - - #[test] - fn test_struct_cast_to_non_struct() { - let (_, _, dtype) = setup_types(); - let scalar = Scalar::struct_( - dtype, - vec![ - Scalar::primitive::(1, Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), - ], + assert_eq!( + s.field("b").unwrap().as_utf8().value().unwrap().as_str(), + "hello" ); + assert!(s.field("c").is_none()); + assert_eq!(s.fields_iter().unwrap().len(), 2); - let result = scalar - .as_struct() - .cast(&DType::Primitive(I32, Nullability::NonNullable)); - assert!(result.is_err()); - } - - #[test] - fn test_struct_project() { - let (_, _, dtype) = setup_types(); - let f0_val = Scalar::primitive::(42, Nullability::NonNullable); - let f1_val = Scalar::utf8("hello", Nullability::NonNullable); - - let scalar = Scalar::struct_(dtype, vec![f0_val, f1_val]); - - // Project to only field "b" - let projected = scalar.as_struct().project(&["b".into()]).unwrap(); - let projected_struct = projected.as_struct(); - - assert_eq!(projected_struct.names().len(), 1); - assert_eq!(projected_struct.names()[0].as_ref(), "b"); - - let fields = projected_struct.fields_iter().unwrap().collect::>(); - assert_eq!(fields.len(), 1); - assert_eq!(fields[0].as_utf8().value().unwrap().as_str(), "hello"); - } + // Project non-null and null structs. + let projected = s.project(&["b".into()])?; + assert_eq!(projected.as_struct().names().len(), 1); + assert_eq!( + projected + .as_struct() + .field("b") + .unwrap() + .as_utf8() + .value() + .unwrap() + .as_str(), + "hello" + ); - #[test] - fn test_struct_project_null() { - let (_, _, dtype) = setup_types(); let null_scalar = Scalar::null(dtype); - - let projected = null_scalar.as_struct().project(&["a".into()]).unwrap(); - assert!(projected.as_struct().is_null()); + assert!(null_scalar.as_struct().is_null()); + assert!(null_scalar.as_struct().fields_iter().is_none()); + let null_projected = null_scalar.as_struct().project(&["a".into()])?; + assert!(null_projected.is_null()); assert_eq!( - projected.dtype(), + null_projected.dtype(), &DType::struct_( - [("a", DType::Primitive(I32, Nullability::NonNullable))], + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], Nullability::Nullable, ) ); - } - #[test] - fn test_struct_equality() { - let (_, _, dtype) = setup_types(); - - let scalar1 = Scalar::struct_( - dtype.clone(), - vec![ - Scalar::primitive::(1, Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), - ], - ); - - let scalar2 = Scalar::struct_( - dtype.clone(), - vec![ - Scalar::primitive::(1, Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), - ], + // Non-struct dtype rejections. + let non_struct = DType::Primitive(PType::I32, Nullability::NonNullable); + assert!( + StructScalar::try_new(&non_struct, Some(&ScalarValue::Primitive(PValue::I32(42)))) + .is_err() ); + assert!(scalar.as_struct().cast(&non_struct).is_err()); - let scalar3 = Scalar::struct_( - dtype, - vec![ - Scalar::primitive::(2, Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), - ], + // Different struct schemas are incomparable via PartialOrd. + let other = Scalar::struct_( + DType::struct_( + [("c", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + ), + vec![Scalar::from(1i32)], ); - - assert_eq!(scalar1.as_struct(), scalar2.as_struct()); - assert_ne!(scalar1.as_struct(), scalar3.as_struct()); - - let mut hasher1 = DefaultHasher::new(); - scalar1.as_struct().hash(&mut hasher1); - let mut hasher2 = DefaultHasher::new(); - scalar2.as_struct().hash(&mut hasher2); - assert_eq!(hasher1.finish(), hasher2.finish()); + assert_eq!(scalar.as_struct().partial_cmp(&other.as_struct()), None); + Ok(()) } #[test] - fn test_struct_hash_ignores_nested_nullability() { - let nullable_dtype = DType::Struct( - StructFields::new( - ["value"].into(), - vec![DType::Primitive(I32, Nullability::Nullable)], - ), + fn test_struct_cast_schema_evolution_matches_struct_array() -> VortexResult<()> { + let src_dtype = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I64, Nullability::NonNullable)), + ], Nullability::NonNullable, ); - let non_nullable_dtype = DType::Struct( - StructFields::new( - ["value"].into(), - vec![DType::Primitive(I32, Nullability::NonNullable)], - ), + let src = Scalar::struct_(src_dtype, vec![Scalar::from(1i32), Scalar::from(2i64)]); + + // Reordering fields must match by name (not positionally swap values). + let reordered_dtype = DType::struct_( + [ + ("b", DType::Primitive(PType::I64, Nullability::NonNullable)), + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ], Nullability::NonNullable, ); - let nullable = Scalar::struct_( - nullable_dtype, - [Scalar::primitive(42_i32, Nullability::Nullable)], - ); - let non_nullable = Scalar::struct_( - non_nullable_dtype, - [Scalar::primitive(42_i32, Nullability::NonNullable)], + let reordered = src.cast(&reordered_dtype)?; + assert_eq!( + reordered + .as_struct() + .field("b") + .unwrap() + .as_primitive() + .typed_value::(), + Some(2) ); - let nullable = nullable.as_struct(); - let non_nullable = non_nullable.as_struct(); - - assert_eq!(nullable, non_nullable); - - let mut nullable_hasher = DefaultHasher::new(); - nullable.hash(&mut nullable_hasher); - let mut non_nullable_hasher = DefaultHasher::new(); - non_nullable.hash(&mut non_nullable_hasher); - assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); - } - - #[test] - fn test_struct_partial_ord() { - let (_, _, dtype) = setup_types(); - - let scalar1 = Scalar::struct_( - dtype.clone(), - vec![ - Scalar::primitive::(1, Nullability::NonNullable), - Scalar::utf8("a", Nullability::NonNullable), - ], + assert_eq!( + reordered + .as_struct() + .field("a") + .unwrap() + .as_primitive() + .typed_value::(), + Some(1) ); - let scalar2 = Scalar::struct_( - dtype, - vec![ - Scalar::primitive::(2, Nullability::NonNullable), - Scalar::utf8("b", Nullability::NonNullable), + // Verify ConstantArray::cast matches Canonical StructArray::cast on reordered fields. + let session = VortexSession::empty(); + let mut ctx = session.create_execution_ctx(); + let const_casted = ConstantArray::new(src.clone(), 1) + .into_array() + .cast(reordered_dtype.clone())? + .execute_scalar(0, &mut ctx)?; + let struct_casted = ConstantArray::new(src.clone(), 1) + .into_array() + .execute::(&mut ctx)? + .into_array() + .cast(reordered_dtype)? + .execute_scalar(0, &mut ctx)?; + assert_eq!(const_casted, reordered); + assert_eq!(struct_casted, reordered); + + // Dropping a field and adding a nullable field fills the added field with null. + let evolved_dtype = DType::struct_( + [ + ("a", DType::Primitive(PType::I64, Nullability::NonNullable)), + ("c", DType::Primitive(PType::I32, Nullability::Nullable)), ], - ); - - // Structs with same dtype can be compared - assert!(scalar1.as_struct() < scalar2.as_struct()); - - // Different struct types cannot be compared - let other_dtype = DType::Struct( - StructFields::new( - ["c"].into(), - vec![DType::Primitive(I32, Nullability::NonNullable)], - ), Nullability::NonNullable, ); - let scalar3 = Scalar::struct_( - other_dtype, - vec![Scalar::primitive::(1, Nullability::NonNullable)], + let evolved = src.cast(&evolved_dtype)?; + assert_eq!( + evolved + .as_struct() + .field("a") + .unwrap() + .as_primitive() + .typed_value::(), + Some(1) ); + assert!(evolved.as_struct().field("c").unwrap().is_null()); - assert_eq!(scalar1.as_struct().partial_cmp(&scalar3.as_struct()), None); - } - - #[test] - fn test_struct_try_new_non_struct_dtype() { - let dtype = DType::Primitive(I32, Nullability::NonNullable); - let value = ScalarValue::Primitive(PValue::I32(42)); - - let result = StructScalar::try_new(&dtype, Some(&value)); - assert!(result.is_err()); - } - - #[test] - fn test_struct_field_out_of_bounds() { - let (_, _, dtype) = setup_types(); - let scalar = Scalar::struct_( - dtype, - vec![ - Scalar::primitive::(1, Nullability::NonNullable), - Scalar::utf8("test", Nullability::NonNullable), + // Adding a non-nullable field is rejected. + let added_nonnull = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("c", DType::Primitive(PType::I32, Nullability::NonNullable)), ], + Nullability::NonNullable, ); + assert!(src.cast(&added_nonnull).is_err()); - // Try to access field beyond bounds - let field = scalar.as_struct().field_by_idx(10); - assert!(field.is_none()); + // Direct StructScalar::cast on null to non-nullable struct returns Err instead of panicking. + let null_struct = Scalar::null(DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::Nullable, + )); + assert!(null_struct.as_struct().cast(&added_nonnull).is_err()); + Ok(()) } } From 069c99c1f2616a24992fdc17d44ada968a22337c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 19:56:50 +0000 Subject: [PATCH 2/9] Validate null struct scalar casts and restore review test coverage Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../fns/all_non_distinct/tests.rs | 87 ++++++- vortex-array/src/scalar/cast.rs | 7 + vortex-array/src/scalar/tests/casting.rs | 31 ++- vortex-array/src/scalar/tests/hegel.rs | 235 +++++++++++++++--- vortex-array/src/scalar/tests/nested.rs | 118 +++++++++ .../src/scalar/typed_view/decimal/tests.rs | 66 ++++- .../src/scalar/typed_view/extension/tests.rs | 49 ++++ vortex-array/src/scalar/typed_view/list.rs | 72 ++++++ .../src/scalar/typed_view/primitive/tests.rs | 37 +-- vortex-array/src/scalar/typed_view/struct_.rs | 149 ++++++++++- 10 files changed, 778 insertions(+), 73 deletions(-) diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs index f00d95c1c23..e2c5ca243b3 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs @@ -202,7 +202,7 @@ fn hegel_nullable_garbage_under_nulls_ignored(tc: TestCase) { (a, b) }; - let [a, b]: [ArrayRef; 2] = match tc.draw(gs::integers::().max_value(4)) { + let [a, b]: [ArrayRef; 2] = match tc.draw(gs::integers::().max_value(5)) { 0 => { let (va, vb) = draw_i32_pair(1); [va, vb].map(|v| PrimitiveArray::new(Buffer::from(v), validity.clone()).into_array()) @@ -237,7 +237,7 @@ fn hegel_nullable_garbage_under_nulls_ignored(tc: TestCase) { .into_array() }) } - _ => { + 4 => { let (va, vb) = draw_i32_pair(2); [va, vb].map(|v| { FixedSizeListArray::try_new( @@ -250,6 +250,42 @@ fn hegel_nullable_garbage_under_nulls_ignored(tc: TestCase) { .into_array() }) } + _ => { + let (va, vb) = draw_i32_pair(2); + let offsets_a: Vec = (0..len) + .map(|i| u32::try_from(i * 2).vortex_expect("small len")) + .collect(); + let sizes_a: Vec = vec![2; len]; + // Null rows can also carry different offsets/sizes pointing to garbage elements. + let mut offsets_b = offsets_a.clone(); + let mut sizes_b = sizes_a.clone(); + for (i, &v) in valid.iter().enumerate() { + if !v { + offsets_b[i] = 0; + sizes_b[i] = tc.draw(gs::integers::().max_value(2)); + } + } + [ + ListViewArray::try_new( + PrimitiveArray::from_iter(va).into_array(), + PrimitiveArray::from_iter(offsets_a).into_array(), + PrimitiveArray::from_iter(sizes_a).into_array(), + validity.clone(), + &mut ctx, + ) + .vortex_expect("listview a") + .into_array(), + ListViewArray::try_new( + PrimitiveArray::from_iter(vb).into_array(), + PrimitiveArray::from_iter(offsets_b).into_array(), + PrimitiveArray::from_iter(sizes_b).into_array(), + validity, + &mut ctx, + ) + .vortex_expect("listview b") + .into_array(), + ] + } }; assert!(all_non_distinct(&a, &b, &mut ctx).vortex_expect("all_non_distinct")); @@ -542,3 +578,50 @@ fn variant_reordered_fields_repeated_names_map_and_ext_storage() -> VortexResult Scalar::extension_ref(ext_dt, rhs_ne), ) } + +#[test] +fn list_different_lengths_same_flattened_elements() -> VortexResult<()> { + // Equal flattened elements [1, 2, 3] partitioned differently across rows on the non-zero-copy + // ListView path (out-of-order / overlapping offsets): [[1, 2], [3]] vs [[1], [2, 3]]. + let mut ctx = SESSION.create_execution_ctx(); + let elems = buffer![1i32, 2, 3].into_array(); + let lhs = ListViewArray::try_new( + elems.clone(), + buffer![0u32, 2].into_array(), + buffer![2u32, 1].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let rhs = ListViewArray::try_new( + elems.clone(), + buffer![0u32, 1].into_array(), + buffer![1u32, 2].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + assert!(!all_non_distinct(&lhs, &rhs, &mut ctx)?); + assert_matches_baseline(&lhs, &rhs)?; + + // Non-zero-copy out-of-order offsets sharing the same backing elements: [[3], [1, 2]] vs [[2, 3], [1]]. + let ooo_lhs = ListViewArray::try_new( + elems.clone(), + buffer![2u32, 0].into_array(), + buffer![1u32, 2].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let ooo_rhs = ListViewArray::try_new( + elems, + buffer![1u32, 0].into_array(), + buffer![2u32, 1].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + assert!(!all_non_distinct(&ooo_lhs, &ooo_rhs, &mut ctx)?); + assert_matches_baseline(&ooo_lhs, &ooo_rhs)?; + Ok(()) +} diff --git a/vortex-array/src/scalar/cast.rs b/vortex-array/src/scalar/cast.rs index 03807bc658f..ce24a1a55c1 100644 --- a/vortex-array/src/scalar/cast.rs +++ b/vortex-array/src/scalar/cast.rs @@ -11,6 +11,7 @@ use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; +use super::check_struct_cast_added_fields; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; @@ -60,6 +61,12 @@ impl Scalar { // Cast nulls after checking the extension dtype restrictions. if self.value().is_none() || matches!(self.dtype(), DType::Null) { + if let (Some(source), Some(target)) = ( + self.dtype().as_struct_fields_opt(), + target_dtype.as_struct_fields_opt(), + ) { + check_struct_cast_added_fields(source, target)?; + } vortex_ensure!( target_dtype.is_nullable(), "Cannot cast null to {target_dtype}: target type is non-nullable" diff --git a/vortex-array/src/scalar/tests/casting.rs b/vortex-array/src/scalar/tests/casting.rs index 088607d52ec..12c7160488c 100644 --- a/vortex-array/src/scalar/tests/casting.rs +++ b/vortex-array/src/scalar/tests/casting.rs @@ -259,11 +259,15 @@ mod tests { Nullability::NonNullable, )? .cast(&dst_dtype)?; - assert_eq!(unchanged.as_union().child(), Some(Scalar::from(42_i32))); + let unchanged_child = unchanged.as_union().child().vortex_expect("present"); + assert_eq!(unchanged_child, Scalar::from(42_i32)); assert_eq!( - changed.as_union().child(), - Some(Scalar::utf8("hello", Nullability::Nullable)) + unchanged_child.dtype(), + &DType::Primitive(PType::I32, Nullability::NonNullable) ); + let changed_child = changed.as_union().child().vortex_expect("present"); + assert_eq!(changed_child, Scalar::utf8("hello", Nullability::Nullable)); + assert_eq!(changed_child.dtype(), &DType::Utf8(Nullability::Nullable)); // Outer nullability widening preserves selected child nullability and inner null. let nullable_outer = DType::Union(src.clone(), Nullability::Nullable); @@ -322,14 +326,21 @@ mod tests { Nullability::Nullable, ); let cast_list = list.cast(&target_list)?; + assert_eq!(cast_list.dtype(), &target_list); + let cast_elem_child = cast_list + .as_list() + .element(0) + .vortex_expect("elem") + .as_union() + .child() + .vortex_expect("present"); assert_eq!( - cast_list - .as_list() - .element(0) - .vortex_expect("elem") - .as_union() - .child(), - Some(Scalar::primitive(42_i32, Nullability::Nullable)) + cast_elem_child, + Scalar::primitive(42_i32, Nullability::Nullable) + ); + assert_eq!( + cast_elem_child.dtype(), + &DType::Primitive(PType::I32, Nullability::Nullable) ); Ok(()) } diff --git a/vortex-array/src/scalar/tests/hegel.rs b/vortex-array/src/scalar/tests/hegel.rs index e0d78158ece..eda2b91f6d0 100644 --- a/vortex-array/src/scalar/tests/hegel.rs +++ b/vortex-array/src/scalar/tests/hegel.rs @@ -235,9 +235,31 @@ fn draw_pvalue(tc: &TestCase, ptype: PType) -> PValue { } } +fn widen_decimal_value(tc: &TestCase, val: DecimalValue) -> DecimalValue { + if !tc.draw(gs::booleans()) { + return val; + } + let (v, min_tier) = match val { + DecimalValue::I8(x) => (i128::from(x), 0u8), + DecimalValue::I16(x) => (i128::from(x), 1), + DecimalValue::I32(x) => (i128::from(x), 2), + DecimalValue::I64(x) => (i128::from(x), 3), + DecimalValue::I128(x) => (x, 4), + DecimalValue::I256(_) => return val, + }; + match tc.draw(gs::integers::().min_value(min_tier).max_value(5)) { + 0 => DecimalValue::I8(i8::try_from(v).vortex_expect("fits in i8")), + 1 => DecimalValue::I16(i16::try_from(v).vortex_expect("fits in i16")), + 2 => DecimalValue::I32(i32::try_from(v).vortex_expect("fits in i32")), + 3 => DecimalValue::I64(i64::try_from(v).vortex_expect("fits in i64")), + 4 => DecimalValue::I128(v), + _ => DecimalValue::I256(i256::from_i128(v)), + } +} + fn draw_decimal_value(tc: &TestCase, decimal_dtype: DecimalDType) -> DecimalValue { let p = decimal_dtype.precision() as usize; - match decimal_dtype.canonical_values_type() { + let canonical = match decimal_dtype.canonical_values_type() { DecimalType::I8 => DecimalValue::I8( tc.draw( gs::integers::() @@ -289,12 +311,17 @@ fn draw_decimal_value(tc: &TestCase, decimal_dtype: DecimalDType) -> DecimalValu }; DecimalValue::I256(val) } - } + }; + widen_decimal_value(tc, canonical) } -fn draw_variant_inner(tc: &TestCase) -> Scalar { - let inner_dtype = draw_scalar_dtype(tc, 1, false); - let inner = draw_scalar(tc, &inner_dtype); +fn draw_variant_inner(tc: &TestCase, allow_nested_variant: bool) -> Scalar { + let inner_dtype = if allow_nested_variant && tc.draw(gs::integers::().max_value(3)) == 0 { + DType::Variant(Nullability::from(tc.draw(gs::booleans()))) + } else { + draw_scalar_dtype(tc, 1, false) + }; + let inner = draw_scalar_with_variant_depth(tc, &inner_dtype, false); if inner.is_null() { Scalar::null(DType::Null) } else { @@ -303,6 +330,14 @@ fn draw_variant_inner(tc: &TestCase) -> Scalar { } pub(crate) fn draw_scalar(tc: &TestCase, dtype: &DType) -> Scalar { + draw_scalar_with_variant_depth(tc, dtype, true) +} + +fn draw_scalar_with_variant_depth( + tc: &TestCase, + dtype: &DType, + allow_nested_variant: bool, +) -> Scalar { if dtype.is_nullable() && tc.draw(gs::integers::().max_value(3)) == 0 { return Scalar::null(dtype.clone()); } @@ -315,7 +350,7 @@ pub(crate) fn draw_scalar(tc: &TestCase, dtype: &DType) -> Scalar { DType::Utf8(n) => Scalar::utf8(tc.draw(gs::text().max_size(24)), *n), DType::Binary(n) => Scalar::binary(tc.draw(gs::binary().max_size(24)), *n), DType::Variant(n) => { - let s = Scalar::variant(draw_variant_inner(tc)); + let s = Scalar::variant(draw_variant_inner(tc, allow_nested_variant)); if *n == Nullability::Nullable { s.into_nullable() } else { @@ -523,37 +558,121 @@ fn hegel_scalar_cast_matches_constant_array_cast(tc: TestCase) { ), } - if !scalar.is_null() { - let canon_res = ConstantArray::new(scalar.clone(), 1) - .into_array() - .execute::(&mut ctx) - .and_then(|c| c.into_array().cast(target.clone())) - .and_then(|arr| arr.execute::(&mut ctx)) - .and_then(|c| c.into_array().execute_scalar(0, &mut ctx)); - match (&scalar_res, &canon_res) { - (Ok(s), Ok(a)) => { - assert_eq!( - s.dtype(), - a.dtype(), - "Canonical dtype mismatch casting {scalar:?} to {target}" - ); - assert_eq!( - s, a, - "Canonical value mismatch casting {scalar:?} to {target}" - ); - } - (Err(err), Ok(a)) => panic!( - "Scalar::cast failed ({err}) while Canonical::cast succeeded ({a:?}) for {scalar:?} -> {target}" - ), - _ => {} + let canon_res = ConstantArray::new(scalar.clone(), 1) + .into_array() + .execute::(&mut ctx) + .and_then(|c| c.into_array().cast(target.clone())) + .and_then(|arr| arr.execute::(&mut ctx)) + .and_then(|c| c.into_array().execute_scalar(0, &mut ctx)); + match (&scalar_res, &canon_res) { + (Ok(s), Ok(a)) => { + assert_eq!( + s.dtype(), + a.dtype(), + "Canonical dtype mismatch casting {scalar:?} to {target}" + ); + assert_eq!( + s, a, + "Canonical value mismatch casting {scalar:?} to {target}" + ); + } + (Err(_), Err(_)) => {} + (Ok(s), Err(err)) => { + // Known cases where Scalar::cast is intentionally more permissive than Canonical::cast: + // 1. Typed nulls & empty collections: Scalar::cast skips casting inner values when a + // scalar is null or an empty List/FixedSizeList/Map, whereas Canonical::cast + // requires a CastKernel and casts inner child arrays even when empty/all-null. + // Struct added-non-nullable-field errors are NEVER ignored here. + // 2. List <-> FixedSizeList: ListScalar::cast converts between them, while + // Canonical::cast has no CastKernel between ListView and FixedSizeList. + // 3. Decimal <-> Primitive: DecimalScalar/PrimitiveScalar support numeric casts that + // Canonical::cast has no CastKernel for. + let is_added_nonnull_field_err = err + .to_string() + .contains("CAST for struct only supports added nullable fields"); + let is_known_exception = !is_added_nonnull_field_err + && (contains_empty_collection_or_null(&scalar) + || contains_known_canonical_cast_gap(scalar.dtype(), &target)); + assert!( + is_known_exception, + "Scalar::cast succeeded ({s:?}) while Canonical::cast failed ({err}) for {scalar:?} -> {target}" + ); + } + (Err(err), Ok(a)) => panic!( + "Scalar::cast failed ({err}) while Canonical::cast succeeded ({a:?}) for {scalar:?} -> {target}" + ), + } +} + +fn contains_empty_collection_or_null(scalar: &Scalar) -> bool { + if scalar.is_null() { + return true; + } + match scalar.dtype() { + DType::List(..) | DType::FixedSizeList(..) => { + let list = scalar.as_list(); + list.is_empty() + || list + .elements() + .is_some_and(|elems| elems.iter().any(contains_empty_collection_or_null)) + } + DType::Struct(..) => scalar + .as_struct() + .fields_iter() + .is_some_and(|mut fields| fields.any(|f| contains_empty_collection_or_null(&f))), + DType::Map(..) => { + let map = scalar.as_map(); + map.is_empty() + || map.entries().any(|(k, v)| { + contains_empty_collection_or_null(&k) || contains_empty_collection_or_null(&v) + }) + } + _ => false, + } +} + +fn contains_known_canonical_cast_gap(source: &DType, target: &DType) -> bool { + match (source, target) { + (DType::FixedSizeList(..), DType::List(..)) + | (DType::List(..), DType::FixedSizeList(..)) + | (DType::Decimal(..), DType::Primitive(..)) + | (DType::Primitive(..), DType::Decimal(..)) => true, + (DType::List(a, _), DType::List(b, _)) + | (DType::FixedSizeList(a, ..), DType::FixedSizeList(b, ..)) => { + contains_known_canonical_cast_gap(a, b) + } + (DType::Struct(a, _), DType::Struct(b, _)) => { + b.names().iter().zip(b.fields()).any(|(name, tb)| { + a.find(name).is_some_and(|i| { + contains_known_canonical_cast_gap( + &a.field_by_index(i).vortex_expect("valid field"), + &tb, + ) + }) + }) } + (DType::Map(a, _), DType::Map(b, _)) => { + contains_known_canonical_cast_gap(&a.key_dtype(), &b.key_dtype()) + || contains_known_canonical_cast_gap(&a.value_dtype(), &b.value_dtype()) + } + _ => false, + } +} + +fn draw_multi_width_i128(tc: &TestCase) -> i128 { + match tc.draw(gs::integers::().max_value(4)) { + 0 => i128::from(tc.draw(gs::integers::())), + 1 => i128::from(tc.draw(gs::integers::())), + 2 => i128::from(tc.draw(gs::integers::())), + 3 => i128::from(tc.draw(gs::integers::())), + _ => tc.draw(gs::integers::()), } } #[hegel::test(test_cases = 200)] fn hegel_decimal_value_eq_ord_hash_across_widths(tc: TestCase) { - let v1 = tc.draw(gs::integers::()); - let v2 = tc.draw(gs::integers::()); + let v1 = draw_multi_width_i128(&tc); + let v2 = draw_multi_width_i128(&tc); let reps = |v: i128| -> Vec { let mut out = vec![ @@ -610,6 +729,46 @@ fn contains_variant(dtype: &DType) -> bool { } } +fn make_nested_nullable(dtype: &DType) -> DType { + match dtype { + DType::List(elem, nullability) => DType::List( + Arc::new(make_nested_nullable(elem).as_nullable()), + *nullability, + ), + DType::FixedSizeList(elem, size, nullability) => DType::FixedSizeList( + Arc::new(make_nested_nullable(elem).as_nullable()), + *size, + *nullability, + ), + DType::Struct(fields, n) => DType::struct_( + fields + .names() + .iter() + .zip(fields.fields()) + .map(|(name, f)| (name.clone(), make_nested_nullable(&f).as_nullable())), + *n, + ), + DType::Map(m, n) => DType::map( + m.key_dtype(), + make_nested_nullable(&m.value_dtype()).as_nullable(), + m.keys_sorted(), + *n, + ) + .vortex_expect("valid map dtype"), + DType::Union(u, n) => DType::Union( + UnionVariants::new( + u.names().clone(), + u.variants() + .map(|v| make_nested_nullable(&v).as_nullable()) + .collect(), + ) + .vortex_expect("valid union variants"), + *n, + ), + _ => dtype.clone(), + } +} + #[hegel::test(test_cases = 200)] fn hegel_eq_ord_hash_and_nullability_laws(tc: TestCase) { let depth = tc.draw(gs::integers::().max_value(2)); @@ -638,14 +797,26 @@ fn hegel_eq_ord_hash_and_nullability_laws(tc: TestCase) { assert_eq!(ord == Ordering::Equal, a == b); } - // Nullability invariance and null-orders-first law + // Nullability invariance (top-level and nested) and null-orders-first law let a_nullable = a.clone().into_nullable(); + assert_eq!(a_nullable.dtype(), &dtype.as_nullable()); assert_eq!(a, a_nullable); assert_eq!(hash_of(&a), hash_of(&a_nullable)); if !contains_variant(&dtype) { assert_eq!(a.partial_cmp(&a_nullable), Some(Ordering::Equal)); } + let nested_nullable_dtype = make_nested_nullable(&dtype); + if nested_nullable_dtype != dtype + && let Ok(a_nested) = Scalar::try_new(nested_nullable_dtype, a.value().cloned()) + { + assert_eq!(a, a_nested); + assert_eq!(hash_of(&a), hash_of(&a_nested)); + if !contains_variant(&dtype) { + assert_eq!(a.partial_cmp(&a_nested), Some(Ordering::Equal)); + } + } + if !a.is_null() { let null_s = Scalar::null(dtype.as_nullable()); assert_ne!(null_s, a_nullable); diff --git a/vortex-array/src/scalar/tests/nested.rs b/vortex-array/src/scalar/tests/nested.rs index 7c57aa9a75d..7acb5a53002 100644 --- a/vortex-array/src/scalar/tests/nested.rs +++ b/vortex-array/src/scalar/tests/nested.rs @@ -8,13 +8,21 @@ #[cfg(test)] mod tests { + use std::cmp::Ordering; + use std::hash::DefaultHasher; + use std::hash::Hash; + use std::hash::Hasher; use std::sync::Arc; + use rstest::rstest; use vortex_error::VortexResult; use crate::dtype::DType; + use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; + use crate::dtype::half::f16; + use crate::scalar::DecimalValue; use crate::scalar::PValue; use crate::scalar::Scalar; use crate::scalar::ScalarValue; @@ -147,4 +155,114 @@ mod tests { ); assert_eq!(string_list.approx_nbytes(), 5); } + + #[test] + fn test_scalar_hash_ignores_nested_nullability() { + let hash_of = |s: &Scalar| { + let mut h = DefaultHasher::new(); + s.hash(&mut h); + h.finish() + }; + + let list_nullable = Scalar::list( + DType::Primitive(PType::I32, Nullability::Nullable), + vec![Scalar::primitive(42i32, Nullability::Nullable)], + Nullability::NonNullable, + ); + let list_nonnull = Scalar::list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::primitive(42i32, Nullability::NonNullable)], + Nullability::NonNullable, + ); + assert_eq!(list_nullable, list_nonnull); + assert_eq!(hash_of(&list_nullable), hash_of(&list_nonnull)); + + let struct_nullable = Scalar::struct_( + DType::struct_( + [("v", DType::Primitive(PType::I32, Nullability::Nullable))], + Nullability::NonNullable, + ), + vec![Scalar::primitive(42i32, Nullability::Nullable)], + ); + let struct_nonnull = Scalar::struct_( + DType::struct_( + [("v", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + ), + vec![Scalar::primitive(42i32, Nullability::NonNullable)], + ); + assert_eq!(struct_nullable, struct_nonnull); + assert_eq!(hash_of(&struct_nullable), hash_of(&struct_nonnull)); + } + + #[rstest] + #[case::decimal( + Scalar::decimal( + DecimalValue::I32(100), + DecimalDType::new(5, 2), + Nullability::NonNullable, + ), + Scalar::decimal( + DecimalValue::I32(200), + DecimalDType::new(5, 2), + Nullability::NonNullable, + ) + )] + #[case::f16( + Scalar::primitive(f16::from_f32(-1.5), Nullability::NonNullable), + Scalar::primitive(f16::from_f32(2.5), Nullability::NonNullable), + )] + #[case::f32( + Scalar::primitive(-1.5f32, Nullability::NonNullable), + Scalar::primitive(2.5f32, Nullability::NonNullable), + )] + #[case::f64( + Scalar::primitive(1.5f64, Nullability::NonNullable), + Scalar::primitive(f64::NAN, Nullability::NonNullable) + )] + #[case::list( + Scalar::list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::from(1i32), Scalar::from(2i32)], + Nullability::NonNullable, + ), + Scalar::list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::from(1i32), Scalar::from(3i32)], + Nullability::NonNullable, + ), + )] + #[case::fixed_size_list( + Scalar::fixed_size_list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::from(1i32), Scalar::from(2i32)], + Nullability::NonNullable, + ), + Scalar::fixed_size_list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::from(1i32), Scalar::from(3i32)], + Nullability::NonNullable, + ), + )] + #[case::struct_( + Scalar::struct_( + DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + ), + vec![Scalar::from(1i32)], + ), + Scalar::struct_( + DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + ), + vec![Scalar::from(2i32)], + ), + )] + fn test_scalar_ordering_direction(#[case] smaller: Scalar, #[case] larger: Scalar) { + assert_ne!(smaller, larger); + assert_eq!(smaller.partial_cmp(&larger), Some(Ordering::Less)); + assert_eq!(larger.partial_cmp(&smaller), Some(Ordering::Greater)); + } } diff --git a/vortex-array/src/scalar/typed_view/decimal/tests.rs b/vortex-array/src/scalar/typed_view/decimal/tests.rs index fee77d69bf2..8b406e4c9de 100644 --- a/vortex-array/src/scalar/typed_view/decimal/tests.rs +++ b/vortex-array/src/scalar/typed_view/decimal/tests.rs @@ -166,8 +166,32 @@ fn test_decimal_cast_exact_and_lossy_and_unsupported() -> VortexResult<()> { DType::Utf8(Nullability::NonNullable), DType::Binary(Nullability::NonNullable), ] { - assert!(d.cast(&target).is_err()); + let err = d.cast(&target).unwrap_err(); + assert!(err.to_string().contains("Cannot cast"), "{err}"); } + // Out-of-range decimal -> int casts report the target range error. + let u8_err = Scalar::decimal( + DecimalValue::I32(25_600), + DecimalDType::new(10, 2), + Nullability::NonNullable, + ) + .cast(&DType::Primitive(PType::U8, Nullability::NonNullable)) + .unwrap_err(); + assert!( + u8_err.to_string().contains("out of range for u8"), + "{u8_err}" + ); + let u32_err = Scalar::decimal( + DecimalValue::I32(-5_000), + DecimalDType::new(10, 2), + Nullability::NonNullable, + ) + .cast(&DType::Primitive(PType::U32, Nullability::NonNullable)) + .unwrap_err(); + assert!( + u32_err.to_string().contains("out of range for u32"), + "{u32_err}" + ); Ok(()) } @@ -193,10 +217,18 @@ fn cast_decimal_to_f64_spans_the_scale_domain( ); let value: f64 = (&scalar.cast(&DType::Primitive(PType::F64, Nullability::NonNullable))?).try_into()?; - assert!( - (value - expected).abs() <= expected.abs() * 1e-15, - "decimal({precision},{scale}) storing {stored} cast to {value}, expected {expected}" - ); + if scale.abs() <= 22 { + assert_eq!( + value, expected, + "decimal({precision},{scale}) storing {stored} cast to {value}, expected {expected}" + ); + } else { + // `10^scale` is not exact in `f64` above `10^22`. + assert!( + (value - expected).abs() <= expected.abs() * 1e-15, + "decimal({precision},{scale}) storing {stored} cast to {value}, expected {expected}" + ); + } Ok(()) } @@ -225,19 +257,26 @@ fn cast_decimal_to_narrow_float_and_wide_i256_to_f64() -> VortexResult<()> { #[test] fn test_decimal_conversions_and_partial_ord_mismatch() -> VortexResult<()> { - // Unsigned From -> wider signed DecimalValue. - assert_eq!(DecimalValue::from(255u8).decimal_type(), DecimalType::I16); + // Unsigned From -> wider signed DecimalValue (check both width and exact value). + let from_u8 = DecimalValue::from(255u8); + assert_eq!( + (from_u8.decimal_type(), from_u8), + (DecimalType::I16, DecimalValue::I16(255)) + ); + let from_u16 = DecimalValue::from(65535u16); assert_eq!( - DecimalValue::from(65535u16).decimal_type(), - DecimalType::I32 + (from_u16.decimal_type(), from_u16), + (DecimalType::I32, DecimalValue::I32(65_535)) ); + let from_u32 = DecimalValue::from(u32::MAX); assert_eq!( - DecimalValue::from(u32::MAX).decimal_type(), - DecimalType::I64 + (from_u32.decimal_type(), from_u32), + (DecimalType::I64, DecimalValue::I64(i64::from(u32::MAX))) ); + let from_u64 = DecimalValue::from(u64::MAX); assert_eq!( - DecimalValue::from(u64::MAX).decimal_type(), - DecimalType::I128 + (from_u64.decimal_type(), from_u64), + (DecimalType::I128, DecimalValue::I128(i128::from(u64::MAX))) ); // Scalar::from(DecimalValue) / TryFrom roundtrip across widths. @@ -437,6 +476,7 @@ fn test_decimal_scalar_checked_binary_numeric_edge_cases() -> VortexResult<()> { )? .ok_or_else(|| vortex_err!("expected carry digit"))?; assert_eq!(sum_dtype, DecimalDType::new(4, 0)); + assert_eq!(sum.decimal_type(), DecimalType::I16); assert_eq!(sum, DecimalValue::I16(1_001)); // Saturated precision overflow for Add and Mul. diff --git a/vortex-array/src/scalar/typed_view/extension/tests.rs b/vortex-array/src/scalar/typed_view/extension/tests.rs index b96fcfcc26c..26e278198c2 100644 --- a/vortex-array/src/scalar/typed_view/extension/tests.rs +++ b/vortex-array/src/scalar/typed_view/extension/tests.rs @@ -1,6 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::cmp::Ordering; +use std::hash::DefaultHasher; +use std::hash::Hash; +use std::hash::Hasher; + use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -149,3 +154,47 @@ fn test_ext_scalar_cast_errors() { .is_err() ); } + +#[test] +fn test_ext_scalar_hash_ignores_storage_nullability() { + let nullable = Scalar::extension::( + EmptyMetadata, + Scalar::primitive(42_i32, Nullability::Nullable), + ); + let non_nullable = Scalar::extension::( + EmptyMetadata, + Scalar::primitive(42_i32, Nullability::NonNullable), + ); + let nullable = nullable.as_extension(); + let non_nullable = non_nullable.as_extension(); + + assert_eq!(nullable, non_nullable); + + let mut nullable_hasher = DefaultHasher::new(); + nullable.hash(&mut nullable_hasher); + let mut non_nullable_hasher = DefaultHasher::new(); + non_nullable.hash(&mut non_nullable_hasher); + assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); +} + +#[test] +fn test_ext_scalar_ordering_direction() { + let smaller = Scalar::extension::( + EmptyMetadata, + Scalar::primitive(10_i32, Nullability::NonNullable), + ); + let larger = Scalar::extension::( + EmptyMetadata, + Scalar::primitive(20_i32, Nullability::NonNullable), + ); + + assert_ne!(smaller.as_extension(), larger.as_extension()); + assert_eq!( + smaller.as_extension().partial_cmp(&larger.as_extension()), + Some(Ordering::Less) + ); + assert_eq!( + larger.as_extension().partial_cmp(&smaller.as_extension()), + Some(Ordering::Greater) + ); +} diff --git a/vortex-array/src/scalar/typed_view/list.rs b/vortex-array/src/scalar/typed_view/list.rs index 6674b459513..1890ce14b7d 100644 --- a/vortex-array/src/scalar/typed_view/list.rs +++ b/vortex-array/src/scalar/typed_view/list.rs @@ -233,6 +233,9 @@ impl<'a> ListScalar<'a> { #[cfg(test)] mod tests { + use std::cmp::Ordering; + use std::hash::DefaultHasher; + use std::hash::Hasher; use std::sync::Arc; use super::*; @@ -297,4 +300,73 @@ mod tests { Nullability::NonNullable, ); } + + #[test] + fn test_list_hash_ignores_nested_nullability() { + let nullable = Scalar::list( + DType::Primitive(PType::I32, Nullability::Nullable), + vec![Scalar::primitive(42_i32, Nullability::Nullable)], + Nullability::NonNullable, + ); + let non_nullable = Scalar::list( + DType::Primitive(PType::I32, Nullability::NonNullable), + vec![Scalar::primitive(42_i32, Nullability::NonNullable)], + Nullability::NonNullable, + ); + let nullable = nullable.as_list(); + let non_nullable = non_nullable.as_list(); + + assert_eq!(nullable, non_nullable); + + let mut nullable_hasher = DefaultHasher::new(); + nullable.hash(&mut nullable_hasher); + let mut non_nullable_hasher = DefaultHasher::new(); + non_nullable.hash(&mut non_nullable_hasher); + assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); + } + + #[test] + fn test_list_and_fsl_ordering_direction() { + let elem = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)); + + let smaller_list = Scalar::list( + Arc::clone(&elem), + vec![Scalar::from(1i32), Scalar::from(2i32)], + Nullability::NonNullable, + ); + let larger_list = Scalar::list( + Arc::clone(&elem), + vec![Scalar::from(1i32), Scalar::from(3i32)], + Nullability::NonNullable, + ); + assert_ne!(smaller_list.as_list(), larger_list.as_list()); + assert_eq!( + smaller_list.as_list().partial_cmp(&larger_list.as_list()), + Some(Ordering::Less) + ); + assert_eq!( + larger_list.as_list().partial_cmp(&smaller_list.as_list()), + Some(Ordering::Greater) + ); + + let smaller_fsl = Scalar::fixed_size_list( + Arc::clone(&elem), + vec![Scalar::from(1i32), Scalar::from(2i32)], + Nullability::NonNullable, + ); + let larger_fsl = Scalar::fixed_size_list( + elem, + vec![Scalar::from(1i32), Scalar::from(3i32)], + Nullability::NonNullable, + ); + assert_ne!(smaller_fsl.as_list(), larger_fsl.as_list()); + assert_eq!( + smaller_fsl.as_list().partial_cmp(&larger_fsl.as_list()), + Some(Ordering::Less) + ); + assert_eq!( + larger_fsl.as_list().partial_cmp(&smaller_fsl.as_list()), + Some(Ordering::Greater) + ); + } } diff --git a/vortex-array/src/scalar/typed_view/primitive/tests.rs b/vortex-array/src/scalar/typed_view/primitive/tests.rs index d412f2533ea..a9ca9a0a0b1 100644 --- a/vortex-array/src/scalar/typed_view/primitive/tests.rs +++ b/vortex-array/src/scalar/typed_view/primitive/tests.rs @@ -254,21 +254,22 @@ fn test_pvalue_cross_type_eq_ord_hash_zero_and_bytes() { assert_eq!(PValue::F32(42.0).partial_cmp(&PValue::F64(42.0)), None); // Zero values and is_instance_of across all PTypes. - for ptype in [ - PType::U8, - PType::U16, - PType::U32, - PType::U64, - PType::I8, - PType::I16, - PType::I32, - PType::I64, - PType::F16, - PType::F32, - PType::F64, + for (ptype, expected_zero) in [ + (PType::U8, PValue::U8(0)), + (PType::U16, PValue::U16(0)), + (PType::U32, PValue::U32(0)), + (PType::U64, PValue::U64(0)), + (PType::I8, PValue::I8(0)), + (PType::I16, PValue::I16(0)), + (PType::I32, PValue::I32(0)), + (PType::I64, PValue::I64(0)), + (PType::F16, PValue::F16(f16::ZERO)), + (PType::F32, PValue::F32(0.0)), + (PType::F64, PValue::F64(0.0)), ] { let z = PValue::zero(&ptype); assert_eq!(z.ptype(), ptype); + assert_eq!(z, expected_zero); assert!(z.is_instance_of(&ptype)); } assert!(!PValue::U8(10).is_instance_of(&PType::U16)); @@ -333,7 +334,9 @@ fn test_coerce_pvalue_and_bounds() -> VortexResult<()> { assert!(f16::coerce(PValue::U32(u32::from(u16::MAX) + 1)).is_err()); assert!(f16::coerce(PValue::U64(u64::from(u16::MAX) + 1)).is_err()); - // f32 bit coercion bounds. + // f32 bit coercion bounds (including narrow unsigned widths U8/U16). + assert_eq!(f32::coerce(PValue::U8(0x2A))?.to_bits(), 0x2Au32); + assert_eq!(f32::coerce(PValue::U16(0x1234))?.to_bits(), 0x1234u32); assert_eq!(f32::coerce(PValue::U32(0x3f80_0000))?, 1.0f32); assert_eq!( f32::coerce(PValue::U64(u64::from(u32::MAX)))?.to_bits(), @@ -341,7 +344,13 @@ fn test_coerce_pvalue_and_bounds() -> VortexResult<()> { ); assert!(f32::coerce(PValue::U64(u64::from(u32::MAX) + 1)).is_err()); - // f64 accepts all unsigned widths as bit patterns. + // f64 accepts all unsigned widths (U8/U16/U32/U64) as bit patterns. + assert_eq!(f64::coerce(PValue::U8(0x2A))?.to_bits(), 0x2Au64); + assert_eq!(f64::coerce(PValue::U16(0x1234))?.to_bits(), 0x1234u64); + assert_eq!( + f64::coerce(PValue::U32(0x1234_5678))?.to_bits(), + 0x1234_5678u64 + ); assert_eq!(f64::coerce(PValue::U64(0x3ff0_0000_0000_0000))?, 1.0f64); assert_eq!(f64::coerce(PValue::U64(u64::MAX))?.to_bits(), u64::MAX); Ok(()) diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index b9c59781610..b4f4f268247 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -218,6 +218,7 @@ impl<'a> StructScalar<'a> { let own_st = self.struct_fields(); let Some(fs) = self.fields else { + check_struct_cast_added_fields(own_st, st)?; return Scalar::try_new(dtype.clone(), None); }; @@ -301,6 +302,25 @@ impl<'a> StructScalar<'a> { } } +/// Checks that any target struct field absent from `source` is nullable, matching +/// [`struct_cast_fields`](crate::arrays::struct_::compute::cast::struct_cast_fields). +pub(crate) fn check_struct_cast_added_fields( + source: &StructFields, + target: &StructFields, +) -> VortexResult<()> { + if source.names() != target.names() { + for (target_name, target_dtype) in target.names().iter().zip(target.fields()) { + if source.find(target_name).is_none() { + vortex_ensure!( + target_dtype.is_nullable(), + "CAST for struct only supports added nullable fields" + ); + } + } + } + Ok(()) +} + impl Scalar { /// Creates a new struct scalar with the given fields, checking dtypes at runtime. pub fn struct_(dtype: DType, children: impl IntoIterator) -> Self { @@ -354,6 +374,8 @@ impl Scalar { #[cfg(test)] mod tests { + use std::hash::DefaultHasher; + use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -566,6 +588,34 @@ mod tests { ); assert!(evolved.as_struct().field("c").unwrap().is_null()); + // Renaming fields with the same field count matches by name (not positionally). + let renamed_nullable = DType::struct_( + [ + ("x", DType::Primitive(PType::I32, Nullability::Nullable)), + ("y", DType::Primitive(PType::I64, Nullability::Nullable)), + ], + Nullability::NonNullable, + ); + let renamed = src.cast(&renamed_nullable)?; + assert!(renamed.as_struct().field("x").unwrap().is_null()); + assert!(renamed.as_struct().field("y").unwrap().is_null()); + let struct_renamed = ConstantArray::new(src.clone(), 1) + .into_array() + .execute::(&mut ctx)? + .into_array() + .cast(renamed_nullable)? + .execute_scalar(0, &mut ctx)?; + assert_eq!(struct_renamed, renamed); + + let renamed_nonnull = DType::struct_( + [ + ("x", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("y", DType::Primitive(PType::I64, Nullability::NonNullable)), + ], + Nullability::NonNullable, + ); + assert!(src.cast(&renamed_nonnull).is_err()); + // Adding a non-nullable field is rejected. let added_nonnull = DType::struct_( [ @@ -576,12 +626,107 @@ mod tests { ); assert!(src.cast(&added_nonnull).is_err()); - // Direct StructScalar::cast on null to non-nullable struct returns Err instead of panicking. + // Null nullable struct cast to nullable struct adding a non-nullable field is rejected + // by both Scalar::cast and StructScalar::cast (matching StructArray::cast). let null_struct = Scalar::null(DType::struct_( - [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + [("a", DType::Primitive(PType::I32, Nullability::Nullable))], Nullability::Nullable, )); + let nullable_added_nonnull = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::Nullable)), + ("b", DType::Primitive(PType::I32, Nullability::NonNullable)), + ], + Nullability::Nullable, + ); + let err = null_struct.cast(&nullable_added_nonnull).unwrap_err(); + assert!( + err.to_string() + .contains("CAST for struct only supports added nullable fields"), + "{err}" + ); + let err = null_struct + .as_struct() + .cast(&nullable_added_nonnull) + .unwrap_err(); + assert!( + err.to_string() + .contains("CAST for struct only supports added nullable fields"), + "{err}" + ); + // Adding a nullable field to a null struct succeeds with a typed null. + let nullable_added_nullable = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::Nullable)), + ("b", DType::Primitive(PType::I32, Nullability::Nullable)), + ], + Nullability::Nullable, + ); + let null_evolved = null_struct.as_struct().cast(&nullable_added_nullable)?; + assert!(null_evolved.is_null()); + assert_eq!(null_evolved.dtype(), &nullable_added_nullable); + + // Direct StructScalar::cast on null to non-nullable struct returns Err instead of panicking. assert!(null_struct.as_struct().cast(&added_nonnull).is_err()); Ok(()) } + + #[test] + fn test_struct_hash_ignores_nested_nullability() { + let nullable_dtype = DType::Struct( + StructFields::new( + ["value"].into(), + vec![DType::Primitive(PType::I32, Nullability::Nullable)], + ), + Nullability::NonNullable, + ); + let non_nullable_dtype = DType::Struct( + StructFields::new( + ["value"].into(), + vec![DType::Primitive(PType::I32, Nullability::NonNullable)], + ), + Nullability::NonNullable, + ); + let nullable = Scalar::struct_( + nullable_dtype, + [Scalar::primitive(42_i32, Nullability::Nullable)], + ); + let non_nullable = Scalar::struct_( + non_nullable_dtype, + [Scalar::primitive(42_i32, Nullability::NonNullable)], + ); + let nullable = nullable.as_struct(); + let non_nullable = non_nullable.as_struct(); + + assert_eq!(nullable, non_nullable); + + let mut nullable_hasher = DefaultHasher::new(); + nullable.hash(&mut nullable_hasher); + let mut non_nullable_hasher = DefaultHasher::new(); + non_nullable.hash(&mut non_nullable_hasher); + assert_eq!(nullable_hasher.finish(), non_nullable_hasher.finish()); + } + + #[test] + fn test_struct_ordering_direction() { + let dtype = DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I32, Nullability::NonNullable)), + ], + Nullability::NonNullable, + ); + let smaller = Scalar::struct_(dtype.clone(), [Scalar::from(1i32), Scalar::from(10i32)]); + let larger = Scalar::struct_(dtype, [Scalar::from(1i32), Scalar::from(20i32)]); + + assert_ne!(smaller.as_struct(), larger.as_struct()); + assert_eq!( + smaller.as_struct().partial_cmp(&larger.as_struct()), + Some(Ordering::Less) + ); + assert_eq!( + larger.as_struct().partial_cmp(&smaller.as_struct()), + Some(Ordering::Greater) + ); + } } From 05d00d399b3555e37c1720c50c88e93ca70af908 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 20:04:17 +0000 Subject: [PATCH 3/9] Match repeated struct cast fields by occurrence and tighten test parity checks Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../fns/all_non_distinct/tests.rs | 17 ++ .../src/arrays/struct_/compute/cast.rs | 8 +- vortex-array/src/scalar/tests/hegel.rs | 73 ++++++--- vortex-array/src/scalar/typed_view/struct_.rs | 145 +++++++++++++++--- .../src/scalar_fn/builtin/cast/mod.rs | 7 +- 5 files changed, 199 insertions(+), 51 deletions(-) diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs index e2c5ca243b3..ab5a4aaf5e1 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs @@ -625,3 +625,20 @@ fn list_different_lengths_same_flattened_elements() -> VortexResult<()> { assert_matches_baseline(&ooo_lhs, &ooo_rhs)?; Ok(()) } + +#[test] +fn long_array_mismatch_at_last_row() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let base: Vec = (0..1000).collect(); + let mut diff = base.clone(); + diff[999] = -1; + + let lhs = PrimitiveArray::from_iter(base.clone()).into_array(); + let eq_rhs = PrimitiveArray::from_iter(base).into_array(); + let ne_rhs = PrimitiveArray::from_iter(diff).into_array(); + + assert!(all_non_distinct(&lhs, &eq_rhs, &mut ctx)?); + assert!(!all_non_distinct(&lhs, &ne_rhs, &mut ctx)?); + assert_matches_baseline(&lhs, &ne_rhs)?; + Ok(()) +} diff --git a/vortex-array/src/arrays/struct_/compute/cast.rs b/vortex-array/src/arrays/struct_/compute/cast.rs index 9a6dc4b1919..d5bc49b7762 100644 --- a/vortex-array/src/arrays/struct_/compute/cast.rs +++ b/vortex-array/src/arrays/struct_/compute/cast.rs @@ -22,6 +22,7 @@ use crate::dtype::StructFields; use crate::kernel::ExecuteParentKernel; use crate::optimizer::kernels::ArrayKernelsExt; use crate::scalar::Scalar; +use crate::scalar::map_struct_cast_fields; use crate::scalar_fn::ScalarFnVTable; use crate::scalar_fn::builtin::cast::Cast; @@ -96,8 +97,11 @@ pub(crate) fn struct_cast_fields( cast_fields.push(cast_field); } } else { - for (target_name, target_type) in target_type.names().iter().zip_eq(target_type.fields()) { - match source_sdtype.find(target_name) { + for (src_field_idx, target_type) in map_struct_cast_fields(source_sdtype, target_type) + .into_iter() + .zip_eq(target_type.fields()) + { + match src_field_idx { None => { // No source field with this name => evolve the schema compatibly. // If the field is nullable, we add a new ConstantArray field with the type. diff --git a/vortex-array/src/scalar/tests/hegel.rs b/vortex-array/src/scalar/tests/hegel.rs index eda2b91f6d0..6ed39ba4844 100644 --- a/vortex-array/src/scalar/tests/hegel.rs +++ b/vortex-array/src/scalar/tests/hegel.rs @@ -591,7 +591,7 @@ fn hegel_scalar_cast_matches_constant_array_cast(tc: TestCase) { .to_string() .contains("CAST for struct only supports added nullable fields"); let is_known_exception = !is_added_nonnull_field_err - && (contains_empty_collection_or_null(&scalar) + && (has_empty_collection_or_null_in_cast(&scalar, &target) || contains_known_canonical_cast_gap(scalar.dtype(), &target)); assert!( is_known_exception, @@ -604,27 +604,47 @@ fn hegel_scalar_cast_matches_constant_array_cast(tc: TestCase) { } } -fn contains_empty_collection_or_null(scalar: &Scalar) -> bool { +fn has_empty_collection_or_null_in_cast(scalar: &Scalar, target: &DType) -> bool { if scalar.is_null() { return true; } - match scalar.dtype() { - DType::List(..) | DType::FixedSizeList(..) => { + match (scalar.dtype(), target) { + (DType::List(..) | DType::FixedSizeList(..), DType::List(elem_target, _)) + | (DType::List(..) | DType::FixedSizeList(..), DType::FixedSizeList(elem_target, ..)) => { let list = scalar.as_list(); list.is_empty() - || list - .elements() - .is_some_and(|elems| elems.iter().any(contains_empty_collection_or_null)) + || list.elements().is_some_and(|elems| { + elems + .iter() + .any(|elem| has_empty_collection_or_null_in_cast(elem, elem_target)) + }) + } + (DType::Struct(src_fields, _), DType::Struct(dst_fields, _)) => { + let st = scalar.as_struct(); + if src_fields.names() == dst_fields.names() { + st.fields_iter().is_some_and(|fields| { + fields + .zip(dst_fields.fields()) + .any(|(f, dst_dt)| has_empty_collection_or_null_in_cast(&f, &dst_dt)) + }) + } else { + crate::scalar::map_struct_cast_fields(src_fields, dst_fields) + .into_iter() + .zip(dst_fields.fields()) + .any(|(src_idx, dst_dt)| { + src_idx.is_some_and(|i| { + st.field_by_idx(i) + .is_some_and(|f| has_empty_collection_or_null_in_cast(&f, &dst_dt)) + }) + }) + } } - DType::Struct(..) => scalar - .as_struct() - .fields_iter() - .is_some_and(|mut fields| fields.any(|f| contains_empty_collection_or_null(&f))), - DType::Map(..) => { + (DType::Map(..), DType::Map(dst_map, _)) => { let map = scalar.as_map(); map.is_empty() || map.entries().any(|(k, v)| { - contains_empty_collection_or_null(&k) || contains_empty_collection_or_null(&v) + has_empty_collection_or_null_in_cast(&k, &dst_map.key_dtype()) + || has_empty_collection_or_null_in_cast(&v, &dst_map.value_dtype()) }) } _ => false, @@ -635,21 +655,30 @@ fn contains_known_canonical_cast_gap(source: &DType, target: &DType) -> bool { match (source, target) { (DType::FixedSizeList(..), DType::List(..)) | (DType::List(..), DType::FixedSizeList(..)) - | (DType::Decimal(..), DType::Primitive(..)) + | (DType::Decimal(..), DType::Primitive(PType::F16 | PType::F32, _)) | (DType::Primitive(..), DType::Decimal(..)) => true, (DType::List(a, _), DType::List(b, _)) | (DType::FixedSizeList(a, ..), DType::FixedSizeList(b, ..)) => { contains_known_canonical_cast_gap(a, b) } (DType::Struct(a, _), DType::Struct(b, _)) => { - b.names().iter().zip(b.fields()).any(|(name, tb)| { - a.find(name).is_some_and(|i| { - contains_known_canonical_cast_gap( - &a.field_by_index(i).vortex_expect("valid field"), - &tb, - ) - }) - }) + if a.names() == b.names() { + a.fields() + .zip(b.fields()) + .any(|(ta, tb)| contains_known_canonical_cast_gap(&ta, &tb)) + } else { + crate::scalar::map_struct_cast_fields(a, b) + .into_iter() + .zip(b.fields()) + .any(|(src_idx, tb)| { + src_idx.is_some_and(|i| { + contains_known_canonical_cast_gap( + &a.field_by_index(i).vortex_expect("valid field"), + &tb, + ) + }) + }) + } } (DType::Map(a, _), DType::Map(b, _)) => { contains_known_canonical_cast_gap(&a.key_dtype(), &b.key_dtype()) diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index b4f4f268247..bd5e9423054 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -240,28 +240,26 @@ impl<'a> StructScalar<'a> { }) .collect::>>()? } else { - st.names() - .iter() + map_struct_cast_fields(own_st, st) + .into_iter() .zip(st.fields()) - .map( - |(target_name, target_dtype)| match own_st.find(target_name) { - None => { - vortex_ensure!( - target_dtype.is_nullable(), - "CAST for struct only supports added nullable fields" - ); - Ok(None) - } - Some(src_idx) => Scalar::try_new( - own_st - .field_by_index(src_idx) - .vortex_expect("valid source field index"), - fs[src_idx].clone(), - )? - .cast(&target_dtype) - .map(|s| s.into_value()), - }, - ) + .map(|(src_idx, target_dtype)| match src_idx { + None => { + vortex_ensure!( + target_dtype.is_nullable(), + "CAST for struct only supports added nullable fields" + ); + Ok(None) + } + Some(src_idx) => Scalar::try_new( + own_st + .field_by_index(src_idx) + .vortex_expect("valid source field index"), + fs[src_idx].clone(), + )? + .cast(&target_dtype) + .map(|s| s.into_value()), + }) .collect::>>()? }; Scalar::try_new(dtype.clone(), Some(ScalarValue::Tuple(fields))) @@ -302,6 +300,31 @@ impl<'a> StructScalar<'a> { } } +/// Maps each target struct field to the matching source field index by `(name, occurrence)`, +/// or `None` when the target field has no remaining source field with the same name. +pub(crate) fn map_struct_cast_fields( + source: &StructFields, + target: &StructFields, +) -> Vec> { + let mut used = vec![false; source.nfields()]; + target + .names() + .iter() + .map(|target_name| { + let src_idx = source + .names() + .iter() + .enumerate() + .find(|&(i, name)| !used[i] && name == target_name) + .map(|(i, _)| i); + if let Some(i) = src_idx { + used[i] = true; + } + src_idx + }) + .collect() +} + /// Checks that any target struct field absent from `source` is nullable, matching /// [`struct_cast_fields`](crate::arrays::struct_::compute::cast::struct_cast_fields). pub(crate) fn check_struct_cast_added_fields( @@ -309,8 +332,11 @@ pub(crate) fn check_struct_cast_added_fields( target: &StructFields, ) -> VortexResult<()> { if source.names() != target.names() { - for (target_name, target_dtype) in target.names().iter().zip(target.fields()) { - if source.find(target_name).is_none() { + for (src_idx, target_dtype) in map_struct_cast_fields(source, target) + .into_iter() + .zip(target.fields()) + { + if src_idx.is_none() { vortex_ensure!( target_dtype.is_nullable(), "CAST for struct only supports added nullable fields" @@ -380,6 +406,7 @@ mod tests { use vortex_session::VortexSession; use super::*; + use crate::Canonical; use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::ConstantArray; @@ -561,7 +588,7 @@ mod tests { .execute_scalar(0, &mut ctx)?; let struct_casted = ConstantArray::new(src.clone(), 1) .into_array() - .execute::(&mut ctx)? + .execute::(&mut ctx)? .into_array() .cast(reordered_dtype)? .execute_scalar(0, &mut ctx)?; @@ -601,7 +628,7 @@ mod tests { assert!(renamed.as_struct().field("y").unwrap().is_null()); let struct_renamed = ConstantArray::new(src.clone(), 1) .into_array() - .execute::(&mut ctx)? + .execute::(&mut ctx)? .into_array() .cast(renamed_nullable)? .execute_scalar(0, &mut ctx)?; @@ -668,6 +695,74 @@ mod tests { // Direct StructScalar::cast on null to non-nullable struct returns Err instead of panicking. assert!(null_struct.as_struct().cast(&added_nonnull).is_err()); + + // Repeated field names match by occurrence rather than overwriting later occurrences. + let dup_src_dtype = DType::Struct( + StructFields::new( + ["x", "x", "old"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::Nullable), + ], + ), + Nullability::NonNullable, + ); + let dup_dst_dtype = DType::Struct( + StructFields::new( + ["x", "x", "new"].into(), + vec![ + DType::Primitive(PType::I64, Nullability::NonNullable), + DType::Primitive(PType::I64, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::Nullable), + ], + ), + Nullability::NonNullable, + ); + let dup_src = Scalar::struct_( + dup_src_dtype, + [ + Scalar::from(1_i32), + Scalar::from(2_i32), + Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), + ], + ); + let dup_scalar = dup_src.cast(&dup_dst_dtype)?; + let dup_fields = dup_scalar + .as_struct() + .fields_iter() + .vortex_expect("non-null") + .collect::>(); + assert_eq!( + dup_fields, + vec![ + Scalar::from(1_i64), + Scalar::from(2_i64), + Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), + ] + ); + let dup_arr = ConstantArray::new(dup_src.clone(), 1) + .into_array() + .execute::(&mut ctx)? + .into_array() + .cast(dup_dst_dtype)? + .execute::(&mut ctx)? + .into_array(); + assert_eq!(dup_arr.execute_scalar(0, &mut ctx)?, dup_scalar); + + // An extra non-nullable occurrence of an existing name is treated as an added field. + let dup_extra_nonnull = DType::Struct( + StructFields::new( + ["x", "x", "x"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::NonNullable), + ], + ), + Nullability::NonNullable, + ); + assert!(dup_src.cast(&dup_extra_nonnull).is_err()); Ok(()) } diff --git a/vortex-array/src/scalar_fn/builtin/cast/mod.rs b/vortex-array/src/scalar_fn/builtin/cast/mod.rs index b5011d0f833..ceeb22faccc 100644 --- a/vortex-array/src/scalar_fn/builtin/cast/mod.rs +++ b/vortex-array/src/scalar_fn/builtin/cast/mod.rs @@ -113,8 +113,11 @@ fn check_struct_extension_cast(source: &StructFields, target: &StructFields) -> return Ok(()); } - for (name, target) in target.names().iter().zip(target.fields()) { - if let Some(source) = source.field(name) { + for (src_idx, target) in crate::scalar::map_struct_cast_fields(source, target) + .into_iter() + .zip(target.fields()) + { + if let Some(source) = src_idx.and_then(|i| source.field_by_index(i)) { check_extension_cast(&source, &target)?; } } From 3bbd3b5804119752da9dfa404de1e0f1afef444f Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 20:10:04 +0000 Subject: [PATCH 4/9] Recursively validate nested struct added fields on null scalar casts Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../fns/all_non_distinct/tests.rs | 2 +- vortex-array/src/scalar/typed_view/struct_.rs | 110 ++++++++++++++++-- 2 files changed, 104 insertions(+), 8 deletions(-) diff --git a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs index ab5a4aaf5e1..0ed40caef44 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_distinct/tests.rs @@ -627,7 +627,7 @@ fn list_different_lengths_same_flattened_elements() -> VortexResult<()> { } #[test] -fn long_array_mismatch_at_last_row() -> VortexResult<()> { +fn test_all_non_distinct_long_array_mismatch_at_last_row() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let base: Vec = (0..1000).collect(); let mut diff = base.clone(); diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index bd5e9423054..72848cefa3f 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -325,23 +325,46 @@ pub(crate) fn map_struct_cast_fields( .collect() } -/// Checks that any target struct field absent from `source` is nullable, matching +/// Recursively checks that any target struct field absent from `source` is nullable, matching /// [`struct_cast_fields`](crate::arrays::struct_::compute::cast::struct_cast_fields). pub(crate) fn check_struct_cast_added_fields( source: &StructFields, target: &StructFields, ) -> VortexResult<()> { - if source.names() != target.names() { - for (src_idx, target_dtype) in map_struct_cast_fields(source, target) - .into_iter() - .zip(target.fields()) - { - if src_idx.is_none() { + if source.names() == target.names() { + for (src_dtype, target_dtype) in source.fields().zip(target.fields()) { + if let (Some(src_child), Some(target_child)) = ( + src_dtype.as_struct_fields_opt(), + target_dtype.as_struct_fields_opt(), + ) { + check_struct_cast_added_fields(src_child, target_child)?; + } + } + return Ok(()); + } + + for (src_idx, target_dtype) in map_struct_cast_fields(source, target) + .into_iter() + .zip(target.fields()) + { + match src_idx { + None => { vortex_ensure!( target_dtype.is_nullable(), "CAST for struct only supports added nullable fields" ); } + Some(i) => { + let src_dtype = source + .field_by_index(i) + .vortex_expect("valid source field index"); + if let (Some(src_child), Some(target_child)) = ( + src_dtype.as_struct_fields_opt(), + target_dtype.as_struct_fields_opt(), + ) { + check_struct_cast_added_fields(src_child, target_child)?; + } + } } } Ok(()) @@ -410,6 +433,7 @@ mod tests { use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::ConstantArray; + use crate::arrays::struct_::StructArrayExt; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::Nullability; @@ -763,6 +787,78 @@ mod tests { Nullability::NonNullable, ); assert!(dup_src.cast(&dup_extra_nonnull).is_err()); + + // Null outer struct recursively validates added non-nullable fields in nested child structs. + let nested_src_dtype = DType::struct_( + [( + "inner", + DType::struct_( + [("x", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + ), + )], + Nullability::Nullable, + ); + let nested_dst_dtype = DType::struct_( + [( + "inner", + DType::Struct( + StructFields::new( + ["x", "x"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I32, Nullability::NonNullable), + ], + ), + Nullability::NonNullable, + ), + )], + Nullability::Nullable, + ); + let nested_null = Scalar::null(nested_src_dtype); + let scalar_err = nested_null.cast(&nested_dst_dtype).unwrap_err(); + assert!( + scalar_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{scalar_err}" + ); + let const_err = ConstantArray::new(nested_null.clone(), 1) + .into_array() + .cast(nested_dst_dtype.clone()) + .and_then(|a| a.execute::(&mut ctx)) + .and_then(|c| { + c.into_struct() + .unmasked_field(0) + .clone() + .execute::(&mut ctx) + }) + .unwrap_err(); + let mat_err = ConstantArray::new(nested_null, 1) + .into_array() + .execute::(&mut ctx)? + .into_array() + .cast(nested_dst_dtype) + .and_then(|a| a.execute::(&mut ctx)) + .and_then(|c| { + c.into_struct() + .unmasked_field(0) + .clone() + .execute::(&mut ctx) + }) + .unwrap_err(); + assert!( + const_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{const_err}" + ); + assert!( + mat_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{mat_err}" + ); Ok(()) } From 978fbea64b01e46c870b5a1c5b09698d09f3c9e9 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 20:15:17 +0000 Subject: [PATCH 5/9] Validate added struct fields across containers and propagate from Constant::cast Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../src/arrays/constant/compute/cast.rs | 2 + vortex-array/src/scalar/cast.rs | 7 +- vortex-array/src/scalar/typed_view/struct_.rs | 112 +++++++++++------- 3 files changed, 71 insertions(+), 50 deletions(-) diff --git a/vortex-array/src/arrays/constant/compute/cast.rs b/vortex-array/src/arrays/constant/compute/cast.rs index 60c7ecd8d3c..55bc3acab17 100644 --- a/vortex-array/src/arrays/constant/compute/cast.rs +++ b/vortex-array/src/arrays/constant/compute/cast.rs @@ -9,10 +9,12 @@ use crate::array::ArrayView; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::dtype::DType; +use crate::scalar::check_struct_cast_added_fields; use crate::scalar_fn::builtin::cast::CastReduce; impl CastReduce for Constant { fn cast(array: ArrayView<'_, Constant>, dtype: &DType) -> VortexResult> { + check_struct_cast_added_fields(array.dtype(), dtype)?; match array.scalar().cast(dtype) { Ok(scalar) => Ok(Some(ConstantArray::new(scalar, array.len()).into_array())), Err(_) => Ok(None), diff --git a/vortex-array/src/scalar/cast.rs b/vortex-array/src/scalar/cast.rs index ce24a1a55c1..88665de266e 100644 --- a/vortex-array/src/scalar/cast.rs +++ b/vortex-array/src/scalar/cast.rs @@ -61,12 +61,7 @@ impl Scalar { // Cast nulls after checking the extension dtype restrictions. if self.value().is_none() || matches!(self.dtype(), DType::Null) { - if let (Some(source), Some(target)) = ( - self.dtype().as_struct_fields_opt(), - target_dtype.as_struct_fields_opt(), - ) { - check_struct_cast_added_fields(source, target)?; - } + check_struct_cast_added_fields(self.dtype(), target_dtype)?; vortex_ensure!( target_dtype.is_nullable(), "Cannot cast null to {target_dtype}: target type is non-nullable" diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index 72848cefa3f..feada493f0e 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -218,7 +218,7 @@ impl<'a> StructScalar<'a> { let own_st = self.struct_fields(); let Some(fs) = self.fields else { - check_struct_cast_added_fields(own_st, st)?; + check_struct_cast_added_fields(self.dtype(), dtype)?; return Scalar::try_new(dtype.clone(), None); }; @@ -325,47 +325,49 @@ pub(crate) fn map_struct_cast_fields( .collect() } -/// Recursively checks that any target struct field absent from `source` is nullable, matching +/// Recursively checks that any target struct field absent from `source` (including inside +/// nested structs, lists, fixed-size lists, and maps) is nullable, matching /// [`struct_cast_fields`](crate::arrays::struct_::compute::cast::struct_cast_fields). -pub(crate) fn check_struct_cast_added_fields( - source: &StructFields, - target: &StructFields, -) -> VortexResult<()> { - if source.names() == target.names() { - for (src_dtype, target_dtype) in source.fields().zip(target.fields()) { - if let (Some(src_child), Some(target_child)) = ( - src_dtype.as_struct_fields_opt(), - target_dtype.as_struct_fields_opt(), - ) { - check_struct_cast_added_fields(src_child, target_child)?; - } - } - return Ok(()); - } - - for (src_idx, target_dtype) in map_struct_cast_fields(source, target) - .into_iter() - .zip(target.fields()) - { - match src_idx { - None => { - vortex_ensure!( - target_dtype.is_nullable(), - "CAST for struct only supports added nullable fields" - ); - } - Some(i) => { - let src_dtype = source - .field_by_index(i) - .vortex_expect("valid source field index"); - if let (Some(src_child), Some(target_child)) = ( - src_dtype.as_struct_fields_opt(), - target_dtype.as_struct_fields_opt(), - ) { - check_struct_cast_added_fields(src_child, target_child)?; +pub(crate) fn check_struct_cast_added_fields(source: &DType, target: &DType) -> VortexResult<()> { + match (source, target) { + (DType::Struct(src_fields, _), DType::Struct(target_fields, _)) => { + if src_fields.names() == target_fields.names() { + for (src_dtype, target_dtype) in src_fields.fields().zip(target_fields.fields()) { + check_struct_cast_added_fields(&src_dtype, &target_dtype)?; + } + } else { + for (src_idx, target_dtype) in map_struct_cast_fields(src_fields, target_fields) + .into_iter() + .zip(target_fields.fields()) + { + match src_idx { + None => { + vortex_ensure!( + target_dtype.is_nullable(), + "CAST for struct only supports added nullable fields" + ); + } + Some(i) => { + let src_dtype = src_fields + .field_by_index(i) + .vortex_expect("valid source field index"); + check_struct_cast_added_fields(&src_dtype, &target_dtype)?; + } + } } } } + (DType::List(src_elem, _), DType::List(dst_elem, _)) + | (DType::FixedSizeList(src_elem, ..), DType::FixedSizeList(dst_elem, ..)) + | (DType::List(src_elem, _), DType::FixedSizeList(dst_elem, ..)) + | (DType::FixedSizeList(src_elem, ..), DType::List(dst_elem, ..)) => { + check_struct_cast_added_fields(src_elem, dst_elem)?; + } + (DType::Map(src_map, _), DType::Map(dst_map, _)) => { + check_struct_cast_added_fields(&src_map.key_dtype(), &dst_map.key_dtype())?; + check_struct_cast_added_fields(&src_map.value_dtype(), &dst_map.value_dtype())?; + } + _ => {} } Ok(()) } @@ -424,6 +426,7 @@ impl Scalar { #[cfg(test)] mod tests { use std::hash::DefaultHasher; + use std::sync::Arc; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -823,16 +826,11 @@ mod tests { .contains("CAST for struct only supports added nullable fields"), "{scalar_err}" ); + // ConstantArray::cast propagates the added-field error directly without materializing. let const_err = ConstantArray::new(nested_null.clone(), 1) .into_array() .cast(nested_dst_dtype.clone()) .and_then(|a| a.execute::(&mut ctx)) - .and_then(|c| { - c.into_struct() - .unmasked_field(0) - .clone() - .execute::(&mut ctx) - }) .unwrap_err(); let mat_err = ConstantArray::new(nested_null, 1) .into_array() @@ -859,6 +857,32 @@ mod tests { .contains("CAST for struct only supports added nullable fields"), "{mat_err}" ); + + // Container-nested structs (e.g. List) are also validated on null scalars. + let list_src = Scalar::null(DType::List( + Arc::new(DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + )), + Nullability::Nullable, + )); + let list_dst = DType::List( + Arc::new(DType::struct_( + [ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I32, Nullability::NonNullable)), + ], + Nullability::NonNullable, + )), + Nullability::Nullable, + ); + let list_err = list_src.cast(&list_dst).unwrap_err(); + assert!( + list_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{list_err}" + ); Ok(()) } From 9b7379805c6b6f262d5586107285993d178d6a44 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 20:18:06 +0000 Subject: [PATCH 6/9] Validate added struct fields before non-null scalar dispatch Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/scalar/cast.rs | 3 ++- vortex-array/src/scalar/typed_view/struct_.rs | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/vortex-array/src/scalar/cast.rs b/vortex-array/src/scalar/cast.rs index 88665de266e..f6c7998af4c 100644 --- a/vortex-array/src/scalar/cast.rs +++ b/vortex-array/src/scalar/cast.rs @@ -59,9 +59,10 @@ impl Scalar { )); } + check_struct_cast_added_fields(self.dtype(), target_dtype)?; + // Cast nulls after checking the extension dtype restrictions. if self.value().is_none() || matches!(self.dtype(), DType::Null) { - check_struct_cast_added_fields(self.dtype(), target_dtype)?; vortex_ensure!( target_dtype.is_nullable(), "Cannot cast null to {target_dtype}: target type is non-nullable" diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index feada493f0e..9649e759d38 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -883,6 +883,32 @@ mod tests { .contains("CAST for struct only supports added nullable fields"), "{list_err}" ); + // Non-null empty collections also reject added non-nullable struct fields consistently. + let empty_list = Scalar::list_empty( + Arc::new(DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::NonNullable))], + Nullability::NonNullable, + )), + Nullability::NonNullable, + ); + let empty_scalar_err = empty_list.cast(&list_dst).unwrap_err(); + let empty_const_err = ConstantArray::new(empty_list, 1) + .into_array() + .cast(list_dst) + .and_then(|a| a.execute::(&mut ctx)) + .unwrap_err(); + assert!( + empty_scalar_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{empty_scalar_err}" + ); + assert!( + empty_const_err + .to_string() + .contains("CAST for struct only supports added nullable fields"), + "{empty_const_err}" + ); Ok(()) } From 529378a59ab8ac4cd296ddd5878c373438708f96 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 20:39:59 +0000 Subject: [PATCH 7/9] Split nested struct cast test to satisfy clippy cognitive complexity Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/scalar/typed_view/struct_.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index 9649e759d38..7dc4b3ce390 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -790,6 +790,12 @@ mod tests { Nullability::NonNullable, ); assert!(dup_src.cast(&dup_extra_nonnull).is_err()); + Ok(()) + } + + #[test] + fn test_struct_cast_added_fields_nested_and_containers() -> VortexResult<()> { + let mut ctx = VortexSession::empty().create_execution_ctx(); // Null outer struct recursively validates added non-nullable fields in nested child structs. let nested_src_dtype = DType::struct_( From 9604f6349604351d247ce8d0ac54650349914f5c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sun, 29 Nov 2026 21:42:31 +0000 Subject: [PATCH 8/9] Only run recursive added-field check on null scalars and empty collections Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/scalar/cast.rs | 3 +-- vortex-array/src/scalar/typed_view/list.rs | 13 +++++++++++-- vortex-array/src/scalar/typed_view/map.rs | 10 ++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/vortex-array/src/scalar/cast.rs b/vortex-array/src/scalar/cast.rs index f6c7998af4c..88665de266e 100644 --- a/vortex-array/src/scalar/cast.rs +++ b/vortex-array/src/scalar/cast.rs @@ -59,10 +59,9 @@ impl Scalar { )); } - check_struct_cast_added_fields(self.dtype(), target_dtype)?; - // Cast nulls after checking the extension dtype restrictions. if self.value().is_none() || matches!(self.dtype(), DType::Null) { + check_struct_cast_added_fields(self.dtype(), target_dtype)?; vortex_ensure!( target_dtype.is_nullable(), "Cannot cast null to {target_dtype}: target type is non-nullable" diff --git a/vortex-array/src/scalar/typed_view/list.rs b/vortex-array/src/scalar/typed_view/list.rs index 1890ce14b7d..c4d9611a3d8 100644 --- a/vortex-array/src/scalar/typed_view/list.rs +++ b/vortex-array/src/scalar/typed_view/list.rs @@ -213,11 +213,20 @@ impl<'a> ListScalar<'a> { ) } + let elements = self + .elements + .ok_or_else(|| vortex_err!("nullness should be handled in Scalar::cast"))?; + if elements.is_empty() { + crate::scalar::check_struct_cast_added_fields( + self.element_dtype.as_ref(), + target_element_dtype, + )?; + } + Scalar::try_new( dtype.clone(), Some(ScalarValue::Tuple( - self.elements - .ok_or_else(|| vortex_err!("nullness should be handled in Scalar::cast"))? + elements .iter() .map(|element| { // Recursively cast the elements of the list. diff --git a/vortex-array/src/scalar/typed_view/map.rs b/vortex-array/src/scalar/typed_view/map.rs index fd49f999325..4890765b31b 100644 --- a/vortex-array/src/scalar/typed_view/map.rs +++ b/vortex-array/src/scalar/typed_view/map.rs @@ -165,6 +165,16 @@ impl<'a> MapScalar<'a> { let target_key = target.key_dtype(); let target_value = target.value_dtype(); + if entries.is_empty() { + crate::scalar::check_struct_cast_added_fields( + &self.map_dtype().key_dtype(), + &target_key, + )?; + crate::scalar::check_struct_cast_added_fields( + &self.map_dtype().value_dtype(), + &target_value, + )?; + } let entries = entries .iter() .map(|entry| { From f9e8241ec26c1d57bda67a02a9cba9601c15a489 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 30 Nov 2026 01:38:56 +0000 Subject: [PATCH 9/9] Index source field positions once in map_struct_cast_fields Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/scalar/typed_view/struct_.rs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/vortex-array/src/scalar/typed_view/struct_.rs b/vortex-array/src/scalar/typed_view/struct_.rs index 7dc4b3ce390..d3da951b943 100644 --- a/vortex-array/src/scalar/typed_view/struct_.rs +++ b/vortex-array/src/scalar/typed_view/struct_.rs @@ -10,12 +10,14 @@ use std::hash::Hash; use std::hash::Hasher; use itertools::Itertools; +use smallvec::SmallVec; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_error::vortex_panic; +use vortex_utils::aliases::hash_map::HashMap; use crate::dtype::DType; use crate::dtype::FieldName; @@ -306,22 +308,15 @@ pub(crate) fn map_struct_cast_fields( source: &StructFields, target: &StructFields, ) -> Vec> { - let mut used = vec![false; source.nfields()]; + let mut positions: HashMap<&FieldName, SmallVec<[usize; 1]>> = + HashMap::with_capacity(source.nfields()); + for (i, name) in source.names().as_ref().iter().enumerate().rev() { + positions.entry(name).or_default().push(i); + } target .names() .iter() - .map(|target_name| { - let src_idx = source - .names() - .iter() - .enumerate() - .find(|&(i, name)| !used[i] && name == target_name) - .map(|(i, _)| i); - if let Some(i) = src_idx { - used[i] = true; - } - src_idx - }) + .map(|target_name| positions.get_mut(target_name).and_then(SmallVec::pop)) .collect() }