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

vortex-data / vortex / 16773563683

06 Aug 2025 09:51AM UTC coverage: 84.025% (+0.6%) from 83.389%
16773563683

Pull #4127

github

web-flow
Merge f2b01c37f into 773d4ec96
Pull Request #4127: experiment: prefetch files in duckdb scan

39 of 45 new or added lines in 2 files covered. (86.67%)

168 existing lines in 9 files now uncovered.

48344 of 57535 relevant lines covered (84.03%)

520551.22 hits per line

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

82.61
/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) {
4,221✔
42
    let len = array.len();
4,221✔
43
    if len == 0 {
4,221✔
44
        return;
1✔
45
    }
4,220✔
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,651,964✔
49
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern.clone())).vortex_unwrap();
4,220✔
50

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

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

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

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

75
    for i in 0..filtered.len() {
1,100,809✔
76
        let filtered_val = filtered.scalar_at(i).vortex_unwrap();
1,100,809✔
77
        let taken_val = taken.scalar_at(i).vortex_unwrap();
1,100,809✔
78
        assert_eq!(
1,100,809✔
79
            filtered_val, taken_val,
80
            "Filter and take produced different values at index {i}. \
×
UNCOV
81
             Filtered value: {filtered_val:?}, Taken value: {taken_val:?}"
×
82
        );
83
    }
84
}
4,221✔
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) {
4,221✔
102
    let len = array.len();
4,221✔
103
    if len == 0 {
4,221✔
104
        return;
1✔
105
    }
4,220✔
106

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

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

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

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

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

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

139
    for i in 0..double_masked.len() {
1,651,964✔
140
        let double_val = double_masked.scalar_at(i).vortex_unwrap();
1,651,964✔
141
        let direct_val = directly_masked.scalar_at(i).vortex_unwrap();
1,651,964✔
142
        assert_eq!(
1,651,964✔
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\
×
UNCOV
146
             This likely indicates an issue with how masks are composed in the array implementation."
×
147
        );
148
    }
149
}
4,221✔
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) {
4,221✔
165
    let len = array.len();
4,221✔
166
    if len == 0 {
4,221✔
167
        return;
1✔
168
    }
4,220✔
169

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

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

183
    for i in 0..len {
1,651,964✔
184
        let original_val = array.scalar_at(i).vortex_unwrap();
1,651,964✔
185
        let filtered_val = filtered.scalar_at(i).vortex_unwrap();
1,651,964✔
186
        assert_eq!(
1,651,964✔
187
            filtered_val, original_val,
188
            "Filtering with all-true mask should preserve all values. \
×
UNCOV
189
             Value at index {i} changed from {original_val:?} to {filtered_val:?}"
×
190
        );
191
    }
192
}
4,221✔
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) {
4,221✔
208
    let len = array.len();
4,221✔
209
    if len == 0 {
4,221✔
210
        return;
1✔
211
    }
4,220✔
212

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

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

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

232
    for i in 0..len {
1,651,964✔
233
        let original_val = array.scalar_at(i).vortex_unwrap();
1,651,964✔
234
        let masked_val = masked.scalar_at(i).vortex_unwrap();
1,651,964✔
235
        let expected_val = original_val.clone().into_nullable();
1,651,964✔
236
        assert_eq!(
1,651,964✔
237
            masked_val, expected_val,
238
            "Masking with all-false mask should preserve values (as nullable). \
×
UNCOV
239
             Value at index {i}: original = {original_val:?}, masked = {masked_val:?}, expected = {expected_val:?}"
×
240
        );
241
    }
242
}
4,221✔
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) {
4,221✔
259
    let len = array.len();
4,221✔
260
    if len < 4 {
4,221✔
261
        return; // Need at least 4 elements for meaningful test
663✔
262
    }
3,558✔
263

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

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

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

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

283
    for i in 0..filtered.len() {
10,674✔
284
        let filtered_val = filtered.scalar_at(i).vortex_unwrap();
10,674✔
285
        let sliced_val = sliced.scalar_at(i).vortex_unwrap();
10,674✔
286
        assert_eq!(
10,674✔
287
            filtered_val, sliced_val,
288
            "Filter with contiguous mask and slice produced different values at index {i}. \
×
UNCOV
289
             Filtered value: {filtered_val:?}, Sliced value: {sliced_val:?}"
×
290
        );
291
    }
292
}
4,221✔
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) {
4,221✔
308
    let len = array.len();
4,221✔
309
    if len < 3 {
4,221✔
310
        return; // Need at least 3 elements
509✔
311
    }
3,712✔
312

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

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

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

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

341
/// Tests that filter preserves relative ordering
342
fn test_filter_preserves_order(array: &dyn Array) {
4,221✔
343
    let len = array.len();
4,221✔
344
    if len < 4 {
4,221✔
345
        return;
663✔
346
    }
3,558✔
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,650,953✔
350
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
3,558✔
351

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

354
    // Verify the filtered array contains the right elements in order
355
    assert_eq!(filtered.len(), 3.min(len));
3,558✔
356
    if len >= 4 {
3,558✔
357
        assert_eq!(
3,558✔
358
            filtered.scalar_at(0).vortex_unwrap(),
3,558✔
359
            array.scalar_at(0).vortex_unwrap()
3,558✔
360
        );
361
        assert_eq!(
3,558✔
362
            filtered.scalar_at(1).vortex_unwrap(),
3,558✔
363
            array.scalar_at(2).vortex_unwrap()
3,558✔
364
        );
365
        assert_eq!(
3,558✔
366
            filtered.scalar_at(2).vortex_unwrap(),
3,558✔
367
            array.scalar_at(3).vortex_unwrap()
3,558✔
368
        );
UNCOV
369
    }
×
370
}
4,221✔
371

372
/// Tests that take with repeated indices works correctly
373
fn test_take_repeated_indices(array: &dyn Array) {
4,221✔
374
    let len = array.len();
4,221✔
375
    if len == 0 {
4,221✔
376
        return;
1✔
377
    }
4,220✔
378

379
    // Take the first element three times
380
    let indices = PrimitiveArray::from_iter([0u64, 0, 0]).into_array();
4,220✔
381
    let taken = take(array, &indices).vortex_unwrap();
4,220✔
382

383
    assert_eq!(taken.len(), 3);
4,220✔
384
    for i in 0..3 {
16,880✔
385
        assert_eq!(
12,660✔
386
            taken.scalar_at(i).vortex_unwrap(),
12,660✔
387
            array.scalar_at(0).vortex_unwrap()
12,660✔
388
        );
389
    }
390
}
4,221✔
391

392
/// Tests mask and filter interaction with nulls
393
fn test_mask_filter_null_consistency(array: &dyn Array) {
4,221✔
394
    let len = array.len();
4,221✔
395
    if len < 3 {
4,221✔
396
        return;
509✔
397
    }
3,712✔
398

399
    // First mask some elements
400
    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 2 == 0).collect();
1,651,415✔
401
    let mask_array = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
3,712✔
402
    let masked = mask(array, &mask_array).vortex_unwrap();
3,712✔
403

404
    // Then filter to remove the nulls
405
    let filter_pattern: Vec<bool> = (0..len).map(|i| i % 2 != 0).collect();
1,651,415✔
406
    let filter_mask = Mask::try_from(&BoolArray::from_iter(filter_pattern)).vortex_unwrap();
3,712✔
407
    let filtered = filter(&masked, &filter_mask).vortex_unwrap();
3,712✔
408

409
    // This should be equivalent to directly filtering the original array
410
    let direct_filtered = filter(array, &filter_mask).vortex_unwrap();
3,712✔
411

412
    assert_eq!(filtered.len(), direct_filtered.len());
3,712✔
413
    for i in 0..filtered.len() {
824,528✔
414
        assert_eq!(
824,528✔
415
            filtered.scalar_at(i).vortex_unwrap(),
824,528✔
416
            direct_filtered.scalar_at(i).vortex_unwrap()
824,528✔
417
        );
418
    }
419
}
4,221✔
420

