Skip to main content

vortex_array/compute/conformance/
consistency.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! # Array Consistency Tests
5//!
6//! This module contains tests that verify consistency between related compute operations
7//! on Vortex arrays. These tests ensure that different ways of achieving the same result
8//! produce identical outputs.
9//!
10//! ## Test Categories
11//!
12//! - **Filter/Take Consistency**: Verifies that filtering with a mask produces the same
13//!   result as taking with the indices where the mask is true.
14//! - **Mask Composition**: Ensures that applying multiple masks sequentially produces
15//!   the same result as applying a combined mask.
16//! - **Identity Operations**: Tests that operations with identity inputs (all-true masks,
17//!   sequential indices) preserve the original array.
18//! - **Null Handling**: Verifies consistent behavior when operations introduce or
19//!   interact with null values.
20//! - **Edge Cases**: Tests empty arrays, single elements, and boundary conditions.
21
22use std::sync::Arc;
23
24use vortex_buffer::BitBuffer;
25use vortex_error::VortexExpect;
26use vortex_error::vortex_panic;
27use vortex_mask::Mask;
28
29use crate::ArrayRef;
30use crate::IntoArray;
31use crate::LEGACY_SESSION;
32use crate::VortexSessionExecute;
33use crate::arrays::BoolArray;
34use crate::arrays::PrimitiveArray;
35use crate::builtins::ArrayBuiltins;
36use crate::dtype::DType;
37use crate::dtype::Nullability;
38use crate::dtype::PType;
39use crate::scalar_fn::fns::operators::Operator;
40
41/// Tests that filter and take operations produce consistent results.
42///
43/// # Invariant
44/// `filter(array, mask)` should equal `take(array, indices_where_mask_is_true)`
45///
46/// # Test Details
47/// - Creates a mask that keeps elements where index % 3 != 1
48/// - Applies filter with this mask
49/// - Creates indices array containing positions where mask is true
50/// - Applies take with these indices
51/// - Verifies both results are identical
52fn test_filter_take_consistency(array: &ArrayRef) {
53    let len = array.len();
54    if len == 0 {
55        return;
56    }
57
58    // Create a test mask (keep elements where index % 3 != 1)
59    let mask_pattern: BitBuffer = (0..len).map(|i| i % 3 != 1).collect();
60    let mask = Mask::from_buffer(mask_pattern.clone());
61
62    // Filter the array
63    let filtered = array
64        .filter(mask)
65        .vortex_expect("filter should succeed in conformance test");
66
67    // Create indices where mask is true
68    let indices: Vec<u64> = mask_pattern
69        .iter()
70        .enumerate()
71        .filter_map(|(i, v)| v.then_some(i as u64))
72        .collect();
73    let indices_array = PrimitiveArray::from_iter(indices).into_array();
74
75    // Take using those indices
76    let taken = array
77        .take(indices_array)
78        .vortex_expect("take should succeed in conformance test");
79
80    // Results should be identical
81    assert_eq!(
82        filtered.len(),
83        taken.len(),
84        "Filter and take should produce arrays of the same length. \
85         Filtered length: {}, Taken length: {}",
86        filtered.len(),
87        taken.len()
88    );
89
90    for i in 0..filtered.len() {
91        let filtered_val = filtered
92            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
93            .vortex_expect("scalar_at should succeed in conformance test");
94        let taken_val = taken
95            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
96            .vortex_expect("scalar_at should succeed in conformance test");
97        assert_eq!(
98            filtered_val, taken_val,
99            "Filter and take produced different values at index {i}. \
100             Filtered value: {filtered_val:?}, Taken value: {taken_val:?}"
101        );
102    }
103}
104
105/// Tests that double masking is consistent with combined mask.
106///
107/// # Invariant
108/// `mask(mask(array, mask1), mask2)` should equal `mask(array, mask1 | mask2)`
109///
110/// # Test Details
111/// - Creates two masks: mask1 (every 3rd element) and mask2 (every 2nd element)
112/// - Applies masks sequentially: first mask1, then mask2 on the result
113/// - Creates a combined mask using OR operation (element is masked if either mask is true)
114/// - Applies the combined mask directly to the original array
115/// - Verifies both approaches produce identical results
116///
117/// # Why This Matters
118/// This test ensures that mask operations compose correctly, which is critical for
119/// complex query operations that may apply multiple filters.
120fn test_double_mask_consistency(array: &ArrayRef) {
121    let len = array.len();
122    if len == 0 {
123        return;
124    }
125
126    // Create two different mask patterns
127    let mask1: Mask = (0..len).map(|i| i % 3 == 0).collect();
128    let mask2: Mask = (0..len).map(|i| i % 2 == 0).collect();
129
130    // Apply masks sequentially
131    let first_masked = array
132        .clone()
133        .mask((!&mask1).into_array())
134        .vortex_expect("mask should succeed in conformance test");
135    let double_masked = first_masked
136        .mask((!&mask2).into_array())
137        .vortex_expect("mask should succeed in conformance test");
138
139    // Create combined mask (OR operation - element is masked if EITHER mask is true)
140    let combined_pattern: BitBuffer = mask1
141        .to_bit_buffer()
142        .iter()
143        .zip(mask2.to_bit_buffer().iter())
144        .map(|(a, b)| a || b)
145        .collect();
146    let combined_mask = Mask::from_buffer(combined_pattern);
147
148    // Apply combined mask directly
149    let directly_masked = array
150        .clone()
151        .mask((!&combined_mask).into_array())
152        .vortex_expect("mask should succeed in conformance test");
153
154    // Results should be identical
155    assert_eq!(
156        double_masked.len(),
157        directly_masked.len(),
158        "Sequential masking and combined masking should produce arrays of the same length. \
159         Sequential length: {}, Combined length: {}",
160        double_masked.len(),
161        directly_masked.len()
162    );
163
164    for i in 0..double_masked.len() {
165        let double_val = double_masked
166            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
167            .vortex_expect("scalar_at should succeed in conformance test");
168        let direct_val = directly_masked
169            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
170            .vortex_expect("scalar_at should succeed in conformance test");
171        assert_eq!(
172            double_val, direct_val,
173            "Sequential masking and combined masking produced different values at index {i}. \
174             Sequential masking value: {double_val:?}, Combined masking value: {direct_val:?}\n\
175             This likely indicates an issue with how masks are composed in the array implementation."
176        );
177    }
178}
179
180/// Tests that filtering with an all-true mask preserves the array.
181///
182/// # Invariant
183/// `filter(array, all_true_mask)` should equal `array`
184///
185/// # Test Details
186/// - Creates a mask with all elements set to true
187/// - Applies filter with this mask
188/// - Verifies the result is identical to the original array
189///
190/// # Why This Matters
191/// This is an identity operation that should be optimized in implementations
192/// to avoid unnecessary copying.
193fn test_filter_identity(array: &ArrayRef) {
194    let len = array.len();
195    if len == 0 {
196        return;
197    }
198
199    let all_true_mask = Mask::new_true(len);
200    let filtered = array
201        .filter(all_true_mask)
202        .vortex_expect("filter should succeed in conformance test");
203
204    // Filtered array should be identical to original
205    assert_eq!(
206        filtered.len(),
207        array.len(),
208        "Filtering with all-true mask should preserve array length. \
209         Original length: {}, Filtered length: {}",
210        array.len(),
211        filtered.len()
212    );
213
214    for i in 0..len {
215        let original_val = array
216            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
217            .vortex_expect("scalar_at should succeed in conformance test");
218        let filtered_val = filtered
219            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
220            .vortex_expect("scalar_at should succeed in conformance test");
221        assert_eq!(
222            filtered_val, original_val,
223            "Filtering with all-true mask should preserve all values. \
224             Value at index {i} changed from {original_val:?} to {filtered_val:?}"
225        );
226    }
227}
228
229/// Tests that masking with an all-false mask preserves values while making them nullable.
230///
231/// # Invariant
232/// `mask(array, all_false_mask)` should have same values as `array` but with nullable type
233///
234/// # Test Details
235/// - Creates a mask with all elements set to false (no elements are nullified)
236/// - Applies mask operation
237/// - Verifies all values are preserved but the array type becomes nullable
238///
239/// # Why This Matters
240/// Masking always produces a nullable array, even when no values are actually masked.
241/// This test ensures the type system handles this correctly.
242fn test_mask_identity(array: &ArrayRef) {
243    let len = array.len();
244    if len == 0 {
245        return;
246    }
247
248    let all_false_mask = Mask::new_false(len);
249    let masked = array
250        .clone()
251        .mask((!&all_false_mask).into_array())
252        .vortex_expect("mask should succeed in conformance test");
253
254    // Masked array should have same values (just nullable)
255    assert_eq!(
256        masked.len(),
257        array.len(),
258        "Masking with all-false mask should preserve array length. \
259         Original length: {}, Masked length: {}",
260        array.len(),
261        masked.len()
262    );
263
264    assert!(
265        masked.dtype().is_nullable(),
266        "Mask operation should always produce a nullable array, but dtype is {}",
267        masked.dtype()
268    );
269
270    for i in 0..len {
271        let original_val = array
272            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
273            .vortex_expect("scalar_at should succeed in conformance test");
274        let masked_val = masked
275            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
276            .vortex_expect("scalar_at should succeed in conformance test");
277        let expected_val = original_val.clone().into_nullable();
278        assert_eq!(
279            masked_val, expected_val,
280            "Masking with all-false mask should preserve values (as nullable). \
281             Value at index {i}: original = {original_val:?}, masked = {masked_val:?}, expected = {expected_val:?}"
282        );
283    }
284}
285
286/// Tests that slice and filter with contiguous mask produce same results.
287///
288/// # Invariant
289/// `filter(array, contiguous_true_mask)` should equal `slice(array, start, end)`
290///
291/// # Test Details
292/// - Creates a mask that is true only for indices 1, 2, and 3
293/// - Filters the array with this mask
294/// - Slices the array from index 1 to 4
295/// - Verifies both operations produce identical results
296///
297/// # Why This Matters
298/// When a filter mask represents a contiguous range, it should be equivalent to
299/// a slice operation. Some implementations may optimize this case.
300fn test_slice_filter_consistency(array: &ArrayRef) {
301    let len = array.len();
302    if len < 4 {
303        return; // Need at least 4 elements for meaningful test
304    }
305
306    // Create a contiguous mask (true from index 1 to 3)
307    let mut mask_pattern = vec![false; len];
308    mask_pattern[1..4.min(len)].fill(true);
309
310    let mask = Mask::from_iter(mask_pattern);
311    let filtered = array
312        .filter(mask)
313        .vortex_expect("filter should succeed in conformance test");
314
315    // Slice should produce the same result
316    let sliced = array
317        .slice(1..4.min(len))
318        .vortex_expect("slice should succeed in conformance test");
319
320    assert_eq!(
321        filtered.len(),
322        sliced.len(),
323        "Filter with contiguous mask and slice should produce same length. \
324         Filtered length: {}, Sliced length: {}",
325        filtered.len(),
326        sliced.len()
327    );
328
329    for i in 0..filtered.len() {
330        let filtered_val = filtered
331            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
332            .vortex_expect("scalar_at should succeed in conformance test");
333        let sliced_val = sliced
334            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
335            .vortex_expect("scalar_at should succeed in conformance test");
336        assert_eq!(
337            filtered_val, sliced_val,
338            "Filter with contiguous mask and slice produced different values at index {i}. \
339             Filtered value: {filtered_val:?}, Sliced value: {sliced_val:?}"
340        );
341    }
342}
343
344/// Tests that take with sequential indices equals slice.
345///
346/// # Invariant
347/// `take(array, [1, 2, 3, ...])` should equal `slice(array, 1, n)`
348///
349/// # Test Details
350/// - Creates indices array with sequential values [1, 2, 3]
351/// - Takes elements at these indices
352/// - Slices array from index 1 to 4
353/// - Verifies both operations produce identical results
354///
355/// # Why This Matters
356/// Sequential takes are a common pattern that can be optimized to slice operations.
357fn test_take_slice_consistency(array: &ArrayRef) {
358    let len = array.len();
359    if len < 3 {
360        return; // Need at least 3 elements
361    }
362
363    // Take indices [1, 2, 3]
364    let end = 4.min(len);
365    let indices = PrimitiveArray::from_iter((1..end).map(|i| i as u64)).into_array();
366    let taken = array
367        .take(indices)
368        .vortex_expect("take should succeed in conformance test");
369
370    // Slice from 1 to end
371    let sliced = array
372        .slice(1..end)
373        .vortex_expect("slice should succeed in conformance test");
374
375    assert_eq!(
376        taken.len(),
377        sliced.len(),
378        "Take with sequential indices and slice should produce same length. \
379         Taken length: {}, Sliced length: {}",
380        taken.len(),
381        sliced.len()
382    );
383
384    for i in 0..taken.len() {
385        let taken_val = taken
386            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
387            .vortex_expect("scalar_at should succeed in conformance test");
388        let sliced_val = sliced
389            .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
390            .vortex_expect("scalar_at should succeed in conformance test");
391        assert_eq!(
392            taken_val, sliced_val,
393            "Take with sequential indices and slice produced different values at index {i}. \
394             Taken value: {taken_val:?}, Sliced value: {sliced_val:?}"
395        );
396    }
397}
398
399/// Tests that filter preserves relative ordering
400fn test_filter_preserves_order(array: &ArrayRef) {
401    let len = array.len();
402    if len < 4 {
403        return;
404    }
405
406    // Create a mask that selects elements at indices 0, 2, 3
407    let mask_pattern: Vec<bool> = (0..len).map(|i| i == 0 || i == 2 || i == 3).collect();
408    let mask = Mask::from_iter(mask_pattern);
409
410    let filtered = array
411        .filter(mask)
412        .vortex_expect("filter should succeed in conformance test");
413
414    // Verify the filtered array contains the right elements in order
415    assert_eq!(filtered.len(), 3.min(len));
416    if len >= 4 {
417        assert_eq!(
418            filtered
419                .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
420                .vortex_expect("scalar_at should succeed in conformance test"),
421            array
422                .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
423                .vortex_expect("scalar_at should succeed in conformance test")
424        );
425        assert_eq!(
426            filtered
427                .execute_scalar(1, &mut LEGACY_SESSION.create_execution_ctx())
428                .vortex_expect("scalar_at should succeed in conformance test"),
429            array
430                .execute_scalar(2, &mut LEGACY_SESSION.create_execution_ctx())
431                .vortex_expect("scalar_at should succeed in conformance test")
432        );
433        assert_eq!(
434            filtered
435                .execute_scalar(2, &mut LEGACY_SESSION.create_execution_ctx())
436                .vortex_expect("scalar_at should succeed in conformance test"),
437            array
438                .execute_scalar(3, &mut LEGACY_SESSION.create_execution_ctx())
439                .vortex_expect("scalar_at should succeed in conformance test")
440        );
441    }
442}
443
444/// Tests that take with repeated indices works correctly
445fn test_take_repeated_indices(array: &ArrayRef) {
446    let len = array.len();
447    if len == 0 {
448        return;
449    }
450
451    // Take the first element three times
452    let indices = PrimitiveArray::from_iter([0u64, 0, 0]).into_array();
453    let taken = array
454        .take(indices)
455        .vortex_expect("take should succeed in conformance test");
456
457    assert_eq!(taken.len(), 3);
458    for i in 0..3 {
459        assert_eq!(
460            taken
461                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
462                .vortex_expect("scalar_at should succeed in conformance test"),
463            array
464                .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
465                .vortex_expect("scalar_at should succeed in conformance test")
466        );
467    }
468}
469
470/// Tests mask and filter interaction with nulls
471fn test_mask_filter_null_consistency(array: &ArrayRef) {
472    let len = array.len();
473    if len < 3 {
474        return;
475    }
476
477    // First mask some elements
478    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 2 == 0).collect();
479    let mask_array = Mask::from_iter(mask_pattern);
480    let masked = array
481        .clone()
482        .mask((!&mask_array).into_array())
483        .vortex_expect("mask should succeed in conformance test");
484
485    // Then filter to remove the nulls
486    let filter_pattern: Vec<bool> = (0..len).map(|i| i % 2 != 0).collect();
487    let filter_mask = Mask::from_iter(filter_pattern);
488    let filtered = masked
489        .filter(filter_mask.clone())
490        .vortex_expect("filter should succeed in conformance test");
491
492    // This should be equivalent to directly filtering the original array
493    let direct_filtered = array
494        .filter(filter_mask)
495        .vortex_expect("filter should succeed in conformance test");
496
497    assert_eq!(filtered.len(), direct_filtered.len());
498    for i in 0..filtered.len() {
499        assert_eq!(
500            filtered
501                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
502                .vortex_expect("scalar_at should succeed in conformance test"),
503            direct_filtered
504                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
505                .vortex_expect("scalar_at should succeed in conformance test")
506        );
507    }
508}
509
510/// Tests that empty operations are consistent
511fn test_empty_operations_consistency(array: &ArrayRef) {
512    let len = array.len();
513
514    // Empty filter
515    let empty_filter = array
516        .filter(Mask::new_false(len))
517        .vortex_expect("filter should succeed in conformance test");
518    assert_eq!(empty_filter.len(), 0);
519    assert_eq!(empty_filter.dtype(), array.dtype());
520
521    // Empty take
522    let empty_indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable).into_array();
523    let empty_take = array
524        .take(empty_indices)
525        .vortex_expect("take should succeed in conformance test");
526    assert_eq!(empty_take.len(), 0);
527    assert_eq!(empty_take.dtype(), array.dtype());
528
529    // Empty slice (if array is non-empty)
530    if len > 0 {
531        let empty_slice = array
532            .slice(0..0)
533            .vortex_expect("slice should succeed in conformance test");
534        assert_eq!(empty_slice.len(), 0);
535        assert_eq!(empty_slice.dtype(), array.dtype());
536    }
537}
538
539/// Tests that take preserves array properties
540fn test_take_preserves_properties(array: &ArrayRef) {
541    let len = array.len();
542    if len == 0 {
543        return;
544    }
545
546    // Take all elements in original order
547    let indices = PrimitiveArray::from_iter((0..len).map(|i| i as u64)).into_array();
548    let taken = array
549        .take(indices)
550        .vortex_expect("take should succeed in conformance test");
551
552    // Should be identical to original
553    assert_eq!(taken.len(), array.len());
554    assert_eq!(taken.dtype(), array.dtype());
555    for i in 0..len {
556        assert_eq!(
557            taken
558                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
559                .vortex_expect("scalar_at should succeed in conformance test"),
560            array
561                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
562                .vortex_expect("scalar_at should succeed in conformance test")
563        );
564    }
565}
566
567/// Tests consistency with nullable indices.
568///
569/// # Invariant
570/// `take(array, [Some(0), None, Some(2)])` should produce `[array[0], null, array[2]]`
571///
572/// # Test Details
573/// - Creates an indices array with null at position 1: `[Some(0), None, Some(2)]`
574/// - Takes elements using these indices
575/// - Verifies that:
576///   - Position 0 contains the value from array index 0
577///   - Position 1 contains null
578///   - Position 2 contains the value from array index 2
579///   - The result array has nullable type
580///
581/// # Why This Matters
582/// Nullable indices are a powerful feature that allows introducing nulls during
583/// a take operation, which is useful for outer joins and similar operations.
584fn test_nullable_indices_consistency(array: &ArrayRef) {
585    let len = array.len();
586    if len < 3 {
587        return; // Need at least 3 elements to test indices 0 and 2
588    }
589
590    // Create nullable indices where some indices are null
591    let indices = PrimitiveArray::from_option_iter([Some(0u64), None, Some(2u64)]).into_array();
592
593    let taken = array
594        .take(indices)
595        .vortex_expect("take should succeed in conformance test");
596
597    // Result should have nulls where indices were null
598    assert_eq!(
599        taken.len(),
600        3,
601        "Take with nullable indices should produce array of length 3, got {}",
602        taken.len()
603    );
604
605    assert!(
606        taken.dtype().is_nullable(),
607        "Take with nullable indices should produce nullable array, but dtype is {:?}",
608        taken.dtype()
609    );
610
611    // Check first element (from index 0)
612    let expected_0 = array
613        .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
614        .vortex_expect("scalar_at should succeed in conformance test")
615        .into_nullable();
616    let actual_0 = taken
617        .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
618        .vortex_expect("scalar_at should succeed in conformance test");
619    assert_eq!(
620        actual_0, expected_0,
621        "Take with nullable indices: element at position 0 should be from array index 0. \
622         Expected: {expected_0:?}, Actual: {actual_0:?}"
623    );
624
625    // Check second element (should be null)
626    let actual_1 = taken
627        .execute_scalar(1, &mut LEGACY_SESSION.create_execution_ctx())
628        .vortex_expect("scalar_at should succeed in conformance test");
629    assert!(
630        actual_1.is_null(),
631        "Take with nullable indices: element at position 1 should be null, but got {actual_1:?}"
632    );
633
634    // Check third element (from index 2)
635    let expected_2 = array
636        .execute_scalar(2, &mut LEGACY_SESSION.create_execution_ctx())
637        .vortex_expect("scalar_at should succeed in conformance test")
638        .into_nullable();
639    let actual_2 = taken
640        .execute_scalar(2, &mut LEGACY_SESSION.create_execution_ctx())
641        .vortex_expect("scalar_at should succeed in conformance test");
642    assert_eq!(
643        actual_2, expected_2,
644        "Take with nullable indices: element at position 2 should be from array index 2. \
645         Expected: {expected_2:?}, Actual: {actual_2:?}"
646    );
647}
648
649/// Tests large array consistency
650fn test_large_array_consistency(array: &ArrayRef) {
651    let len = array.len();
652    if len < 1000 {
653        return;
654    }
655
656    // Test with every 10th element
657    let indices: Vec<u64> = (0..len).step_by(10).map(|i| i as u64).collect();
658    let indices_array = PrimitiveArray::from_iter(indices).into_array();
659    let taken = array
660        .take(indices_array)
661        .vortex_expect("take should succeed in conformance test");
662
663    // Create equivalent filter mask
664    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 10 == 0).collect();
665    let mask = Mask::from_iter(mask_pattern);
666    let filtered = array
667        .filter(mask)
668        .vortex_expect("filter should succeed in conformance test");
669
670    // Results should match
671    assert_eq!(taken.len(), filtered.len());
672    for i in 0..taken.len() {
673        assert_eq!(
674            taken
675                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
676                .vortex_expect("scalar_at should succeed in conformance test"),
677            filtered
678                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
679                .vortex_expect("scalar_at should succeed in conformance test")
680        );
681    }
682}
683
684/// Tests that comparison operations follow inverse relationships.
685///
686/// # Invariants
687/// - `compare(array, value, Eq)` is the inverse of `compare(array, value, NotEq)`
688/// - `compare(array, value, Gt)` is the inverse of `compare(array, value, Lte)`
689/// - `compare(array, value, Lt)` is the inverse of `compare(array, value, Gte)`
690///
691/// # Test Details
692/// - Creates comparison results for each operator
693/// - Verifies that inverse operations produce opposite boolean values
694/// - Tests with multiple scalar values to ensure consistency
695///
696/// # Why This Matters
697/// Comparison operations must maintain logical consistency across encodings.
698/// This test catches bugs where an encoding might implement one comparison
699/// correctly but fail on its logical inverse.
700fn test_comparison_inverse_consistency(array: &ArrayRef) {
701    let len = array.len();
702    if len == 0 {
703        return;
704    }
705
706    // Skip non-comparable types.
707    match array.dtype() {
708        DType::Null | DType::Extension(_) | DType::Struct(..) | DType::List(..) => return,
709        _ => {}
710    }
711
712    // Get a test value from the middle of the array
713    let test_scalar = if len == 0 {
714        return;
715    } else {
716        array
717            .execute_scalar(len / 2, &mut LEGACY_SESSION.create_execution_ctx())
718            .vortex_expect("scalar_at should succeed in conformance test")
719    };
720
721    // Test Eq vs NotEq
722    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
723    if let (Ok(eq_result), Ok(neq_result)) = (
724        array
725            .clone()
726            .binary(const_array.clone().into_array(), Operator::Eq),
727        array
728            .clone()
729            .binary(const_array.clone().into_array(), Operator::NotEq),
730    ) {
731        let inverted_eq = eq_result
732            .not()
733            .vortex_expect("not should succeed in conformance test");
734
735        assert_eq!(
736            inverted_eq.len(),
737            neq_result.len(),
738            "Inverted Eq should have same length as NotEq"
739        );
740
741        for i in 0..inverted_eq.len() {
742            let inv_val = inverted_eq
743                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
744                .vortex_expect("scalar_at should succeed in conformance test");
745            let neq_val = neq_result
746                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
747                .vortex_expect("scalar_at should succeed in conformance test");
748            assert_eq!(
749                inv_val, neq_val,
750                "At index {i}: NOT(Eq) should equal NotEq. \
751                 NOT(Eq) = {inv_val:?}, NotEq = {neq_val:?}"
752            );
753        }
754    }
755
756    // Test Gt vs Lte
757    if let (Ok(gt_result), Ok(lte_result)) = (
758        array
759            .clone()
760            .binary(const_array.clone().into_array(), Operator::Gt),
761        array
762            .clone()
763            .binary(const_array.clone().into_array(), Operator::Lte),
764    ) {
765        let inverted_gt = gt_result
766            .not()
767            .vortex_expect("not should succeed in conformance test");
768
769        for i in 0..inverted_gt.len() {
770            let inv_val = inverted_gt
771                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
772                .vortex_expect("scalar_at should succeed in conformance test");
773            let lte_val = lte_result
774                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
775                .vortex_expect("scalar_at should succeed in conformance test");
776            assert_eq!(
777                inv_val, lte_val,
778                "At index {i}: NOT(Gt) should equal Lte. \
779                 NOT(Gt) = {inv_val:?}, Lte = {lte_val:?}"
780            );
781        }
782    }
783
784    // Test Lt vs Gte
785    if let (Ok(lt_result), Ok(gte_result)) = (
786        array
787            .clone()
788            .binary(const_array.clone().into_array(), Operator::Lt),
789        array
790            .clone()
791            .binary(const_array.into_array(), Operator::Gte),
792    ) {
793        let inverted_lt = lt_result
794            .not()
795            .vortex_expect("not should succeed in conformance test");
796
797        for i in 0..inverted_lt.len() {
798            let inv_val = inverted_lt
799                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
800                .vortex_expect("scalar_at should succeed in conformance test");
801            let gte_val = gte_result
802                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
803                .vortex_expect("scalar_at should succeed in conformance test");
804            assert_eq!(
805                inv_val, gte_val,
806                "At index {i}: NOT(Lt) should equal Gte. \
807                 NOT(Lt) = {inv_val:?}, Gte = {gte_val:?}"
808            );
809        }
810    }
811}
812
813/// Tests that comparison operations maintain proper symmetry relationships.
814///
815/// # Invariants
816/// - `compare(array, value, Gt)` should equal `compare_scalar_array(value, array, Lt)`
817/// - `compare(array, value, Lt)` should equal `compare_scalar_array(value, array, Gt)`
818/// - `compare(array, value, Eq)` should equal `compare_scalar_array(value, array, Eq)`
819///
820/// # Test Details
821/// - Compares array-scalar operations with their symmetric scalar-array versions
822/// - Verifies that ordering relationships are properly reversed
823/// - Tests equality which should be symmetric
824///
825/// # Why This Matters
826/// Ensures that comparison operations maintain mathematical ordering properties
827/// regardless of operand order.
828fn test_comparison_symmetry_consistency(array: &ArrayRef) {
829    let len = array.len();
830    if len == 0 {
831        return;
832    }
833
834    // Skip non-comparable types.
835    match array.dtype() {
836        DType::Null | DType::Extension(_) | DType::Struct(..) | DType::List(..) => return,
837        _ => {}
838    }
839
840    // Get test values
841    let test_scalar = if len == 2 {
842        return;
843    } else {
844        array
845            .execute_scalar(len / 2, &mut LEGACY_SESSION.create_execution_ctx())
846            .vortex_expect("scalar_at should succeed in conformance test")
847    };
848
849    // Create a constant array with the test scalar for reverse comparison
850    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
851
852    // Test Gt vs Lt symmetry
853    if let (Ok(arr_gt_scalar), Ok(scalar_lt_arr)) = (
854        array
855            .clone()
856            .binary(const_array.clone().into_array(), Operator::Gt),
857        const_array
858            .clone()
859            .into_array()
860            .binary(array.clone(), Operator::Lt),
861    ) {
862        assert_eq!(
863            arr_gt_scalar.len(),
864            scalar_lt_arr.len(),
865            "Symmetric comparisons should have same length"
866        );
867
868        for i in 0..arr_gt_scalar.len() {
869            let arr_gt = arr_gt_scalar
870                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
871                .vortex_expect("scalar_at should succeed in conformance test");
872            let scalar_lt = scalar_lt_arr
873                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
874                .vortex_expect("scalar_at should succeed in conformance test");
875            assert_eq!(
876                arr_gt, scalar_lt,
877                "At index {i}: (array > scalar) should equal (scalar < array). \
878                 array > scalar = {arr_gt:?}, scalar < array = {scalar_lt:?}"
879            );
880        }
881    }
882
883    // Test Eq symmetry
884    if let (Ok(arr_eq_scalar), Ok(scalar_eq_arr)) = (
885        array
886            .clone()
887            .binary(const_array.clone().into_array(), Operator::Eq),
888        const_array.into_array().binary(array.clone(), Operator::Eq),
889    ) {
890        for i in 0..arr_eq_scalar.len() {
891            let arr_eq = arr_eq_scalar
892                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
893                .vortex_expect("scalar_at should succeed in conformance test");
894            let scalar_eq = scalar_eq_arr
895                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
896                .vortex_expect("scalar_at should succeed in conformance test");
897            assert_eq!(
898                arr_eq, scalar_eq,
899                "At index {i}: (array == scalar) should equal (scalar == array). \
900                 array == scalar = {arr_eq:?}, scalar == array = {scalar_eq:?}"
901            );
902        }
903    }
904}
905
906/// Tests that boolean operations follow De Morgan's laws.
907///
908/// # Invariants
909/// - `NOT(A AND B)` equals `(NOT A) OR (NOT B)`
910/// - `NOT(A OR B)` equals `(NOT A) AND (NOT B)`
911///
912/// # Test Details
913/// - If the array is boolean, uses it directly for testing boolean operations
914/// - Creates two boolean masks from patterns based on the array
915/// - Computes AND/OR operations and their inversions
916/// - Verifies De Morgan's laws hold for all elements
917///
918/// # Why This Matters
919/// Boolean operations must maintain logical consistency across encodings.
920/// This test catches bugs where encodings might optimize boolean operations
921/// incorrectly, breaking fundamental logical properties.
922fn test_boolean_demorgan_consistency(array: &ArrayRef) {
923    if !matches!(array.dtype(), DType::Bool(_)) {
924        return;
925    }
926
927    let bool_mask = {
928        let mask_pattern: Vec<bool> = (0..array.len()).map(|i| i % 3 == 0).collect();
929        BoolArray::from_iter(mask_pattern)
930    };
931    let bool_mask = bool_mask.into_array();
932
933    // Test first De Morgan's law: NOT(A AND B) = (NOT A) OR (NOT B)
934    if let (Ok(a_and_b), Ok(not_a), Ok(not_b)) = (
935        array.clone().binary(bool_mask.clone(), Operator::And),
936        array.not(),
937        bool_mask.not(),
938    ) {
939        let not_a_and_b = a_and_b
940            .not()
941            .vortex_expect("not should succeed in conformance test");
942        let not_a_or_not_b = not_a
943            .binary(not_b, Operator::Or)
944            .vortex_expect("or should succeed in conformance test");
945
946        assert_eq!(
947            not_a_and_b.len(),
948            not_a_or_not_b.len(),
949            "De Morgan's law results should have same length"
950        );
951
952        for i in 0..not_a_and_b.len() {
953            let left = not_a_and_b
954                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
955                .vortex_expect("scalar_at should succeed in conformance test");
956            let right = not_a_or_not_b
957                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
958                .vortex_expect("scalar_at should succeed in conformance test");
959            assert_eq!(
960                left, right,
961                "De Morgan's first law failed at index {i}: \
962                 NOT(A AND B) = {left:?}, (NOT A) OR (NOT B) = {right:?}"
963            );
964        }
965    }
966
967    // Test second De Morgan's law: NOT(A OR B) = (NOT A) AND (NOT B)
968    if let (Ok(a_or_b), Ok(not_a), Ok(not_b)) = (
969        array.clone().binary(bool_mask.clone(), Operator::Or),
970        array.not(),
971        bool_mask.not(),
972    ) {
973        let not_a_or_b = a_or_b
974            .not()
975            .vortex_expect("not should succeed in conformance test");
976        let not_a_and_not_b = not_a
977            .binary(not_b, Operator::And)
978            .vortex_expect("and should succeed in conformance test");
979
980        for i in 0..not_a_or_b.len() {
981            let left = not_a_or_b
982                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
983                .vortex_expect("scalar_at should succeed in conformance test");
984            let right = not_a_and_not_b
985                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
986                .vortex_expect("scalar_at should succeed in conformance test");
987            assert_eq!(
988                left, right,
989                "De Morgan's second law failed at index {i}: \
990                 NOT(A OR B) = {left:?}, (NOT A) AND (NOT B) = {right:?}"
991            );
992        }
993    }
994}
995
996/// Tests that slice and aggregate operations produce consistent results.
997///
998/// # Invariants
999/// - Aggregating a sliced array should equal aggregating the corresponding
1000///   elements from the canonical form
1001/// - This applies to sum, count, min/max, and other aggregate functions
1002///
1003/// # Test Details
1004/// - Slices the array and computes aggregates
1005/// - Compares against aggregating the canonical form's slice
1006/// - Tests multiple aggregate functions where applicable
1007///
1008/// # Why This Matters
1009/// Aggregate operations on sliced arrays must produce correct results
1010/// regardless of the underlying encoding's offset handling.
1011fn test_slice_aggregate_consistency(array: &ArrayRef) {
1012    use crate::aggregate_fn::fns::min_max::min_max;
1013    use crate::aggregate_fn::fns::nan_count::nan_count;
1014    use crate::aggregate_fn::fns::sum::sum;
1015    use crate::dtype::DType;
1016
1017    let mut ctx = LEGACY_SESSION.create_execution_ctx();
1018
1019    let len = array.len();
1020    if len < 5 {
1021        return; // Need enough elements for meaningful slice
1022    }
1023
1024    // Define slice bounds
1025    let start = 1;
1026    let end = (len - 1).min(start + 10); // Take up to 10 elements
1027
1028    // Get sliced array and canonical slice
1029    let sliced = array
1030        .slice(start..end)
1031        .vortex_expect("slice should succeed in conformance test");
1032    #[expect(deprecated)]
1033    let canonical = array.to_canonical().vortex_expect("to_canonical failed");
1034    let canonical_sliced = canonical
1035        .into_array()
1036        .slice(start..end)
1037        .vortex_expect("slice should succeed in conformance test");
1038
1039    // Test null count through invalid_count
1040    let sliced_invalid_count = sliced
1041        .invalid_count(&mut ctx)
1042        .vortex_expect("invalid_count should succeed in conformance test");
1043    let canonical_invalid_count = canonical_sliced
1044        .invalid_count(&mut ctx)
1045        .vortex_expect("invalid_count should succeed in conformance test");
1046    assert_eq!(
1047        sliced_invalid_count, canonical_invalid_count,
1048        "null_count on sliced array should match canonical. \
1049             Sliced: {sliced_invalid_count}, Canonical: {canonical_invalid_count}",
1050    );
1051
1052    // Test sum for numeric types
1053    if !matches!(array.dtype(), DType::Primitive(..)) {
1054        return;
1055    }
1056
1057    if let (Ok(slice_sum), Ok(canonical_sum)) =
1058        (sum(&sliced, &mut ctx), sum(&canonical_sliced, &mut ctx))
1059    {
1060        // Compare sum scalars
1061        assert_eq!(
1062            slice_sum, canonical_sum,
1063            "sum on sliced array should match canonical. \
1064                 Sliced: {slice_sum:?}, Canonical: {canonical_sum:?}"
1065        );
1066    }
1067
1068    // Test min_max
1069    if let (Ok(slice_minmax), Ok(canonical_minmax)) = (
1070        min_max(&sliced, &mut ctx),
1071        min_max(&canonical_sliced, &mut ctx),
1072    ) {
1073        match (slice_minmax, canonical_minmax) {
1074            (Some(s_result), Some(c_result)) => {
1075                assert_eq!(
1076                    s_result.min, c_result.min,
1077                    "min on sliced array should match canonical. \
1078                         Sliced: {:?}, Canonical: {:?}",
1079                    s_result.min, c_result.min
1080                );
1081                assert_eq!(
1082                    s_result.max, c_result.max,
1083                    "max on sliced array should match canonical. \
1084                         Sliced: {:?}, Canonical: {:?}",
1085                    s_result.max, c_result.max
1086                );
1087            }
1088            (None, None) => {} // Both empty, OK
1089            _ => vortex_panic!("min_max results don't match"),
1090        }
1091    }
1092
1093    // Test nan_count for floating point types
1094    if array.dtype().is_float()
1095        && let (Ok(slice_nan_count), Ok(canonical_nan_count)) = (
1096            nan_count(&sliced, &mut ctx),
1097            nan_count(&canonical_sliced, &mut ctx),
1098        )
1099    {
1100        assert_eq!(
1101            slice_nan_count, canonical_nan_count,
1102            "nan_count on sliced array should match canonical. \
1103                 Sliced: {slice_nan_count}, Canonical: {canonical_nan_count}"
1104        );
1105    }
1106}
1107
1108/// Tests that cast operations preserve array properties when sliced.
1109///
1110/// # Invariant
1111/// `cast(slice(array, start, end), dtype)` should equal `slice(cast(array, dtype), start, end)`
1112///
1113/// # Test Details
1114/// - Slices the array from index 2 to 7 (or len-2 if smaller)
1115/// - Casts the sliced array to a different type
1116/// - Compares against the canonical form of the array (without slicing or casting the canonical form)
1117/// - Verifies both approaches produce identical results
1118///
1119/// # Why This Matters
1120/// This test specifically catches bugs where encodings (like RunEndArray) fail to preserve
1121/// offset information during cast operations. Such bugs can lead to incorrect data being
1122/// returned after casting a sliced array.
1123fn test_cast_slice_consistency(array: &ArrayRef) {
1124    let len = array.len();
1125    if len < 5 {
1126        return; // Need at least 5 elements for meaningful slice
1127    }
1128
1129    // Define slice bounds
1130    let start = 2;
1131    let end = 7.min(len - 2).max(start + 1); // Ensure we have at least 1 element
1132
1133    // Get canonical form of the original array
1134    #[expect(deprecated)]
1135    let canonical = array.to_canonical().vortex_expect("to_canonical failed");
1136
1137    // Choose appropriate target dtype based on the array's type
1138    let target_dtypes = match array.dtype() {
1139        DType::Null => vec![],
1140        DType::Bool(nullability) => vec![
1141            DType::Primitive(PType::U8, *nullability),
1142            DType::Primitive(PType::I32, *nullability),
1143        ],
1144        DType::Primitive(ptype, nullability) => {
1145            let mut targets = vec![];
1146            // Test nullability changes
1147            let opposite_nullability = match nullability {
1148                Nullability::NonNullable => Nullability::Nullable,
1149                Nullability::Nullable => Nullability::NonNullable,
1150            };
1151            targets.push(DType::Primitive(*ptype, opposite_nullability));
1152
1153            // Test widening casts
1154            match ptype {
1155                PType::U8 => {
1156                    targets.push(DType::Primitive(PType::U16, *nullability));
1157                    targets.push(DType::Primitive(PType::I16, *nullability));
1158                }
1159                PType::U16 => {
1160                    targets.push(DType::Primitive(PType::U32, *nullability));
1161                    targets.push(DType::Primitive(PType::I32, *nullability));
1162                }
1163                PType::U32 => {
1164                    targets.push(DType::Primitive(PType::U64, *nullability));
1165                    targets.push(DType::Primitive(PType::I64, *nullability));
1166                }
1167                PType::U64 => {
1168                    targets.push(DType::Primitive(PType::F64, *nullability));
1169                }
1170                PType::I8 => {
1171                    targets.push(DType::Primitive(PType::I16, *nullability));
1172                    targets.push(DType::Primitive(PType::F32, *nullability));
1173                }
1174                PType::I16 => {
1175                    targets.push(DType::Primitive(PType::I32, *nullability));
1176                    targets.push(DType::Primitive(PType::F32, *nullability));
1177                }
1178                PType::I32 => {
1179                    targets.push(DType::Primitive(PType::I64, *nullability));
1180                    targets.push(DType::Primitive(PType::F64, *nullability));
1181                }
1182                PType::I64 => {
1183                    targets.push(DType::Primitive(PType::F64, *nullability));
1184                }
1185                PType::F16 => {
1186                    targets.push(DType::Primitive(PType::F32, *nullability));
1187                }
1188                PType::F32 => {
1189                    targets.push(DType::Primitive(PType::F64, *nullability));
1190                    targets.push(DType::Primitive(PType::I32, *nullability));
1191                }
1192                PType::F64 => {
1193                    targets.push(DType::Primitive(PType::I64, *nullability));
1194                }
1195            }
1196            targets
1197        }
1198        DType::Utf8(nullability) => {
1199            let opposite = match nullability {
1200                Nullability::NonNullable => Nullability::Nullable,
1201                Nullability::Nullable => Nullability::NonNullable,
1202            };
1203            vec![DType::Utf8(opposite), DType::Binary(*nullability)]
1204        }
1205        DType::Binary(nullability) => {
1206            let opposite = match nullability {
1207                Nullability::NonNullable => Nullability::Nullable,
1208                Nullability::Nullable => Nullability::NonNullable,
1209            };
1210            vec![
1211                DType::Binary(opposite),
1212                DType::Utf8(*nullability), // May fail if not valid UTF-8
1213            ]
1214        }
1215        DType::Decimal(decimal_type, nullability) => {
1216            let opposite = match nullability {
1217                Nullability::NonNullable => Nullability::Nullable,
1218                Nullability::Nullable => Nullability::NonNullable,
1219            };
1220            vec![DType::Decimal(*decimal_type, opposite)]
1221        }
1222        DType::Struct(fields, nullability) => {
1223            let opposite = match nullability {
1224                Nullability::NonNullable => Nullability::Nullable,
1225                Nullability::Nullable => Nullability::NonNullable,
1226            };
1227            vec![DType::Struct(fields.clone(), opposite)]
1228        }
1229        DType::List(element_type, nullability) => {
1230            let opposite = match nullability {
1231                Nullability::NonNullable => Nullability::Nullable,
1232                Nullability::Nullable => Nullability::NonNullable,
1233            };
1234            vec![DType::List(Arc::clone(element_type), opposite)]
1235        }
1236        DType::FixedSizeList(element_type, list_size, nullability) => {
1237            let opposite = match nullability {
1238                Nullability::NonNullable => Nullability::Nullable,
1239                Nullability::Nullable => Nullability::NonNullable,
1240            };
1241            vec![DType::FixedSizeList(
1242                Arc::clone(element_type),
1243                *list_size,
1244                opposite,
1245            )]
1246        }
1247        DType::Extension(_) => vec![], // Extension types typically only cast to themselves
1248        DType::Variant(_) => unimplemented!(),
1249    };
1250
1251    // Test each target dtype
1252    for target_dtype in target_dtypes {
1253        // Slice the array
1254        let sliced = array
1255            .slice(start..end)
1256            .vortex_expect("slice should succeed in conformance test");
1257
1258        // Try to cast the sliced array (force execution via to_canonical)
1259        let slice_then_cast = match sliced.cast(target_dtype.clone()).and_then(|a| {
1260            #[expect(deprecated)]
1261            a.to_canonical().map(|c| c.into_array())
1262        }) {
1263            Ok(result) => result,
1264            Err(_) => continue, // Skip if cast fails
1265        };
1266
1267        // Verify against canonical form
1268        assert_eq!(
1269            slice_then_cast.len(),
1270            end - start,
1271            "Sliced and casted array should have length {}, but has {}",
1272            end - start,
1273            slice_then_cast.len()
1274        );
1275
1276        // Compare each value against the canonical form
1277        for i in 0..slice_then_cast.len() {
1278            let slice_cast_val = slice_then_cast
1279                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
1280                .vortex_expect("scalar_at should succeed in conformance test");
1281
1282            // Get the corresponding value from the canonical array (adjusted for slice offset)
1283            let canonical_val = canonical
1284                .clone()
1285                .into_array()
1286                .execute_scalar(start + i, &mut LEGACY_SESSION.create_execution_ctx())
1287                .vortex_expect("scalar_at should succeed in conformance test");
1288
1289            // Cast the canonical scalar to the target dtype
1290            let expected_val = match canonical_val.cast(&target_dtype) {
1291                Ok(val) => val,
1292                Err(_) => {
1293                    // If scalar cast fails, we can't compare - skip this target dtype
1294                    // This can happen for some type conversions that aren't supported at scalar level
1295                    break;
1296                }
1297            };
1298
1299            assert_eq!(
1300                slice_cast_val,
1301                expected_val,
1302                "Cast of sliced array produced incorrect value at index {i}. \
1303                 Got: {slice_cast_val:?}, Expected: {expected_val:?} \
1304                 (canonical value at index {}: {canonical_val:?})\n\
1305                 This likely indicates the array encoding doesn't preserve offset information during cast.",
1306                start + i
1307            );
1308        }
1309
1310        // Also test the other way: cast then slice
1311        let casted = match array.clone().cast(target_dtype.clone()).and_then(|a| {
1312            #[expect(deprecated)]
1313            a.to_canonical().map(|c| c.into_array())
1314        }) {
1315            Ok(result) => result,
1316            Err(_) => continue, // Skip if cast fails
1317        };
1318        let cast_then_slice = casted
1319            .slice(start..end)
1320            .vortex_expect("slice should succeed in conformance test");
1321
1322        // Verify the two approaches produce identical results
1323        assert_eq!(
1324            slice_then_cast.len(),
1325            cast_then_slice.len(),
1326            "Slice-then-cast and cast-then-slice should produce arrays of the same length"
1327        );
1328
1329        for i in 0..slice_then_cast.len() {
1330            let slice_cast_val = slice_then_cast
1331                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
1332                .vortex_expect("scalar_at should succeed in conformance test");
1333            let cast_slice_val = cast_then_slice
1334                .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
1335                .vortex_expect("scalar_at should succeed in conformance test");
1336            assert_eq!(
1337                slice_cast_val, cast_slice_val,
1338                "Slice-then-cast and cast-then-slice produced different values at index {i}. \
1339                 Slice-then-cast: {slice_cast_val:?}, Cast-then-slice: {cast_slice_val:?}"
1340            );
1341        }
1342    }
1343}
1344
1345/// Run all consistency tests on an array.
1346///
1347/// This function executes a comprehensive suite of consistency tests that verify
1348/// the correctness of compute operations on Vortex arrays.
1349///
1350/// # Test Suite Overview
1351///
1352/// ## Core Operation Consistency
1353/// - **Filter/Take**: Verifies `filter(array, mask)` equals `take(array, true_indices)`
1354/// - **Mask Composition**: Ensures sequential masks equal combined masks
1355/// - **Slice/Filter**: Checks contiguous filters equal slice operations
1356/// - **Take/Slice**: Validates sequential takes equal slice operations
1357/// - **Cast/Slice**: Ensures cast operations preserve sliced array properties
1358///
1359/// ## Boolean Operations
1360/// - **De Morgan's Laws**: Verifies boolean operations follow logical laws
1361///
1362/// ## Comparison Operations
1363/// - **Inverse Relationships**: Verifies logical inverses (Eq/NotEq, Gt/Lte, Lt/Gte)
1364/// - **Symmetry**: Ensures proper ordering relationships when operands are swapped
1365///
1366/// ## Aggregate Operations
1367/// - **Slice/Aggregate**: Verifies aggregates on sliced arrays match canonical
1368///
1369/// ## Identity Operations
1370/// - **Filter Identity**: All-true mask preserves the array
1371/// - **Mask Identity**: All-false mask preserves values (as nullable)
1372/// - **Take Identity**: Taking all indices preserves the array
1373///
1374/// ## Edge Cases
1375/// - **Empty Operations**: Empty filters, takes, and slices behave correctly
1376/// - **Single Element**: Operations work with single-element arrays
1377/// - **Repeated Indices**: Take with duplicate indices works correctly
1378///
1379/// ## Null Handling
1380/// - **Nullable Indices**: Null indices produce null values
1381/// - **Mask/Filter Interaction**: Masking then filtering behaves predictably
1382///
1383/// ## Large Arrays
1384/// - **Performance**: Operations scale correctly to large arrays (1000+ elements)
1385/// ```text
1386pub fn test_array_consistency(array: &ArrayRef) {
1387    // Core operation consistency
1388    test_filter_take_consistency(array);
1389    test_double_mask_consistency(array);
1390    test_slice_filter_consistency(array);
1391    test_take_slice_consistency(array);
1392    test_cast_slice_consistency(array);
1393
1394    // Boolean operations
1395    test_boolean_demorgan_consistency(array);
1396
1397    // Comparison operations
1398    test_comparison_inverse_consistency(array);
1399    test_comparison_symmetry_consistency(array);
1400
1401    // Aggregate operations
1402    test_slice_aggregate_consistency(array);
1403
1404    // Identity operations
1405    test_filter_identity(array);
1406    test_mask_identity(array);
1407    test_take_preserves_properties(array);
1408
1409    // Ordering and correctness
1410    test_filter_preserves_order(array);
1411    test_take_repeated_indices(array);
1412
1413    // Null handling
1414    test_mask_filter_null_consistency(array);
1415    test_nullable_indices_consistency(array);
1416
1417    // Edge cases
1418    test_empty_operations_consistency(array);
1419    test_large_array_consistency(array);
1420}