• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 17075133033

19 Aug 2025 04:01PM UTC coverage: 87.949% (+0.09%) from 87.856%
17075133033

push

github

web-flow
feat: ArrayOperations infallible, eager validation + new_unchecked (#4177)

ArrayOperations currently return VortexResult<>, but they really should
just be infallible. A failed array op is generally indicative of
programmer or encoding error. There's really nothing interesting we can
do to handle an out-of-bounds slice() or scalar_at.

There's a lot that falls out of this, like fixing a bunch of tests,
tweaking our scalar value casting to return Option instead of Result,
etc.

---------

Signed-off-by: Andrew Duffy <andrew@a10y.dev>

1744 of 1985 new or added lines in 195 files covered. (87.86%)

36 existing lines in 27 files now uncovered.

56745 of 64520 relevant lines covered (87.95%)

624082.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.99
/vortex-array/src/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

22
use vortex_dtype::{DType, Nullability, PType};
23
use vortex_error::{VortexUnwrap, vortex_panic};
24
use vortex_mask::Mask;
25

26
use crate::arrays::{BoolArray, PrimitiveArray};
27
use crate::compute::{Operator, and, cast, compare, filter, invert, mask, or, take};
28
use crate::{Array, IntoArray};
29

30
/// Tests that filter and take operations produce consistent results.
31
///
32
/// # Invariant
33
/// `filter(array, mask)` should equal `take(array, indices_where_mask_is_true)`
34
///
35
/// # Test Details
36
/// - Creates a mask that keeps elements where index % 3 != 1
37
/// - Applies filter with this mask
38
/// - Creates indices array containing positions where mask is true
39
/// - Applies take with these indices
40
/// - Verifies both results are identical
41
fn test_filter_take_consistency(array: &dyn Array) {
5,266✔
42
    let len = array.len();
5,266✔
43
    if len == 0 {
5,266✔
44
        return;
1✔
45
    }
5,265✔
46

47
    // Create a test mask (keep elements where index % 3 != 1)
48
    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 3 != 1).collect();
1,780,145✔
49
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern.clone())).vortex_unwrap();
5,265✔
50

51
    // Filter the array
52
    let filtered = filter(array, &mask).vortex_unwrap();
5,265✔
53

54
    // Create indices where mask is true
55
    let indices: Vec<u64> = mask_pattern
5,265✔
56
        .iter()
5,265✔
57
        .enumerate()
5,265✔
58
        .filter_map(|(i, &v)| v.then_some(i as u64))
1,780,145✔
59
        .collect();
5,265✔
60
    let indices_array = PrimitiveArray::from_iter(indices).into_array();
5,265✔
61

62
    // Take using those indices
63
    let taken = take(array, &indices_array).vortex_unwrap();
5,265✔
64

65
    // Results should be identical
66
    assert_eq!(
5,265✔
67
        filtered.len(),
5,265✔
68
        taken.len(),
5,265✔
69
        "Filter and take should produce arrays of the same length. \
×
70
         Filtered length: {}, Taken length: {}",
×
71
        filtered.len(),
×
72
        taken.len()
×
73
    );
74

75
    for i in 0..filtered.len() {
1,186,224✔
76
        let filtered_val = filtered.scalar_at(i);
1,186,224✔
77
        let taken_val = taken.scalar_at(i);
1,186,224✔
78
        assert_eq!(
1,186,224✔
79
            filtered_val, taken_val,
80
            "Filter and take produced different values at index {i}. \
×
81
             Filtered value: {filtered_val:?}, Taken value: {taken_val:?}"
×
82
        );
83
    }
84
}
5,266✔
85

86
/// Tests that double masking is consistent with combined mask.
87
///
88
/// # Invariant
89
/// `mask(mask(array, mask1), mask2)` should equal `mask(array, mask1 | mask2)`
90
///
91
/// # Test Details
92
/// - Creates two masks: mask1 (every 3rd element) and mask2 (every 2nd element)
93
/// - Applies masks sequentially: first mask1, then mask2 on the result
94
/// - Creates a combined mask using OR operation (element is masked if either mask is true)
95
/// - Applies the combined mask directly to the original array
96
/// - Verifies both approaches produce identical results
97
///
98
/// # Why This Matters
99
/// This test ensures that mask operations compose correctly, which is critical for
100
/// complex query operations that may apply multiple filters.
101
fn test_double_mask_consistency(array: &dyn Array) {
5,266✔
102
    let len = array.len();
5,266✔
103
    if len == 0 {
5,266✔
104
        return;
1✔
105
    }
5,265✔
106

107
    // Create two different mask patterns
108
    let mask1_pattern: Vec<bool> = (0..len).map(|i| i % 3 == 0).collect();
1,780,145✔
109
    let mask2_pattern: Vec<bool> = (0..len).map(|i| i % 2 == 0).collect();
1,780,145✔
110

111
    let mask1 = Mask::try_from(&BoolArray::from_iter(mask1_pattern.clone())).vortex_unwrap();
5,265✔
112
    let mask2 = Mask::try_from(&BoolArray::from_iter(mask2_pattern.clone())).vortex_unwrap();
5,265✔
113

114
    // Apply masks sequentially
115
    let first_masked = mask(array, &mask1).vortex_unwrap();
5,265✔
116
    let double_masked = mask(&first_masked, &mask2).vortex_unwrap();
5,265✔
117

118
    // Create combined mask (OR operation - element is masked if EITHER mask is true)
119
    let combined_pattern: Vec<bool> = mask1_pattern
5,265✔
120
        .iter()
5,265✔
121
        .zip(mask2_pattern.iter())
5,265✔
122
        .map(|(&a, &b)| a || b)
1,780,145✔
123
        .collect();
5,265✔
124
    let combined_mask = Mask::try_from(&BoolArray::from_iter(combined_pattern)).vortex_unwrap();
5,265✔
125

126
    // Apply combined mask directly
127
    let directly_masked = mask(array, &combined_mask).vortex_unwrap();
5,265✔
128

129
    // Results should be identical
130
    assert_eq!(
5,265✔
131
        double_masked.len(),
5,265✔
132
        directly_masked.len(),
5,265✔
133
        "Sequential masking and combined masking should produce arrays of the same length. \
×
134
         Sequential length: {}, Combined length: {}",
×
135
        double_masked.len(),
×
136
        directly_masked.len()
×
137
    );
138

139
    for i in 0..double_masked.len() {
1,780,145✔
140
        let double_val = double_masked.scalar_at(i);
1,780,145✔
141
        let direct_val = directly_masked.scalar_at(i);
1,780,145✔
142
        assert_eq!(
1,780,145✔
143
            double_val, direct_val,
144
            "Sequential masking and combined masking produced different values at index {i}. \
×
145
             Sequential masking value: {double_val:?}, Combined masking value: {direct_val:?}\n\
×
146
             This likely indicates an issue with how masks are composed in the array implementation."
×
147
        );
148
    }
149
}
5,266✔
150