421
/// Tests that empty operations are consistent
422
fn test_empty_operations_consistency(array: &dyn Array) {
4,221✔
423
    let len = array.len();
4,221✔
424

425
    // Empty filter
426
    let empty_filter = filter(array, &Mask::new_false(len)).vortex_unwrap();
4,221✔
427
    assert_eq!(empty_filter.len(), 0);
4,221✔
428
    assert_eq!(empty_filter.dtype(), array.dtype());
4,221✔
429

430
    // Empty take
431
    let empty_indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable).into_array();
4,221✔
432
    let empty_take = take(array, &empty_indices).vortex_unwrap();
4,221✔
433
    assert_eq!(empty_take.len(), 0);
4,221✔
434
    assert_eq!(empty_take.dtype(), array.dtype());
4,221✔
435

436
    // Empty slice (if array is non-empty)
437
    if len > 0 {
4,221✔
438
        let empty_slice = array.slice(0, 0).vortex_unwrap();
4,220✔
439
        assert_eq!(empty_slice.len(), 0);
4,220✔
440
        assert_eq!(empty_slice.dtype(), array.dtype());
4,220✔
441
    }
1✔
442
}
4,221✔
443

444
/// Tests that take preserves array properties
445
fn test_take_preserves_properties(array: &dyn Array) {
4,221✔
446
    let len = array.len();
4,221✔
447
    if len == 0 {
4,221✔
448
        return;
1✔
449
    }
4,220✔
450

451
    // Take all elements in original order
452
    let indices = PrimitiveArray::from_iter((0..len).map(|i| i as u64)).into_array();
1,651,964✔
453
    let taken = take(array, &indices).vortex_unwrap();
4,220✔
454

455
    // Should be identical to original
456
    assert_eq!(taken.len(), array.len());
4,220✔
457
    assert_eq!(taken.dtype(), array.dtype());
4,220✔
458
    for i in 0..len {
1,651,964✔
459
        assert_eq!(
1,651,964✔
460
            taken.scalar_at(i).vortex_unwrap(),
1,651,964✔
461
            array.scalar_at(i).vortex_unwrap()
1,651,964✔
462
        );
463
    }
464
}
4,221✔
465

