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