151
/// Tests that filtering with an all-true mask preserves the array.
152
///
153
/// # Invariant
154
/// `filter(array, all_true_mask)` should equal `array`
155
///
156
/// # Test Details
157
/// - Creates a mask with all elements set to true
158
/// - Applies filter with this mask
159
/// - Verifies the result is identical to the original array
160
///
161
/// # Why This Matters
162
/// This is an identity operation that should be optimized in implementations
163
/// to avoid unnecessary copying.
164
fn test_filter_identity(array: &dyn Array) {
5,266✔
165
    let len = array.len();
5,266✔
166
    if len == 0 {
5,266✔
167
        return;
1✔
168
    }
5,265✔
169

170
    let all_true_mask = Mask::new_true(len);
5,265✔
171
    let filtered = filter(array, &all_true_mask).vortex_unwrap();
5,265✔
172

173
    // Filtered array should be identical to original
174
    assert_eq!(
5,265✔
175
        filtered.len(),
5,265✔
176
        array.len(),
5,265✔
177
        "Filtering with all-true mask should preserve array length. \
×
178
         Original length: {}, Filtered length: {}",
×
179
        array.len(),
×
180
        filtered.len()
×
181
    );
182

183
    for i in 0..len {
1,780,145✔
184
        let original_val = array.scalar_at(i);
1,780,145✔
185
        let filtered_val = filtered.scalar_at(i);
1,780,145✔
186
        assert_eq!(
1,780,145✔
187
            filtered_val, original_val,
188
            "Filtering with all-true mask should preserve all values. \
×
189
             Value at index {i} changed from {original_val:?} to {filtered_val:?}"
×
190
        );
191
    }
192
}
5,266✔
193

194
/// Tests that masking with an all-false mask preserves values while making them nullable.
195
///
196
/// # Invariant
197
/// `mask(array, all_false_mask)` should have same values as `array` but with nullable type
198
///
199
/// # Test Details
200
/// - Creates a mask with all elements set to false (no elements are nullified)
201
/// - Applies mask operation
202
/// - Verifies all values are preserved but the array type becomes nullable
203
///
204
/// # Why This Matters
205
/// Masking always produces a nullable array, even when no values are actually masked.
206
/// This test ensures the type system handles this correctly.
207
fn test_mask_identity(array: &dyn Array) {
5,266✔
208
    let len = array.len();
5,266✔
209
    if len == 0 {
5,266✔
210
        return;
1✔
211
    }
5,265✔
212

213
    let all_false_mask = Mask::new_false(len);
5,265✔
214
    let masked = mask(array, &all_false_mask).vortex_unwrap();
5,265✔
215

216
    // Masked array should have same values (just nullable)
217
    assert_eq!(
5,265✔
218
        masked.len(),
5,265✔
219
        array.len(),
5,265✔
220
        "Masking with all-false mask should preserve array length. \
×
221
         Original length: {}, Masked length: {}",
×
222
        array.len(),
×
223
        masked.len()
×
224
    );
225

226
    assert!(
5,265✔
227
        masked.dtype().is_nullable(),
5,265✔
228
        "Mask operation should always produce a nullable array, but dtype is {:?}",
×
229
        masked.dtype()
×
230
    );
231

232
    for i in 0..len {
1,780,145✔
233
        let original_val = array.scalar_at(i);
1,780,145✔
234
        let masked_val = masked.scalar_at(i);
1,780,145✔
235
        let expected_val = original_val.clone().into_nullable();
1,780,145✔
236
        assert_eq!(
1,780,145✔
237
            masked_val, expected_val,
238
            "Masking with all-false mask should preserve values (as nullable). \
×
239
             Value at index {i}: original = {original_val:?}, masked = {masked_val:?}, expected = {expected_val:?}"
×
240
        );
241
    }
242
}
5,266✔
243

244
/// Tests that slice and filter with contiguous mask produce same results.
245
///
246
/// # Invariant
247
/// `filter(array, contiguous_true_mask)` should equal `slice(array, start, end)`
248
///
249
/// # Test Details
250
/// - Creates a mask that is true only for indices 1, 2, and 3
251
/// - Filters the array with this mask
252
/// - Slices the array from index 1 to 4
253
/// - Verifies both operations produce identical results
254
///
255
/// # Why This Matters
256
/// When a filter mask represents a contiguous range, it should be equivalent to
257
/// a slice operation. Some implementations may optimize this case.
258
fn test_slice_filter_consistency(array: &dyn Array) {
5,266✔
259
    let len = array.len();
5,266✔
260
    if len < 4 {
5,266✔
261
        return; // Need at least 4 elements for meaningful test
875✔
262
    }
4,391✔
263

264
    // Create a contiguous mask (true from index 1 to 3)
265
    let mut mask_pattern = vec![false; len];
4,391✔
266
    mask_pattern[1..4.min(len)].fill(true);
4,391✔
267

268
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
4,391✔
269
    let filtered = filter(array, &mask).vortex_unwrap();
4,391✔
270

271
    // Slice should produce the same result
272
    let sliced = array.slice(1, 4.min(len));
4,391✔
273

274
    assert_eq!(
4,391✔
275
        filtered.len(),
4,391✔
276
        sliced.len(),
4,391✔
277
        "Filter with contiguous mask and slice should produce same length. \
×
278
         Filtered length: {}, Sliced length: {}",
×
279
        filtered.len(),
×
280
        sliced.len()
×
281
    );
282

283
    for i in 0..filtered.len() {
13,173✔
284
        let filtered_val = filtered.scalar_at(i);
13,173✔
285
        let sliced_val = sliced.scalar_at(i);
13,173✔
286
        assert_eq!(
13,173✔
287
            filtered_val, sliced_val,
288
            "Filter with contiguous mask and slice produced different values at index {i}. \
×
289
             Filtered value: {filtered_val:?}, Sliced value: {sliced_val:?}"
×
290
        );
291
    }
292
}
5,266✔
293