466
/// Tests consistency with nullable indices.
467
///
468
/// # Invariant
469
/// `take(array, [Some(0), None, Some(2)])` should produce `[array[0], null, array[2]]`
470
///
471
/// # Test Details
472
/// - Creates an indices array with null at position 1: `[Some(0), None, Some(2)]`
473
/// - Takes elements using these indices
474
/// - Verifies that:
475
///   - Position 0 contains the value from array index 0
476
///   - Position 1 contains null
477
///   - Position 2 contains the value from array index 2
478
///   - The result array has nullable type
479
///
480
/// # Why This Matters
481
/// Nullable indices are a powerful feature that allows introducing nulls during
482
/// a take operation, which is useful for outer joins and similar operations.
483
fn test_nullable_indices_consistency(array: &dyn Array) {
4,221✔
484
    let len = array.len();
4,221✔
485
    if len < 3 {
4,221✔
486
        return; // Need at least 3 elements to test indices 0 and 2
509✔
487
    }
3,712✔
488

489
    // Create nullable indices where some indices are null
490
    let indices = PrimitiveArray::from_option_iter([Some(0u64), None, Some(2u64)]).into_array();
3,712✔
491

492
    let taken = take(array, &indices).vortex_unwrap();
3,712✔
493

494
    // Result should have nulls where indices were null
495
    assert_eq!(
3,712✔
496
        taken.len(),
3,712✔
497
        3,
498
        "Take with nullable indices should produce array of length 3, got {}",
×
499
        taken.len()
×
500
    );
501

502
    assert!(
3,712✔
503
        taken.dtype().is_nullable(),
3,712✔
504
        "Take with nullable indices should produce nullable array, but dtype is {:?}",
×
505
        taken.dtype()
×
506
    );
507

508
    // Check first element (from index 0)
509
    let expected_0 = array.scalar_at(0).vortex_unwrap().into_nullable();
3,712✔
510
    let actual_0 = taken.scalar_at(0).vortex_unwrap();
3,712✔
511
    assert_eq!(
3,712✔
512
        actual_0, expected_0,
513
        "Take with nullable indices: element at position 0 should be from array index 0. \
×
514
         Expected: {expected_0:?}, Actual: {actual_0:?}"
×
515
    );
516

517
    // Check second element (should be null)
518
    let actual_1 = taken.scalar_at(1).vortex_unwrap();
3,712✔
519
    assert!(
3,712✔
520
        actual_1.is_null(),
3,712✔
521
        "Take with nullable indices: element at position 1 should be null, but got {actual_1:?}"
×
522
    );
523

524
    // Check third element (from index 2)
525
    let expected_2 = array.scalar_at(2).vortex_unwrap().into_nullable();
3,712✔
526
    let actual_2 = taken.scalar_at(2).vortex_unwrap();
3,712✔
527
    assert_eq!(
3,712✔
528
        actual_2, expected_2,
529
        "Take with nullable indices: element at position 2 should be from array index 2. \
×
530
         Expected: {expected_2:?}, Actual: {actual_2:?}"
×
531
    );
532
}
4,221✔
533

534
/// Tests large array consistency
535
fn test_large_array_consistency(array: &dyn Array) {
4,221✔
536
    let len = array.len();
4,221✔
537
    if len < 1000 {
4,221✔
538
        return;
3,377✔
539
    }
844✔
540

541
    // Test with every 10th element
542
    let indices: Vec<u64> = (0..len).step_by(10).map(|i| i as u64).collect();
162,520✔
543
    let indices_array = PrimitiveArray::from_iter(indices).into_array();
844✔
544
    let taken = take(array, &indices_array).vortex_unwrap();
844✔
545

546
    // Create equivalent filter mask
547
    let mask_pattern: Vec<bool> = (0..len).map(|i| i % 10 == 0).collect();
1,624,592✔
548
    let mask = Mask::try_from(&BoolArray::from_iter(mask_pattern)).vortex_unwrap();
844✔
549
    let filtered = filter(array, &mask).vortex_unwrap();
844✔
550

551
    // Results should match
552
    assert_eq!(taken.len(), filtered.len());
844✔
553
    for i in 0..taken.len() {
162,520✔
554
        assert_eq!(
162,520✔
555
            taken.scalar_at(i).vortex_unwrap(),
162,520✔
556
            filtered.scalar_at(i).vortex_unwrap()
162,520✔
557
        );
558
    }
559
}
4,221✔
560