294
/// Tests that take with sequential indices equals slice.
295
///
296
/// # Invariant
297
/// `take(array, [1, 2, 3, ...])` should equal `slice(array, 1, n)`
298
///
299
/// # Test Details
300
/// - Creates indices array with sequential values [1, 2, 3]
301
/// - Takes elements at these indices
302
/// - Slices array from index 1 to 4
303
/// - Verifies both operations produce identical results
304
///
305
/// # Why This Matters
306
/// Sequential takes are a common pattern that can be optimized to slice operations.
307
fn test_take_slice_consistency(array: &dyn Array) {
5,266✔
308
    let len = array.len();
5,266✔
309
    if len < 3 {
5,266✔
310
        return; // Need at least 3 elements
717✔
311
    }
4,549✔
312

313
    // Take indices [1, 2, 3]
314
    let end = 4.min(len);
4,549✔
315
    let indices = PrimitiveArray::from_iter((1..end).map(|i| i as u64)).into_array();
13,489✔
316
    let taken = take(array, &indices).vortex_unwrap();
4,549✔
317

318
    // Slice from 1 to end
319
    let sliced = array.slice(1, end);
4,549✔
320

321
    assert_eq!(
4,549✔
322
        taken.len(),
4,549✔
323
        sliced.len(),
4,549✔
324
        "Take with sequential indices and slice should produce same length. \
×
325
         Taken length: {}, Sliced length: {}",
×
326
        taken.len(),
×
327
        sliced.len()
×
328
    );
329

330
    for i in 0..taken.len() {
13,489✔
331
        let taken_val = taken.scalar_at(i);
13,489✔
332
        let sliced_val = sliced.scalar_at(i);
13,489✔
333
        assert_eq!(
13,489✔
334
            taken_val, sliced_val,
335
            "Take with sequential indices and slice produced different values at index {i}. \
×
336
             Taken value: {taken_val:?}, Sliced value: {sliced_val:?}"
×
337
        );
338
    }
339
}
5,266✔
340

341
/// Tests that filter preserves relative ordering
342
fn test_filter_preserves_order(array: &dyn Array) {
5,266✔
343
    let len = array.len();
5,266✔
344
    if len < 4 {
5,266✔
345
        return;
875✔
346
    }
4,391✔
347

348
    // Create a mask that selects elements at indices 0, 2, 3
349
    let mask_pattern: Vec<bool> = (0..len).map(|i| i == 0 || i == 2 || i == 3).collect();
1,778,913✔
350
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
4,391✔
351

352
    let filtered = filter(array, &mask).vortex_unwrap();
4,391✔
353

354
    // Verify the filtered array contains the right elements in order
355
    assert_eq!(filtered.len(), 3.min(len));
4,391✔
356
    if len >= 4 {
4,391✔
357
        assert_eq!(filtered.scalar_at(0), array.scalar_at(0));
4,391✔
358
        assert_eq!(filtered.scalar_at(1), array.scalar_at(2),);
4,391✔
359
        assert_eq!(filtered.scalar_at(2), array.scalar_at(3));
4,391✔
UNCOV
360
    }
×
361
}
5,266✔
362

363
/// Tests that take with repeated indices works correctly
364
fn test_take_repeated_indices(array: &dyn Array) {
5,266✔
365
    let len = array.len();
5,266✔
366
    if len == 0 {
5,266✔
367
        return;
1✔
368
    }
5,265✔
369

370
    // Take the first element three times
371
    let indices = PrimitiveArray::from_iter([0u64, 0, 0]).into_array();
5,265✔
372
    let taken = take(array, &indices).vortex_unwrap();
5,265✔
373

374
    assert_eq!(taken.len(), 3);
5,265✔
375
    for i in 0..3 {
21,060✔
376
        assert_eq!(taken.scalar_at(i), array.scalar_at(0),);
15,795✔
377
    }
378
}
5,266✔
379

380
/// Tests mask and filter interaction with nulls
381
fn test_mask_filter_null_consistency(array: &dyn Array) {
5,266✔
382
    let len = array.len();
5,266✔
383
    if len < 3 {
5,266✔
384
        return;
717✔
385
    }
4,549✔
386

387
    // First mask some elements
388
    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 2 == 0).collect();
1,779,387✔
389
    let mask_array = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
4,549✔
390
    let masked = mask(array, &mask_array).vortex_unwrap();
4,549✔
391

392
    // Then filter to remove the nulls
393
    let filter_pattern: Vec<bool> = (0..len).map(|i| i % 2 != 0).collect();
1,779,387✔
394
    let filter_mask = Mask::try_from(&BoolArray::from_iter(filter_pattern)).vortex_unwrap();
4,549✔
395
    let filtered = filter(&masked, &filter_mask).vortex_unwrap();
4,549✔
396

397
    // This should be equivalent to directly filtering the original array
398
    let direct_filtered = filter(array, &filter_mask).vortex_unwrap();
4,549✔
399

400
    assert_eq!(filtered.len(), direct_filtered.len());
4,549✔
401
    for i in 0..filtered.len() {
888,230✔
402
        assert_eq!(filtered.scalar_at(i), direct_filtered.scalar_at(i));
888,230✔
403
    }
404
}
5,266✔
405

406
/// Tests that empty operations are consistent
407
fn test_empty_operations_consistency(array: &dyn Array) {
5,266✔
408
    let len = array.len();
5,266✔
409

410
    // Empty filter
411
    let empty_filter = filter(array, &Mask::new_false(len)).vortex_unwrap();
5,266✔
412
    assert_eq!(empty_filter.len(), 0);
5,266✔
413
    assert_eq!(empty_filter.dtype(), array.dtype());
5,266✔
414

415
    // Empty take
416
    let empty_indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable).into_array();
5,266✔
417
    let empty_take = take(array, &empty_indices).vortex_unwrap();
5,266✔
418
    assert_eq!(empty_take.len(), 0);
5,266✔
419
    assert_eq!(empty_take.dtype(), array.dtype());
5,266✔
420

421
    // Empty slice (if array is non-empty)
422
    if len > 0 {
5,266✔
423
        let empty_slice = array.slice(0, 0);
5,265✔
424
        assert_eq!(empty_slice.len(), 0);
5,265✔
425
        assert_eq!(empty_slice.dtype(), array.dtype());
5,265✔
426
    }
1✔
427
}
5,266✔
428

429
/// Tests that take preserves array properties
430
fn test_take_preserves_properties(array: &dyn Array) {
5,266✔
431
    let len = array.len();
5,266✔
432
    if len == 0 {
5,266✔
433
        return;
1✔
434
    }
5,265✔
435

436
    // Take all elements in original order
437
    let indices = PrimitiveArray::from_iter((0..len).map(|i| i as u64)).into_array();
1,780,145✔
438
    let taken = take(array, &indices).vortex_unwrap();
5,265✔
439

440
    // Should be identical to original
441
    assert_eq!(taken.len(), array.len());
5,265✔
442
    assert_eq!(taken.dtype(), array.dtype());
5,265✔
443
    for i in 0..len {
1,780,145✔
444
        assert_eq!(taken.scalar_at(i), array.scalar_at(i),);
1,780,145✔
445
    }
446
}
5,266✔
447