561
/// Tests that comparison operations follow inverse relationships.
562
///
563
/// # Invariants
564
/// - `compare(array, value, Eq)` is the inverse of `compare(array, value, NotEq)`
565
/// - `compare(array, value, Gt)` is the inverse of `compare(array, value, Lte)`
566
/// - `compare(array, value, Lt)` is the inverse of `compare(array, value, Gte)`
567
///
568
/// # Test Details
569
/// - Creates comparison results for each operator
570
/// - Verifies that inverse operations produce opposite boolean values
571
/// - Tests with multiple scalar values to ensure consistency
572
///
573
/// # Why This Matters
574
/// Comparison operations must maintain logical consistency across encodings.
575
/// This test catches bugs where an encoding might implement one comparison
576
/// correctly but fail on its logical inverse.
577
fn test_comparison_inverse_consistency(array: &dyn Array) {
4,221✔
578
    let len = array.len();
4,221✔
579
    if len == 0 {
4,221✔
580
        return;
1✔
581
    }
4,220✔
582

583
    // Skip non-comparable types
584
    match array.dtype() {
4,220✔
585
        DType::Null | DType::Extension(_) => return,
312✔
586
        DType::Struct(..) | DType::List(..) => return,
10✔
587
        _ => {}
3,898✔
588
    }
589

590
    // Get a test value from the middle of the array
591
    let test_scalar = match array.scalar_at(len / 2) {
3,898✔
592
        Ok(s) => s,
3,898✔
UNCOV
593
        Err(_) => return,
×
594
    };
595

596
    // Test Eq vs NotEq
597
    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
3,898✔
598
    if let (Ok(eq_result), Ok(neq_result)) = (
3,594✔
599
        compare(array, const_array.as_ref(), Operator::Eq),
3,898✔
600
        compare(array, const_array.as_ref(), Operator::NotEq),
3,898✔
601
    ) {
602
        let inverted_eq = invert(&eq_result).vortex_unwrap();
3,594✔
603

604
        assert_eq!(
3,594✔
605
            inverted_eq.len(),
3,594✔
606
            neq_result.len(),
3,594✔
UNCOV
607
            "Inverted Eq should have same length as NotEq"
×
608
        );
609

610
        for i in 0..inverted_eq.len() {
1,417,880✔
611
            let inv_val = inverted_eq.scalar_at(i).vortex_unwrap();
1,417,880✔
612
            let neq_val = neq_result.scalar_at(i).vortex_unwrap();
1,417,880✔
613
            assert_eq!(
1,417,880✔
614
                inv_val, neq_val,
UNCOV
615
                "At index {i}: NOT(Eq) should equal NotEq. \
×
UNCOV
616
                 NOT(Eq) = {inv_val:?}, NotEq = {neq_val:?}"
×
617
            );
618
        }
619
    }
304✔
620

621
    // Test Gt vs Lte
622
    if let (Ok(gt_result), Ok(lte_result)) = (
3,898✔
623
        compare(array, const_array.as_ref(), Operator::Gt),
3,898✔
624
        compare(array, const_array.as_ref(), Operator::Lte),
3,898✔
625
    ) {
626
        let inverted_gt = invert(&gt_result).vortex_unwrap();
3,898✔
627

628
        for i in 0..inverted_gt.len() {
1,592,604✔
629
            let inv_val = inverted_gt.scalar_at(i).vortex_unwrap();
1,592,604✔
630
            let lte_val = lte_result.scalar_at(i).vortex_unwrap();
1,592,604✔
631
            assert_eq!(
1,592,604✔
632
                inv_val, lte_val,
UNCOV
633
                "At index {i}: NOT(Gt) should equal Lte. \
×
UNCOV
634
                 NOT(Gt) = {inv_val:?}, Lte = {lte_val:?}"
×
635
            );
636
        }
UNCOV
637
    }
×
638

639
    // Test Lt vs Gte
640
    if let (Ok(lt_result), Ok(gte_result)) = (
3,898✔
641
        compare(array, const_array.as_ref(), Operator::Lt),
3,898✔
642
        compare(array, const_array.as_ref(), Operator::Gte),
3,898✔
643
    ) {
644
        let inverted_lt = invert(&lt_result).vortex_unwrap();
3,898✔
645

646
        for i in 0..inverted_lt.len() {
1,592,604✔
647
            let inv_val = inverted_lt.scalar_at(i).vortex_unwrap();
1,592,604✔
648
            let gte_val = gte_result.scalar_at(i).vortex_unwrap();
1,592,604✔
649
            assert_eq!(
1,592,604✔
650
                inv_val, gte_val,
UNCOV
651
                "At index {i}: NOT(Lt) should equal Gte. \
×
UNCOV
652
                 NOT(Lt) = {inv_val:?}, Gte = {gte_val:?}"
×
653
            );
654
        }
UNCOV
655
    }
×
656
}
4,221✔
657

658
/// Tests that comparison operations maintain proper symmetry relationships.
659
///
660
/// # Invariants
661
/// - `compare(array, value, Gt)` should equal `compare_scalar_array(value, array, Lt)`
662
/// - `compare(array, value, Lt)` should equal `compare_scalar_array(value, array, Gt)`
663
/// - `compare(array, value, Eq)` should equal `compare_scalar_array(value, array, Eq)`
664
///
665
/// # Test Details
666
/// - Compares array-scalar operations with their symmetric scalar-array versions
667
/// - Verifies that ordering relationships are properly reversed
668
/// - Tests equality which should be symmetric
669
///
670
/// # Why This Matters
671
/// Ensures that comparison operations maintain mathematical ordering properties
672
/// regardless of operand order.
673
fn test_comparison_symmetry_consistency(array: &dyn Array) {
4,221✔
674
    let len = array.len();
4,221✔
675
    if len == 0 {
4,221✔
676
        return;
1✔
677
    }
4,220✔
678

679
    // Skip non-comparable types
680
    match array.dtype() {
4,220✔
681
        DType::Null | DType::Extension(_) => return,
312✔
682
        DType::Struct(..) | DType::List(..) => return,
10✔
683
        _ => {}
3,898✔
684
    }
685

686
    // Get test values
687
    let test_scalar = match array.scalar_at(len / 2) {
3,898✔
688
        Ok(s) => s,
3,898✔
UNCOV
689
        Err(_) => return,
×
690
    };
691

692
    // Create a constant array with the test scalar for reverse comparison
693
    let const_array = crate::arrays::ConstantArray::new(test_scalar, len);
3,898✔
694

695
    // Test Gt vs Lt symmetry
696
    if let (Ok(arr_gt_scalar), Ok(scalar_lt_arr)) = (
3,898✔
697
        compare(array, const_array.as_ref(), Operator::Gt),
3,898✔
698
        compare(const_array.as_ref(), array, Operator::Lt),
3,898✔
699
    ) {
700
        assert_eq!(
3,898✔
701
            arr_gt_scalar.len(),
3,898✔
702
            scalar_lt_arr.len(),
3,898✔
UNCOV
703
            "Symmetric comparisons should have same length"
×
704
        );
705

706
        for i in 0..arr_gt_scalar.len() {
1,592,604✔
707
            let arr_gt = arr_gt_scalar.scalar_at(i).vortex_unwrap();
1,592,604✔
708
            let scalar_lt = scalar_lt_arr.scalar_at(i).vortex_unwrap();
1,592,604✔
709
            assert_eq!(
1,592,604✔
710
                arr_gt, scalar_lt,
UNCOV
711
                "At index {i}: (array > scalar) should equal (scalar < array). \
×
UNCOV
712
                 array > scalar = {arr_gt:?}, scalar < array = {scalar_lt:?}"
×
713
            );
714
        }
UNCOV
715
    }
×
716

717
    // Test Eq symmetry
718
    if let (Ok(arr_eq_scalar), Ok(scalar_eq_arr)) = (
3,594✔
719
        compare(array, const_array.as_ref(), Operator::Eq),
3,898✔
720
        compare(const_array.as_ref(), array, Operator::Eq),
3,898✔
721
    ) {
722
        for i in 0..arr_eq_scalar.len() {
1,417,880✔
723
            let arr_eq = arr_eq_scalar.scalar_at(i).vortex_unwrap();
1,417,880✔
724
            let scalar_eq = scalar_eq_arr.scalar_at(i).vortex_unwrap();
1,417,880✔
725
            assert_eq!(
1,417,880✔
726
                arr_eq, scalar_eq,
UNCOV
727
                "At index {i}: (array == scalar) should equal (scalar == array). \
×
UNCOV
728
                 array == scalar = {arr_eq:?}, scalar == array = {scalar_eq:?}"
×
729
            );
730
        }
731
    }
304✔
732
}
4,221✔
733

734
/// Tests that boolean operations follow De Morgan's laws.
735
///
736
/// # Invariants
737
/// - `NOT(A AND B)` equals `(NOT A) OR (NOT B)`
738
/// - `NOT(A OR B)` equals `(NOT A) AND (NOT B)`
739
///
740
/// # Test Details
741
/// - If the array is boolean, uses it directly for testing boolean operations
742
/// - Creates two boolean masks from patterns based on the array
743
/// - Computes AND/OR operations and their inversions
744
/// - Verifies De Morgan's laws hold for all elements
745
///
746
/// # Why This Matters
747
/// Boolean operations must maintain logical consistency across encodings.
748
/// This test catches bugs where encodings might optimize boolean operations
749
/// incorrectly, breaking fundamental logical properties.
750
fn test_boolean_demorgan_consistency(array: &dyn Array) {
4,221✔
751
    if !matches!(array.dtype(), DType::Bool(_)) {
4,221✔
752
        return;
4,208✔
753
    }
13✔
754

755
    let mask = {
13✔
756
        let mask_pattern: Vec<bool> = (0..array.len()).map(|i| i % 3 == 0).collect();
6,052✔
757
        BoolArray::from_iter(mask_pattern)
13✔
758
    };
759
    let mask = mask.as_ref();
13✔
760

761
    // Test first De Morgan's law: NOT(A AND B) = (NOT A) OR (NOT B)
762
    if let (Ok(a_and_b), Ok(not_a), Ok(not_b)) = (and(array, mask), invert(array), invert(mask)) {
13✔
763
        let not_a_and_b = invert(&a_and_b).vortex_unwrap();
13✔
764
        let not_a_or_not_b = or(&not_a, &not_b).vortex_unwrap();
13✔
765

766
        assert_eq!(
13✔
767
            not_a_and_b.len(),
13✔
768
            not_a_or_not_b.len(),
13✔
UNCOV
769
            "De Morgan's law results should have same length"
×
770
        );
771

772
        for i in 0..not_a_and_b.len() {
6,052✔
773
            let left = not_a_and_b.scalar_at(i).vortex_unwrap();
6,052✔
774
            let right = not_a_or_not_b.scalar_at(i).vortex_unwrap();
6,052✔
775
            assert_eq!(
6,052✔
776
                left, right,
UNCOV
777
                "De Morgan's first law failed at index {i}: \
×
UNCOV
778
                 NOT(A AND B) = {left:?}, (NOT A) OR (NOT B) = {right:?}"
×
779
            );
780
        }
UNCOV
781
    }
×
782

783
    // Test second De Morgan's law: NOT(A OR B) = (NOT A) AND (NOT B)
784
    if let (Ok(a_or_b), Ok(not_a), Ok(not_b)) = (or(array, mask), invert(array), invert(mask)) {
13✔
785
        let not_a_or_b = invert(&a_or_b).vortex_unwrap();
13✔
786
        let not_a_and_not_b = and(&not_a, &not_b).vortex_unwrap();
13✔
787

788
        for i in 0..not_a_or_b.len() {
6,052✔
789
            let left = not_a_or_b.scalar_at(i).vortex_unwrap();
6,052✔
790
            let right = not_a_and_not_b.scalar_at(i).vortex_unwrap();
6,052✔
791
            assert_eq!(
6,052✔
792
                left, right,
UNCOV
793
                "De Morgan's second law failed at index {i}: \
×
UNCOV
794
                 NOT(A OR B) = {left:?}, (NOT A) AND (NOT B) = {right:?}"
×
795
            );
796
        }
UNCOV
797
    }
×
798
}
4,221✔
799