448
/// Tests consistency with nullable indices.
449
///
450
/// # Invariant
451
/// `take(array, [Some(0), None, Some(2)])` should produce `[array[0], null, array[2]]`
452
///
453
/// # Test Details
454
/// - Creates an indices array with null at position 1: `[Some(0), None, Some(2)]`
455
/// - Takes elements using these indices
456
/// - Verifies that:
457
///   - Position 0 contains the value from array index 0
458
///   - Position 1 contains null
459
///   - Position 2 contains the value from array index 2
460
///   - The result array has nullable type
461
///
462
/// # Why This Matters
463
/// Nullable indices are a powerful feature that allows introducing nulls during
464
/// a take operation, which is useful for outer joins and similar operations.
465
fn test_nullable_indices_consistency(array: &dyn Array) {
5,266✔
466
    let len = array.len();
5,266✔
467
    if len < 3 {
5,266✔
468
        return; // Need at least 3 elements to test indices 0 and 2
717✔
469
    }
4,549✔
470

471
    // Create nullable indices where some indices are null
472
    let indices = PrimitiveArray::from_option_iter([Some(0u64), None, Some(2u64)]).into_array();
4,549✔
473

474
    let taken = take(array, &indices).vortex_unwrap();
4,549✔
475

476
    // Result should have nulls where indices were null
477
    assert_eq!(
4,549✔
478
        taken.len(),
4,549✔
479
        3,
480
        "Take with nullable indices should produce array of length 3, got {}",
×
481
        taken.len()
×
482
    );
483

484
    assert!(
4,549✔
485
        taken.dtype().is_nullable(),
4,549✔
486
        "Take with nullable indices should produce nullable array, but dtype is {:?}",
×
487
        taken.dtype()
×
488
    );
489

490
    // Check first element (from index 0)
491
    let expected_0 = array.scalar_at(0).into_nullable();
4,549✔
492
    let actual_0 = taken.scalar_at(0);
4,549✔
493
    assert_eq!(
4,549✔
494
        actual_0, expected_0,
495
        "Take with nullable indices: element at position 0 should be from array index 0. \
×
496
         Expected: {expected_0:?}, Actual: {actual_0:?}"
×
497
    );
498

499
    // Check second element (should be null)
500
    let actual_1 = taken.scalar_at(1);
4,549✔
501
    assert!(
4,549✔
502
        actual_1.is_null(),
4,549✔
503
        "Take with nullable indices: element at position 1 should be null, but got {actual_1:?}"
×
504
    );
505

506
    // Check third element (from index 2)
507
    let expected_2 = array.scalar_at(2).into_nullable();
4,549✔
508
    let actual_2 = taken.scalar_at(2);
4,549✔
509
    assert_eq!(
4,549✔
510
        actual_2, expected_2,
511
        "Take with nullable indices: element at position 2 should be from array index 2. \
×
512
         Expected: {expected_2:?}, Actual: {actual_2:?}"
×
513
    );
514
}
5,266✔
515

516
/// Tests large array consistency
517
fn test_large_array_consistency(array: &dyn Array) {
5,266✔
518
    let len = array.len();
5,266✔
519
    if len < 1000 {
5,266✔
520
        return;
4,322✔
521
    }
944✔
522

523
    // Test with every 10th element
524
    let indices: Vec<u64> = (0..len).step_by(10).map(|i| i as u64).collect();
174,560✔
525
    let indices_array = PrimitiveArray::from_iter(indices).into_array();
944✔
526
    let taken = take(array, &indices_array).vortex_unwrap();
944✔
527

528
    // Create equivalent filter mask
529
    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 10 == 0).collect();
1,744,976✔
530
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
944✔
531
    let filtered = filter(array, &mask).vortex_unwrap();
944✔
532

533
    // Results should match
534
    assert_eq!(taken.len(), filtered.len());
944✔
535
    for i in 0..taken.len() {
174,560✔
536
        assert_eq!(taken.scalar_at(i), filtered.scalar_at(i),);
174,560✔
537
    }
538
}
5,266✔
539

540
/// Tests that comparison operations follow inverse relationships.
541
///
542
/// # Invariants
543
/// - `compare(array, value, Eq)` is the inverse of `compare(array, value, NotEq)`
544
/// - `compare(array, value, Gt)` is the inverse of `compare(array, value, Lte)`
545
/// - `compare(array, value, Lt)` is the inverse of `compare(array, value, Gte)`
546
///
547
/// # Test Details
548
/// - Creates comparison results for each operator
549
/// - Verifies that inverse operations produce opposite boolean values
550
/// - Tests with multiple scalar values to ensure consistency
551
///
552
/// # Why This Matters
553
/// Comparison operations must maintain logical consistency across encodings.
554
/// This test catches bugs where an encoding might implement one comparison
555
/// correctly but fail on its logical inverse.
556
fn test_comparison_inverse_consistency(array: &dyn Array) {
5,266✔
557
    let len = array.len();
5,266✔
558
    if len == 0 {
5,266✔
559
        return;
1✔
560
    }
5,265✔
561

562
    // Skip non-comparable types
563
    match array.dtype() {
5,265✔
564
        DType::Null | DType::Extension(_) => return,
320✔
565
        DType::Struct(..) | DType::List(..) => return,
10✔
566
        _ => {}
4,935✔
567
    }
568

569
    // Get a test value from the middle of the array
570
    let test_scalar = if len == 0 {
4,935✔
NEW
571
        return;
×
572
    } else {
573
        array.scalar_at(len / 2)
4,935✔
574
    };
575

576
    // Test Eq vs NotEq
577
    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
4,935✔
578
    if let (Ok(eq_result), Ok(neq_result)) = (
4,935✔
579
        compare(array, const_array.as_ref(), Operator::Eq),
4,935✔
580
        compare(array, const_array.as_ref(), Operator::NotEq),
4,935✔
581
    ) {
582
        let inverted_eq = invert(&eq_result).vortex_unwrap();
4,935✔
583

584
        assert_eq!(
4,935✔
585
            inverted_eq.len(),
4,935✔
586
            neq_result.len(),
4,935✔
587
            "Inverted Eq should have same length as NotEq"
×
588
        );
589

590
        for i in 0..inverted_eq.len() {
1,719,261✔
591
            let inv_val = inverted_eq.scalar_at(i);
1,719,261✔
592
            let neq_val = neq_result.scalar_at(i);
1,719,261✔
593
            assert_eq!(
1,719,261✔
594
                inv_val, neq_val,
595
                "At index {i}: NOT(Eq) should equal NotEq. \
×
596
                 NOT(Eq) = {inv_val:?}, NotEq = {neq_val:?}"
×
597
            );
598
        }
599
    }
×
600

601
    // Test Gt vs Lte
602
    if let (Ok(gt_result), Ok(lte_result)) = (
4,935✔
603
        compare(array, const_array.as_ref(), Operator::Gt),
4,935✔
604
        compare(array, const_array.as_ref(), Operator::Lte),
4,935✔
605
    ) {
606
        let inverted_gt = invert(&gt_result).vortex_unwrap();
4,935✔
607

608
        for i in 0..inverted_gt.len() {
1,719,261✔
609
            let inv_val = inverted_gt.scalar_at(i);
1,719,261✔
610
            let lte_val = lte_result.scalar_at(i);
1,719,261✔
611
            assert_eq!(
1,719,261✔
612
                inv_val, lte_val,
613
                "At index {i}: NOT(Gt) should equal Lte. \
×
614
                 NOT(Gt) = {inv_val:?}, Lte = {lte_val:?}"
×
615
            );
616
        }
617
    }
×
618

619
    // Test Lt vs Gte
620
    if let (Ok(lt_result), Ok(gte_result)) = (
4,935✔
621
        compare(array, const_array.as_ref(), Operator::Lt),
4,935✔
622
        compare(array, const_array.as_ref(), Operator::Gte),
4,935✔
623
    ) {
624
        let inverted_lt = invert(&lt_result).vortex_unwrap();
4,935✔
625

626
        for i in 0..inverted_lt.len() {
1,719,261✔
627
            let inv_val = inverted_lt.scalar_at(i);
1,719,261✔
628
            let gte_val = gte_result.scalar_at(i);
1,719,261✔
629
            assert_eq!(
1,719,261✔
630
                inv_val, gte_val,
631
                "At index {i}: NOT(Lt) should equal Gte. \
×
632
                 NOT(Lt) = {inv_val:?}, Gte = {gte_val:?}"
×
633
            );
634
        }
635
    }
×
636
}
5,266✔
637

638
/// Tests that comparison operations maintain proper symmetry relationships.
639
///
640
/// # Invariants
641
/// - `compare(array, value, Gt)` should equal `compare_scalar_array(value, array, Lt)`
642
/// - `compare(array, value, Lt)` should equal `compare_scalar_array(value, array, Gt)`
643
/// - `compare(array, value, Eq)` should equal `compare_scalar_array(value, array, Eq)`
644
///
645
/// # Test Details
646
/// - Compares array-scalar operations with their symmetric scalar-array versions
647
/// - Verifies that ordering relationships are properly reversed
648
/// - Tests equality which should be symmetric
649
///
650
/// # Why This Matters
651
/// Ensures that comparison operations maintain mathematical ordering properties
652
/// regardless of operand order.
653
fn test_comparison_symmetry_consistency(array: &dyn Array) {
5,266✔
654
    let len = array.len();
5,266✔
655
    if len == 0 {
5,266✔
656
        return;
1✔
657
    }
5,265✔
658

659
    // Skip non-comparable types
660
    match array.dtype() {
5,265✔
661
        DType::Null | DType::Extension(_) => return,
320✔
662
        DType::Struct(..) | DType::List(..) => return,
10✔
663
        _ => {}
4,935✔
664
    }
665

666
    // Get test values
667
    let test_scalar = if len == 2 {
4,935✔
668
        return;
3✔
669
    } else {
670
        array.scalar_at(len / 2)
4,932✔
671
    };
672

673
    // Create a constant array with the test scalar for reverse comparison
674
    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
4,932✔
675

676
    // Test Gt vs Lt symmetry
677
    if let (Ok(arr_gt_scalar), Ok(scalar_lt_arr)) = (
4,932✔
678
        compare(array, const_array.as_ref(), Operator::Gt),
4,932✔
679
        compare(const_array.as_ref(), array, Operator::Lt),
4,932✔
680
    ) {
681
        assert_eq!(
4,932✔
682
            arr_gt_scalar.len(),
4,932✔
683
            scalar_lt_arr.len(),
4,932✔
684
            "Symmetric comparisons should have same length"
×
685
        );
686

687
        for i in 0..arr_gt_scalar.len() {
1,719,255✔
688
            let arr_gt = arr_gt_scalar.scalar_at(i);
1,719,255✔
689
            let scalar_lt = scalar_lt_arr.scalar_at(i);
1,719,255✔
690
            assert_eq!(
1,719,255✔
691
                arr_gt, scalar_lt,
692
                "At index {i}: (array > scalar) should equal (scalar < array). \
×
693
                 array > scalar = {arr_gt:?}, scalar < array = {scalar_lt:?}"
×
694
            );
695
        }
696
    }
×
697

698
    // Test Eq symmetry
699
    if let (Ok(arr_eq_scalar), Ok(scalar_eq_arr)) = (
4,932✔
700
        compare(array, const_array.as_ref(), Operator::Eq),
4,932✔
701
        compare(const_array.as_ref(), array, Operator::Eq),
4,932✔
702
    ) {
703
        for i in 0..arr_eq_scalar.len() {
1,719,255✔
704
            let arr_eq = arr_eq_scalar.scalar_at(i);
1,719,255✔
705
            let scalar_eq = scalar_eq_arr.scalar_at(i);
1,719,255✔
706
            assert_eq!(
1,719,255✔
707
                arr_eq, scalar_eq,
708
                "At index {i}: (array == scalar) should equal (scalar == array). \
×
709
                 array == scalar = {arr_eq:?}, scalar == array = {scalar_eq:?}"
×
710
            );
711
        }
712
    }
×
713
}
5,266✔
714