800
/// Tests that slice and aggregate operations produce consistent results.
801
///
802
/// # Invariants
803
/// - Aggregating a sliced array should equal aggregating the corresponding
804
///   elements from the canonical form
805
/// - This applies to sum, count, min/max, and other aggregate functions
806
///
807
/// # Test Details
808
/// - Slices the array and computes aggregates
809
/// - Compares against aggregating the canonical form's slice
810
/// - Tests multiple aggregate functions where applicable
811
///
812
/// # Why This Matters
813
/// Aggregate operations on sliced arrays must produce correct results
814
/// regardless of the underlying encoding's offset handling.
815
fn test_slice_aggregate_consistency(array: &dyn Array) {
4,221✔
816
    use vortex_dtype::DType;
817

818
    use crate::compute::{min_max, nan_count, sum};
819

820
    let len = array.len();
4,221✔
821
    if len < 5 {
4,221✔
822
        return; // Need enough elements for meaningful slice
707✔
823
    }
3,514✔
824

825
    // Define slice bounds
826
    let start = 1;
3,514✔
827
    let end = (len - 1).min(start + 10); // Take up to 10 elements
3,514✔
828

829
    // Get sliced array and canonical slice
830
    let sliced = array.slice(start, end).vortex_unwrap();
3,514✔
831
    let canonical = array.to_canonical().vortex_unwrap();
3,514✔
832
    let canonical_sliced = canonical.as_ref().slice(start, end).vortex_unwrap();
3,514✔
833

834
    // Test null count through invalid_count
835
    if let (Ok(slice_null_count), Ok(canonical_null_count)) =
3,514✔
836
        (sliced.invalid_count(), canonical_sliced.invalid_count())
3,514✔
837
    {
838
        assert_eq!(
3,514✔
839
            slice_null_count, canonical_null_count,
UNCOV
840
            "null_count on sliced array should match canonical. \
×
UNCOV
841
             Sliced: {slice_null_count}, Canonical: {canonical_null_count}"
×
842
        );
UNCOV
843
    }
×
844

845
    // Test sum for numeric types
846
    if !matches!(array.dtype(), DType::Primitive(..)) {
3,514✔
847
        return;
684✔
848
    }
2,830✔
849

850
    if let (Ok(slice_sum), Ok(canonical_sum)) = (sum(&sliced), sum(&canonical_sliced)) {
2,830✔
851
        // Compare sum scalars
852
        assert_eq!(
2,830✔
853
            slice_sum, canonical_sum,
UNCOV
854
            "sum on sliced array should match canonical. \
×
UNCOV
855
                 Sliced: {slice_sum:?}, Canonical: {canonical_sum:?}"
×
856
        );
UNCOV
857
    }
×
858

859
    // Test min_max
860
    if let (Ok(slice_minmax), Ok(canonical_minmax)) = (min_max(&sliced), min_max(&canonical_sliced))
2,830✔
861
    {
862
        match (slice_minmax, canonical_minmax) {
2,830✔
863
            (Some(s_result), Some(c_result)) => {
2,791✔
864
                assert_eq!(
2,791✔
865
                    s_result.min, c_result.min,
UNCOV
866
                    "min on sliced array should match canonical. \
×
UNCOV
867
                         Sliced: {:?}, Canonical: {:?}",
×
868
                    s_result.min, c_result.min
869
                );
870
                assert_eq!(
2,791✔
871
                    s_result.max, c_result.max,
UNCOV
872
                    "max on sliced array should match canonical. \
×
UNCOV
873
                         Sliced: {:?}, Canonical: {:?}",
×
874
                    s_result.max, c_result.max
875
                );
876
            }
877
            (None, None) => {} // Both empty, OK
39✔
UNCOV
878
            _ => vortex_panic!("min_max results don't match"),
×
879
        }
UNCOV
880
    }
×
881

882
    // Test nan_count for floating point types
883
    if array.dtype().is_float() {
2,830✔
884
        if let (Ok(slice_nan_count), Ok(canonical_nan_count)) =
537✔
885
            (nan_count(&sliced), nan_count(&canonical_sliced))
537✔
886
        {
887
            assert_eq!(
537✔
888
                slice_nan_count, canonical_nan_count,
UNCOV
889
                "nan_count on sliced array should match canonical. \
×
UNCOV
890
                 Sliced: {slice_nan_count}, Canonical: {canonical_nan_count}"
×
891
            );
UNCOV
892
        }
×
893
    }
2,293✔
894
}
4,221✔
895