715
/// Tests that boolean operations follow De Morgan's laws.
716
///
717
/// # Invariants
718
/// - `NOT(A AND B)` equals `(NOT A) OR (NOT B)`
719
/// - `NOT(A OR B)` equals `(NOT A) AND (NOT B)`
720
///
721
/// # Test Details
722
/// - If the array is boolean, uses it directly for testing boolean operations
723
/// - Creates two boolean masks from patterns based on the array
724
/// - Computes AND/OR operations and their inversions
725
/// - Verifies De Morgan's laws hold for all elements
726
///
727
/// # Why This Matters
728
/// Boolean operations must maintain logical consistency across encodings.
729
/// This test catches bugs where encodings might optimize boolean operations
730
/// incorrectly, breaking fundamental logical properties.
731
fn test_boolean_demorgan_consistency(array: &dyn Array) {
5,266✔
732
    if !matches!(array.dtype(), DType::Bool(_)) {
5,266✔
733
        return;
4,941✔
734
    }
325✔
735

736
    let mask = {
325✔
737
        let mask_pattern: Vec<bool> = (0..array.len()).map(|i| i % 3 == 0).collect();
7,066✔
738
        BoolArray::from_iter(mask_pattern)
325✔
739
    };
740
    let mask = mask.as_ref();
325✔
741

742
    // Test first De Morgan's law: NOT(A AND B) = (NOT A) OR (NOT B)
743
    if let (Ok(a_and_b), Ok(not_a), Ok(not_b)) = (and(array, mask), invert(array), invert(mask)) {
325✔
744
        let not_a_and_b = invert(&a_and_b).vortex_unwrap();
325✔
745
        let not_a_or_not_b = or(&not_a, &not_b).vortex_unwrap();
325✔
746

747
        assert_eq!(
325✔
748
            not_a_and_b.len(),
325✔
749
            not_a_or_not_b.len(),
325✔
750
            "De Morgan's law results should have same length"
×
751
        );
752

753
        for i in 0..not_a_and_b.len() {
7,066✔
754
            let left = not_a_and_b.scalar_at(i);
7,066✔
755
            let right = not_a_or_not_b.scalar_at(i);
7,066✔
756
            assert_eq!(
7,066✔
757
                left, right,
758
                "De Morgan's first law failed at index {i}: \
×
759
                 NOT(A AND B) = {left:?}, (NOT A) OR (NOT B) = {right:?}"
×
760
            );
761
        }
762
    }
×
763

764
    // Test second De Morgan's law: NOT(A OR B) = (NOT A) AND (NOT B)
765
    if let (Ok(a_or_b), Ok(not_a), Ok(not_b)) = (or(array, mask), invert(array), invert(mask)) {
325✔
766
        let not_a_or_b = invert(&a_or_b).vortex_unwrap();
325✔
767
        let not_a_and_not_b = and(&not_a, &not_b).vortex_unwrap();
325✔
768

769
        for i in 0..not_a_or_b.len() {
7,066✔
770
            let left = not_a_or_b.scalar_at(i);
7,066✔
771
            let right = not_a_and_not_b.scalar_at(i);
7,066✔
772
            assert_eq!(
7,066✔
773
                left, right,
774
                "De Morgan's second law failed at index {i}: \
×
775
                 NOT(A OR B) = {left:?}, (NOT A) AND (NOT B) = {right:?}"
×
776
            );
777
        }
778
    }
×
779
}
5,266✔
780

781
/// Tests that slice and aggregate operations produce consistent results.
782
///
783
/// # Invariants
784
/// - Aggregating a sliced array should equal aggregating the corresponding
785
///   elements from the canonical form
786
/// - This applies to sum, count, min/max, and other aggregate functions
787
///
788
/// # Test Details
789
/// - Slices the array and computes aggregates
790
/// - Compares against aggregating the canonical form's slice
791
/// - Tests multiple aggregate functions where applicable
792
///
793
/// # Why This Matters
794
/// Aggregate operations on sliced arrays must produce correct results
795
/// regardless of the underlying encoding's offset handling.
796
fn test_slice_aggregate_consistency(array: &dyn Array) {
5,266✔
797
    use vortex_dtype::DType;
798

799
    use crate::compute::{min_max, nan_count, sum};
800

801
    let len = array.len();
5,266✔
802
    if len < 5 {
5,266✔
803
        return; // Need enough elements for meaningful slice
1,037✔
804
    }
4,229✔
805

806
    // Define slice bounds
807
    let start = 1;
4,229✔
808
    let end = (len - 1).min(start + 10); // Take up to 10 elements
4,229✔
809

810
    // Get sliced array and canonical slice
811
    let sliced = array.slice(start, end);
4,229✔
812
    let canonical = array.to_canonical().vortex_unwrap();
4,229✔
813
    let canonical_sliced = canonical.as_ref().slice(start, end);
4,229✔
814

815
    // Test null count through invalid_count
816
    if let (Ok(slice_null_count), Ok(canonical_null_count)) =
4,229✔
817
        (sliced.invalid_count(), canonical_sliced.invalid_count())
4,229✔
818
    {
819
        assert_eq!(
4,229✔
820
            slice_null_count, canonical_null_count,
821
            "null_count on sliced array should match canonical. \
×
822
             Sliced: {slice_null_count}, Canonical: {canonical_null_count}"
×
823
        );
824
    }
×
825

826
    // Test sum for numeric types
827
    if !matches!(array.dtype(), DType::Primitive(..)) {
4,229✔
828
        return;
818✔
829
    }
3,411✔
830

831
    if let (Ok(slice_sum), Ok(canonical_sum)) = (sum(&sliced), sum(&canonical_sliced)) {
3,411✔
832
        // Compare sum scalars
833
        assert_eq!(
3,411✔
834
            slice_sum, canonical_sum,
835
            "sum on sliced array should match canonical. \
×
836
                 Sliced: {slice_sum:?}, Canonical: {canonical_sum:?}"
×
837
        );
838
    }
×
839

840
    // Test min_max
841
    if let (Ok(slice_minmax), Ok(canonical_minmax)) = (min_max(&sliced), min_max(&canonical_sliced))
3,411✔
842
    {
843
        match (slice_minmax, canonical_minmax) {
3,411✔
844
            (Some(s_result), Some(c_result)) => {
3,371✔
845
                assert_eq!(
3,371✔
846
                    s_result.min, c_result.min,
847
                    "min on sliced array should match canonical. \
×
848
                         Sliced: {:?}, Canonical: {:?}",
×
849
                    s_result.min, c_result.min
850
                );
851
                assert_eq!(
3,371✔
852
                    s_result.max, c_result.max,
853
                    "max on sliced array should match canonical. \
×
854
                         Sliced: {:?}, Canonical: {:?}",
×
855
                    s_result.max, c_result.max
856
                );
857
            }
858
            (None, None) => {} // Both empty, OK
40✔
859
            _ => vortex_panic!("min_max results don't match"),
×
860
        }
861
    }
×
862

863
    // Test nan_count for floating point types
864
    if array.dtype().is_float()
3,411✔
865
        && let (Ok(slice_nan_count), Ok(canonical_nan_count)) =
668✔
866
            (nan_count(&sliced), nan_count(&canonical_sliced))
668✔
867
    {
868
        assert_eq!(
668✔
869
            slice_nan_count, canonical_nan_count,
870
            "nan_count on sliced array should match canonical. \
×
871
                 Sliced: {slice_nan_count}, Canonical: {canonical_nan_count}"
×
872
        );
873
    }
2,743✔
874
}
5,266✔
875