896
/// Tests that cast operations preserve array properties when sliced.
897
///
898
/// # Invariant
899
/// `cast(slice(array, start, end), dtype)` should equal `slice(cast(array, dtype), start, end)`
900
///
901
/// # Test Details
902
/// - Slices the array from index 2 to 7 (or len-2 if smaller)
903
/// - Casts the sliced array to a different type
904
/// - Compares against the canonical form of the array (without slicing or casting the canonical form)
905
/// - Verifies both approaches produce identical results
906
///
907
/// # Why This Matters
908
/// This test specifically catches bugs where encodings (like RunEndArray) fail to preserve
909
/// offset information during cast operations. Such bugs can lead to incorrect data being
910
/// returned after casting a sliced array.
911
fn test_cast_slice_consistency(array: &dyn Array) {
4,221✔
912
    let len = array.len();
4,221✔
913
    if len < 5 {
4,221✔
914
        return; // Need at least 5 elements for meaningful slice
707✔
915
    }
3,514✔
916

917
    // Define slice bounds
918
    let start = 2;
3,514✔
919
    let end = 7.min(len - 2).max(start + 1); // Ensure we have at least 1 element
3,514✔
920

921
    // Get canonical form of the original array
922
    let canonical = array.to_canonical().vortex_unwrap();
3,514✔
923

924
    // Choose appropriate target dtype based on the array's type
925
    let target_dtypes = match array.dtype() {
3,514✔
926
        DType::Null => vec![],
3✔
927
        DType::Bool(nullability) => vec![
10✔
928
            DType::Primitive(PType::U8, *nullability),
10✔
929
            DType::Primitive(PType::I32, *nullability),
10✔
930
        ],
931
        DType::Primitive(ptype, nullability) => {
2,830✔
932
            let mut targets = vec![];
2,830✔
933
            // Test nullability changes
934
            let opposite_nullability = match nullability {
2,830✔
935
                Nullability::NonNullable => Nullability::Nullable,
2,216✔
936
                Nullability::Nullable => Nullability::NonNullable,
614✔
937
            };
938
            targets.push(DType::Primitive(*ptype, opposite_nullability));
2,830✔
939

940
            // Test widening casts
941
            match ptype {
2,830✔
942
                PType::U8 => {
152✔
943
                    targets.push(DType::Primitive(PType::U16, *nullability));
152✔
944
                    targets.push(DType::Primitive(PType::I16, *nullability));
152✔
945
                }
152✔
946
                PType::U16 => {
190✔
947
                    targets.push(DType::Primitive(PType::U32, *nullability));
190✔
948
                    targets.push(DType::Primitive(PType::I32, *nullability));
190✔
949
                }
190✔
950
                PType::U32 => {
267✔
951
                    targets.push(DType::Primitive(PType::U64, *nullability));
267✔
952
                    targets.push(DType::Primitive(PType::I64, *nullability));
267✔
953
                }
267✔
954
                PType::U64 => {
228✔
955
                    targets.push(DType::Primitive(PType::F64, *nullability));
228✔
956
                }
228✔
957
                PType::I8 => {
38✔
958
                    targets.push(DType::Primitive(PType::I16, *nullability));
38✔
959
                    targets.push(DType::Primitive(PType::F32, *nullability));
38✔
960
                }
38✔
961
                PType::I16 => {
115✔
962
                    targets.push(DType::Primitive(PType::I32, *nullability));
115✔
963
                    targets.push(DType::Primitive(PType::F32, *nullability));
115✔
964
                }
115✔
965
                PType::I32 => {
1,034✔
966
                    targets.push(DType::Primitive(PType::I64, *nullability));
1,034✔
967
                    targets.push(DType::Primitive(PType::F64, *nullability));
1,034✔
968
                }
1,034✔
969
                PType::I64 => {
269✔
970
                    targets.push(DType::Primitive(PType::F64, *nullability));
269✔
971
                }
269✔
UNCOV
972
                PType::F16 => {
×
UNCOV
973
                    targets.push(DType::Primitive(PType::F32, *nullability));
×
UNCOV
974
                }
×
975
                PType::F32 => {
344✔
976
                    targets.push(DType::Primitive(PType::F64, *nullability));
344✔
977
                    targets.push(DType::Primitive(PType::I32, *nullability));
344✔
978
                }
344✔
979
                PType::F64 => {
193✔
980
                    targets.push(DType::Primitive(PType::I64, *nullability));
193✔
981
                }
193✔
982
            }
983
            targets
2,830✔
984
        }
985
        DType::Utf8(nullability) => {
238✔
986
            let opposite = match nullability {
238✔
987
                Nullability::NonNullable => Nullability::Nullable,
160✔
988
                Nullability::Nullable => Nullability::NonNullable,
78✔
989
            };
990
            vec![DType::Utf8(opposite), DType::Binary(*nullability)]
238✔
991
        }
992
        DType::Binary(nullability) => {
3✔
993
            let opposite = match nullability {
3✔
994
                Nullability::NonNullable => Nullability::Nullable,
2✔
995
                Nullability::Nullable => Nullability::NonNullable,
1✔
996
            };
997
            vec![
3✔
998
                DType::Binary(opposite),
3✔
999
                DType::Utf8(*nullability), // May fail if not valid UTF-8
3✔
1000
            ]
1001
        }
1002
        DType::Decimal(decimal_type, nullability) => {
268✔
1003
            let opposite = match nullability {
268✔
1004
                Nullability::NonNullable => Nullability::Nullable,
191✔
1005
                Nullability::Nullable => Nullability::NonNullable,
77✔
1006
            };
1007
            vec![DType::Decimal(*decimal_type, opposite)]
268✔
1008
        }
1009
        DType::Struct(fields, nullability) => {
4✔
1010
            let opposite = match nullability {
4✔
1011
                Nullability::NonNullable => Nullability::Nullable,
4✔
UNCOV
1012
                Nullability::Nullable => Nullability::NonNullable,
×
1013
            };
1014
            vec![DType::Struct(fields.clone(), opposite)]
4✔
1015
        }
1016
        DType::List(element_type, nullability) => {
3✔
1017
            let opposite = match nullability {
3✔
1018
                Nullability::NonNullable => Nullability::Nullable,
3✔
UNCOV
1019
                Nullability::Nullable => Nullability::NonNullable,
×
1020
            };
1021
            vec![DType::List(element_type.clone(), opposite)]
3✔
1022
        }
1023
        DType::Extension(_) => vec![], // Extension types typically only cast to themselves
155✔
1024
    };
1025

1026
    // Test each target dtype
1027
    for target_dtype in target_dtypes {
12,091✔
1028
        // Slice the array
1029
        let sliced = array.slice(start, end).vortex_unwrap();
8,577✔
1030

1031
        // Try to cast the sliced array
1032
        let slice_then_cast = match cast(&sliced, &target_dtype) {
8,577✔
1033
            Ok(result) => result,
8,162✔
1034
            Err(_) => continue, // Skip if cast fails
415✔
1035
        };
1036

1037
        // Verify against canonical form
1038
        assert_eq!(
8,162✔
1039
            slice_then_cast.len(),
8,162✔
1040
            end - start,
8,162✔
UNCOV
1041
            "Sliced and casted array should have length {}, but has {}",
×
UNCOV
1042
            end - start,
×
UNCOV
1043
            slice_then_cast.len()
×
1044
        );
1045

1046
        // Compare each value against the canonical form
1047
        for i in 0..slice_then_cast.len() {
20,201✔
1048
            let slice_cast_val = slice_then_cast.scalar_at(i).vortex_unwrap();
20,201✔
1049

1050
            // Get the corresponding value from the canonical array (adjusted for slice offset)
1051
            let canonical_val = canonical.as_ref().scalar_at(start + i).vortex_unwrap();
20,201✔
1052

1053
            // Cast the canonical scalar to the target dtype
1054
            let expected_val = match canonical_val.cast(&target_dtype) {
20,201✔
1055
                Ok(val) => val,
19,702✔
1056
                Err(_) => {
1057
                    // If scalar cast fails, we can't compare - skip this target dtype
1058
                    // This can happen for some type conversions that aren't supported at scalar level
1059
                    break;
499✔
1060
                }
1061
            };
1062

1063
            assert_eq!(
19,702✔
1064
                slice_cast_val,
1065
                expected_val,
UNCOV
1066
                "Cast of sliced array produced incorrect value at index {i}. \
×
UNCOV
1067
                 Got: {slice_cast_val:?}, Expected: {expected_val:?} \
×
UNCOV
1068
                 (canonical value at index {}: {canonical_val:?})\n\
×
UNCOV
1069
                 This likely indicates the array encoding doesn't preserve offset information during cast.",
×
UNCOV
1070
                start + i
×
1071
            );
1072
        }
1073

1074
        // Also test the other way: cast then slice
1075
        let casted = match cast(array, &target_dtype) {
8,162✔
1076
            Ok(result) => result,
7,507✔
1077
            Err(_) => continue, // Skip if cast fails
655✔
1078
        };
1079
        let cast_then_slice = casted.slice(start, end).vortex_unwrap();
7,507✔
1080

1081
        // Verify the two approaches produce identical results
1082
        assert_eq!(
7,507✔
1083
            slice_then_cast.len(),
7,507✔
1084
            cast_then_slice.len(),
7,507✔
UNCOV
1085
            "Slice-then-cast and cast-then-slice should produce arrays of the same length"
×
1086
        );
1087

1088
        for i in 0..slice_then_cast.len() {
19,853✔
1089
            let slice_cast_val = slice_then_cast.scalar_at(i).vortex_unwrap();
19,853✔
1090
            let cast_slice_val = cast_then_slice.scalar_at(i).vortex_unwrap();
19,853✔
1091
            assert_eq!(
19,853✔
1092
                slice_cast_val, cast_slice_val,
UNCOV
1093
                "Slice-then-cast and cast-then-slice produced different values at index {i}. \
×
UNCOV
1094
                 Slice-then-cast: {slice_cast_val:?}, Cast-then-slice: {cast_slice_val:?}"
×
1095
            );
1096
        }
1097
    }
1098
}
4,221✔
1099

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

1149
    // Boolean operations
1150
    test_boolean_demorgan_consistency(array);
4,221✔
1151

1152
    // Comparison operations
1153
    test_comparison_inverse_consistency(array);
4,221✔
1154
    test_comparison_symmetry_consistency(array);
4,221✔
1155

1156
    // Aggregate operations
1157
    test_slice_aggregate_consistency(array);
4,221✔
1158

1159
    // Identity operations
1160
    test_filter_identity(array);
4,221✔
1161
    test_mask_identity(array);
4,221✔
1162
    test_take_preserves_properties(array);
4,221✔
1163

1164
    // Ordering and correctness
1165
    test_filter_preserves_order(array);
4,221✔
1166
    test_take_repeated_indices(array);
4,221✔
1167

1168
    // Null handling
1169
    test_mask_filter_null_consistency(array);
4,221✔
1170
    test_nullable_indices_consistency(array);
4,221✔
1171

1172
    // Edge cases
1173
    test_empty_operations_consistency(array);
4,221✔
1174
    test_large_array_consistency(array);
4,221✔
1175
}
4,221✔
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