876
/// Tests that cast operations preserve array properties when sliced.
877
///
878
/// # Invariant
879
/// `cast(slice(array, start, end), dtype)` should equal `slice(cast(array, dtype), start, end)`
880
///
881
/// # Test Details
882
/// - Slices the array from index 2 to 7 (or len-2 if smaller)
883
/// - Casts the sliced array to a different type
884
/// - Compares against the canonical form of the array (without slicing or casting the canonical form)
885
/// - Verifies both approaches produce identical results
886
///
887
/// # Why This Matters
888
/// This test specifically catches bugs where encodings (like RunEndArray) fail to preserve
889
/// offset information during cast operations. Such bugs can lead to incorrect data being
890
/// returned after casting a sliced array.
891
fn test_cast_slice_consistency(array: &dyn Array) {
5,266✔
892
    let len = array.len();
5,266✔
893
    if len < 5 {
5,266✔
894
        return; // Need at least 5 elements for meaningful slice
1,037✔
895
    }
4,229✔
896

897
    // Define slice bounds
898
    let start = 2;
4,229✔
899
    let end = 7.min(len - 2).max(start + 1); // Ensure we have at least 1 element
4,229✔
900

901
    // Get canonical form of the original array
902
    let canonical = array.to_canonical().vortex_unwrap();
4,229✔
903

904
    // Choose appropriate target dtype based on the array's type
905
    let target_dtypes = match array.dtype() {
4,229✔
906
        DType::Null => vec![],
3✔
907
        DType::Bool(nullability) => vec![
127✔
908
            DType::Primitive(PType::U8, *nullability),
127✔
909
            DType::Primitive(PType::I32, *nullability),
127✔
910
        ],
911
        DType::Primitive(ptype, nullability) => {
3,411✔
912
            let mut targets = vec![];
3,411✔
913
            // Test nullability changes
914
            let opposite_nullability = match nullability {
3,411✔
915
                Nullability::NonNullable => Nullability::Nullable,
2,742✔
916
                Nullability::Nullable => Nullability::NonNullable,
669✔
917
            };
918
            targets.push(DType::Primitive(*ptype, opposite_nullability));
3,411✔
919

920
            // Test widening casts
921
            match ptype {
3,411✔
922
                PType::U8 => {
156✔
923
                    targets.push(DType::Primitive(PType::U16, *nullability));
156✔
924
                    targets.push(DType::Primitive(PType::I16, *nullability));
156✔
925
                }
156✔
926
                PType::U16 => {
195✔
927
                    targets.push(DType::Primitive(PType::U32, *nullability));
195✔
928
                    targets.push(DType::Primitive(PType::I32, *nullability));
195✔
929
                }
195✔
930
                PType::U32 => {
391✔
931
                    targets.push(DType::Primitive(PType::U64, *nullability));
391✔
932
                    targets.push(DType::Primitive(PType::I64, *nullability));
391✔
933
                }
391✔
934
                PType::U64 => {
234✔
935
                    targets.push(DType::Primitive(PType::F64, *nullability));
234✔
936
                }
234✔
937
                PType::I8 => {
39✔
938
                    targets.push(DType::Primitive(PType::I16, *nullability));
39✔
939
                    targets.push(DType::Primitive(PType::F32, *nullability));
39✔
940
                }
39✔
941
                PType::I16 => {
157✔
942
                    targets.push(DType::Primitive(PType::I32, *nullability));
157✔
943
                    targets.push(DType::Primitive(PType::F32, *nullability));
157✔
944
                }
157✔
945
                PType::I32 => {
1,256✔
946
                    targets.push(DType::Primitive(PType::I64, *nullability));
1,256✔
947
                    targets.push(DType::Primitive(PType::F64, *nullability));
1,256✔
948
                }
1,256✔
949
                PType::I64 => {
315✔
950
                    targets.push(DType::Primitive(PType::F64, *nullability));
315✔
951
                }
315✔
952
                PType::F16 => {
×
953
                    targets.push(DType::Primitive(PType::F32, *nullability));
×
954
                }
×
955
                PType::F32 => {
392✔
956
                    targets.push(DType::Primitive(PType::F64, *nullability));
392✔
957
                    targets.push(DType::Primitive(PType::I32, *nullability));
392✔
958
                }
392✔
959
                PType::F64 => {
276✔
960
                    targets.push(DType::Primitive(PType::I64, *nullability));
276✔
961
                }
276✔
962
            }
963
            targets
3,411✔
964
        }
965
        DType::Utf8(nullability) => {
244✔
966
            let opposite = match nullability {
244✔
967
                Nullability::NonNullable => Nullability::Nullable,
164✔
968
                Nullability::Nullable => Nullability::NonNullable,
80✔
969
            };
970
            vec![DType::Utf8(opposite), DType::Binary(*nullability)]
244✔
971
        }
972
        DType::Binary(nullability) => {
3✔
973
            let opposite = match nullability {
3✔
974
                Nullability::NonNullable => Nullability::Nullable,
2✔
975
                Nullability::Nullable => Nullability::NonNullable,
1✔
976
            };
977
            vec![
3✔
978
                DType::Binary(opposite),
3✔
979
                DType::Utf8(*nullability), // May fail if not valid UTF-8
3✔
980
            ]
981
        }
982
        DType::Decimal(decimal_type, nullability) => {
275✔
983
            let opposite = match nullability {
275✔
984
                Nullability::NonNullable => Nullability::Nullable,
196✔
985
                Nullability::Nullable => Nullability::NonNullable,
79✔
986
            };
987
            vec![DType::Decimal(*decimal_type, opposite)]
275✔
988
        }
989
        DType::Struct(fields, nullability) => {
4✔
990
            let opposite = match nullability {
4✔
991
                Nullability::NonNullable => Nullability::Nullable,
4✔
992
                Nullability::Nullable => Nullability::NonNullable,
×
993
            };
994
            vec![DType::Struct(fields.clone(), opposite)]
4✔
995
        }
996
        DType::List(element_type, nullability) => {
3✔
997
            let opposite = match nullability {
3✔
998
                Nullability::NonNullable => Nullability::Nullable,
3✔
999
                Nullability::Nullable => Nullability::NonNullable,
×
1000
            };
1001
            vec![DType::List(element_type.clone(), opposite)]
3✔
1002
        }
1003
        DType::Extension(_) => vec![], // Extension types typically only cast to themselves
159✔
1004
    };
1005

1006
    // Test each target dtype
1007
    for target_dtype in target_dtypes {
14,667✔
1008
        // Slice the array
1009
        let sliced = array.slice(start, end);
10,438✔
1010

1011
        // Try to cast the sliced array
1012
        let slice_then_cast = match cast(&sliced, &target_dtype) {
10,438✔
1013
            Ok(result) => result,
9,545✔
1014
            Err(_) => continue, // Skip if cast fails
893✔
1015
        };
1016

1017
        // Verify against canonical form
1018
        assert_eq!(
9,545✔
1019
            slice_then_cast.len(),
9,545✔
1020
            end - start,
9,545✔
1021
            "Sliced and casted array should have length {}, but has {}",
×
1022
            end - start,
×
1023
            slice_then_cast.len()
×
1024
        );
1025

1026
        // Compare each value against the canonical form
1027
        for i in 0..slice_then_cast.len() {
22,959✔
1028
            let slice_cast_val = slice_then_cast.scalar_at(i);
22,959✔
1029

1030
            // Get the corresponding value from the canonical array (adjusted for slice offset)
1031
            let canonical_val = canonical.as_ref().scalar_at(start + i);
22,959✔
1032

1033
            // Cast the canonical scalar to the target dtype
1034
            let expected_val = match canonical_val.cast(&target_dtype) {
22,959✔
1035
                Ok(val) => val,
22,959✔
1036
                Err(_) => {
1037
                    // If scalar cast fails, we can't compare - skip this target dtype
1038
                    // This can happen for some type conversions that aren't supported at scalar level
UNCOV
1039
                    break;
×
1040
                }
1041
            };
1042

1043
            assert_eq!(
22,959✔
1044
                slice_cast_val,
1045
                expected_val,
1046
                "Cast of sliced array produced incorrect value at index {i}. \
×
1047
                 Got: {slice_cast_val:?}, Expected: {expected_val:?} \
×
1048
                 (canonical value at index {}: {canonical_val:?})\n\
×
1049
                 This likely indicates the array encoding doesn't preserve offset information during cast.",
×
1050
                start + i
×
1051
            );
1052
        }
1053

1054
        // Also test the other way: cast then slice
1055
        let casted = match cast(array, &target_dtype) {
9,545✔
1056
            Ok(result) => result,
8,873✔
1057
            Err(_) => continue, // Skip if cast fails
672✔
1058
        };
1059
        let cast_then_slice = casted.slice(start, end);
8,873✔
1060

1061
        // Verify the two approaches produce identical results
1062
        assert_eq!(
8,873✔
1063
            slice_then_cast.len(),
8,873✔
1064
            cast_then_slice.len(),
8,873✔
1065
            "Slice-then-cast and cast-then-slice should produce arrays of the same length"
×
1066
        );
1067

1068
        for i in 0..slice_then_cast.len() {
22,127✔
1069
            let slice_cast_val = slice_then_cast.scalar_at(i);
22,127✔
1070
            let cast_slice_val = cast_then_slice.scalar_at(i);
22,127✔
1071
            assert_eq!(
22,127✔
1072
                slice_cast_val, cast_slice_val,
1073
                "Slice-then-cast and cast-then-slice produced different values at index {i}. \
×
1074
                 Slice-then-cast: {slice_cast_val:?}, Cast-then-slice: {cast_slice_val:?}"
×
1075
            );
1076
        }
1077
    }
1078
}
5,266✔
1079

1080
/// Run all consistency tests on an array.
1081
///
1082
/// This function executes a comprehensive suite of consistency tests that verify
1083
/// the correctness of compute operations on Vortex arrays.
1084
///
1085
/// # Test Suite Overview
1086
///
1087
/// ## Core Operation Consistency
1088
/// - **Filter/Take**: Verifies `filter(array, mask)` equals `take(array, true_indices)`
1089
/// - **Mask Composition**: Ensures sequential masks equal combined masks
1090
/// - **Slice/Filter**: Checks contiguous filters equal slice operations
1091
/// - **Take/Slice**: Validates sequential takes equal slice operations
1092
/// - **Cast/Slice**: Ensures cast operations preserve sliced array properties
1093
///
1094
/// ## Boolean Operations
1095
/// - **De Morgan's Laws**: Verifies boolean operations follow logical laws
1096
///
1097
/// ## Comparison Operations
1098
/// - **Inverse Relationships**: Verifies logical inverses (Eq/NotEq, Gt/Lte, Lt/Gte)
1099
/// - **Symmetry**: Ensures proper ordering relationships when operands are swapped
1100
///
1101
/// ## Aggregate Operations
1102
/// - **Slice/Aggregate**: Verifies aggregates on sliced arrays match canonical
1103
///
1104
/// ## Identity Operations
1105
/// - **Filter Identity**: All-true mask preserves the array
1106
/// - **Mask Identity**: All-false mask preserves values (as nullable)
1107
/// - **Take Identity**: Taking all indices preserves the array
1108
///
1109
/// ## Edge Cases
1110
/// - **Empty Operations**: Empty filters, takes, and slices behave correctly
1111
/// - **Single Element**: Operations work with single-element arrays
1112
/// - **Repeated Indices**: Take with duplicate indices works correctly
1113
///
1114
/// ## Null Handling
1115
/// - **Nullable Indices**: Null indices produce null values
1116
/// - **Mask/Filter Interaction**: Masking then filtering behaves predictably
1117
///
1118
/// ## Large Arrays
1119
/// - **Performance**: Operations scale correctly to large arrays (1000+ elements)
1120
/// ```text
1121
pub fn test_array_consistency(array: &dyn Array) {
5,266✔
1122
    // Core operation consistency
1123
    test_filter_take_consistency(array);
5,266✔
1124
    test_double_mask_consistency(array);
5,266✔
1125
    test_slice_filter_consistency(array);
5,266✔
1126
    test_take_slice_consistency(array);
5,266✔
1127
    test_cast_slice_consistency(array);
5,266✔
1128

1129
    // Boolean operations
1130
    test_boolean_demorgan_consistency(array);
5,266✔
1131

1132
    // Comparison operations
1133
    test_comparison_inverse_consistency(array);
5,266✔
1134
    test_comparison_symmetry_consistency(array);
5,266✔
1135

1136
    // Aggregate operations
1137
    test_slice_aggregate_consistency(array);
5,266✔
1138

1139
    // Identity operations
1140
    test_filter_identity(array);
5,266✔
1141
    test_mask_identity(array);
5,266✔
1142
    test_take_preserves_properties(array);
5,266✔
1143

1144
    // Ordering and correctness
1145
    test_filter_preserves_order(array);
5,266✔
1146
    test_take_repeated_indices(array);
5,266✔
1147

1148
    // Null handling
1149
    test_mask_filter_null_consistency(array);
5,266✔
1150
    test_nullable_indices_consistency(array);
5,266✔
1151

1152
    // Edge cases
1153
    test_empty_operations_consistency(array);
5,266✔
1154
    test_large_array_consistency(array);
5,266✔
1155
}
5,266✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc