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

vortex-data / vortex / 16992684502

15 Aug 2025 02:56PM UTC coverage: 87.875% (+0.2%) from 87.72%
16992684502

Pull #2456

github

web-flow
Merge 2d540e578 into 4a23f65b3
Pull Request #2456: feat: basic BoolBuffer / BoolBufferMut

1275 of 1428 new or added lines in 110 files covered. (89.29%)

334 existing lines in 31 files now uncovered.

57169 of 65057 relevant lines covered (87.88%)

658056.52 hits per line

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

82.41
/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).vortex_unwrap();
1,186,224✔
77
        let taken_val = taken.scalar_at(i).vortex_unwrap();
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).vortex_unwrap();
1,780,145✔
141
        let direct_val = directly_masked.scalar_at(i).vortex_unwrap();
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).vortex_unwrap();
1,780,145✔
185
        let filtered_val = filtered.scalar_at(i).vortex_unwrap();
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).vortex_unwrap();
1,780,145✔
234
        let masked_val = masked.scalar_at(i).vortex_unwrap();
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)).vortex_unwrap();
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).vortex_unwrap();
13,173✔
285
        let sliced_val = sliced.scalar_at(i).vortex_unwrap();
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).vortex_unwrap();
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).vortex_unwrap();
13,489✔
332
        let sliced_val = sliced.scalar_at(i).vortex_unwrap();
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!(
4,391✔
358
            filtered.scalar_at(0).vortex_unwrap(),
4,391✔
359
            array.scalar_at(0).vortex_unwrap()
4,391✔
360
        );
361
        assert_eq!(
4,391✔
362
            filtered.scalar_at(1).vortex_unwrap(),
4,391✔
363
            array.scalar_at(2).vortex_unwrap()
4,391✔
364
        );
365
        assert_eq!(
4,391✔
366
            filtered.scalar_at(2).vortex_unwrap(),
4,391✔
367
            array.scalar_at(3).vortex_unwrap()
4,391✔
368
        );
369
    }
×
370
}
5,266✔
371

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

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

383
    assert_eq!(taken.len(), 3);
5,265✔
384
    for i in 0..3 {
21,060✔
385
        assert_eq!(
15,795✔
386
            taken.scalar_at(i).vortex_unwrap(),
15,795✔
387
            array.scalar_at(0).vortex_unwrap()
15,795✔
388
        );
389
    }
390
}
5,266✔
391

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

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

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

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

412
    assert_eq!(filtered.len(), direct_filtered.len());
4,549✔
413
    for i in 0..filtered.len() {
888,230✔
414
        assert_eq!(
888,230✔
415
            filtered.scalar_at(i).vortex_unwrap(),
888,230✔
416
            direct_filtered.scalar_at(i).vortex_unwrap()
888,230✔
417
        );
418
    }
419
}
5,266✔
420

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

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

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

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

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

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

455
    // Should be identical to original
456
    assert_eq!(taken.len(), array.len());
5,265✔
457
    assert_eq!(taken.dtype(), array.dtype());
5,265✔
458
    for i in 0..len {
1,780,145✔
459
        assert_eq!(
1,780,145✔
460
            taken.scalar_at(i).vortex_unwrap(),
1,780,145✔
461
            array.scalar_at(i).vortex_unwrap()
1,780,145✔
462
        );
463
    }
464
}
5,266✔
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) {
5,266✔
484
    let len = array.len();
5,266✔
485
    if len < 3 {
5,266✔
486
        return; // Need at least 3 elements to test indices 0 and 2
717✔
487
    }
4,549✔
488

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

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

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

502
    assert!(
4,549✔
503
        taken.dtype().is_nullable(),
4,549✔
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();
4,549✔
510
    let actual_0 = taken.scalar_at(0).vortex_unwrap();
4,549✔
511
    assert_eq!(
4,549✔
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();
4,549✔
519
    assert!(
4,549✔
520
        actual_1.is_null(),
4,549✔
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();
4,549✔
526
    let actual_2 = taken.scalar_at(2).vortex_unwrap();
4,549✔
527
    assert_eq!(
4,549✔
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
}
5,266✔
533

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

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

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

551
    // Results should match
552
    assert_eq!(taken.len(), filtered.len());
944✔
553
    for i in 0..taken.len() {
174,560✔
554
        assert_eq!(
174,560✔
555
            taken.scalar_at(i).vortex_unwrap(),
174,560✔
556
            filtered.scalar_at(i).vortex_unwrap()
174,560✔
557
        );
558
    }
559
}
5,266✔
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) {
5,266✔
578
    let len = array.len();
5,266✔
579
    if len == 0 {
5,266✔
580
        return;
1✔
581
    }
5,265✔
582

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

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

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

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

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

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

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

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

646
        for i in 0..inverted_lt.len() {
1,719,261✔
647
            let inv_val = inverted_lt.scalar_at(i).vortex_unwrap();
1,719,261✔
648
            let gte_val = gte_result.scalar_at(i).vortex_unwrap();
1,719,261✔
649
            assert_eq!(
1,719,261✔
650
                inv_val, gte_val,
651
                "At index {i}: NOT(Lt) should equal Gte. \
×
652
                 NOT(Lt) = {inv_val:?}, Gte = {gte_val:?}"
×
653
            );
654
        }
655
    }
×
656
}
5,266✔
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) {
5,266✔
674
    let len = array.len();
5,266✔
675
    if len == 0 {
5,266✔
676
        return;
1✔
677
    }
5,265✔
678

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

686
    // Get test values
687
    let test_scalar = match array.scalar_at(len / 2) {
4,935✔
688
        Ok(s) => s,
4,935✔
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);
4,935✔
694

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

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

717
    // Test Eq symmetry
718
    if let (Ok(arr_eq_scalar), Ok(scalar_eq_arr)) = (
4,935✔
719
        compare(array, const_array.as_ref(), Operator::Eq),
4,935✔
720
        compare(const_array.as_ref(), array, Operator::Eq),
4,935✔
721
    ) {
722
        for i in 0..arr_eq_scalar.len() {
1,719,261✔
723
            let arr_eq = arr_eq_scalar.scalar_at(i).vortex_unwrap();
1,719,261✔
724
            let scalar_eq = scalar_eq_arr.scalar_at(i).vortex_unwrap();
1,719,261✔
725
            assert_eq!(
1,719,261✔
726
                arr_eq, scalar_eq,
727
                "At index {i}: (array == scalar) should equal (scalar == array). \
×
728
                 array == scalar = {arr_eq:?}, scalar == array = {scalar_eq:?}"
×
729
            );
730
        }
UNCOV
731
    }
×
732
}
5,266✔
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) {
5,266✔
751
    if !matches!(array.dtype(), DType::Bool(_)) {
5,266✔
752
        return;
4,941✔
753
    }
325✔
754

755
    let mask = {
325✔
756
        let mask_pattern: Vec<bool> = (0..array.len()).map(|i| i % 3 == 0).collect();
7,066✔
757
        BoolArray::from_iter(mask_pattern)
325✔
758
    };
759
    let mask = mask.as_ref();
325✔
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)) {
325✔
763
        let not_a_and_b = invert(&a_and_b).vortex_unwrap();
325✔
764
        let not_a_or_not_b = or(&not_a, &not_b).vortex_unwrap();
325✔
765

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

772
        for i in 0..not_a_and_b.len() {
7,066✔
773
            let left = not_a_and_b.scalar_at(i).vortex_unwrap();
7,066✔
774
            let right = not_a_or_not_b.scalar_at(i).vortex_unwrap();
7,066✔
775
            assert_eq!(
7,066✔
776
                left, right,
777
                "De Morgan's first law failed at index {i}: \
×
778
                 NOT(A AND B) = {left:?}, (NOT A) OR (NOT B) = {right:?}"
×
779
            );
780
        }
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)) {
325✔
785
        let not_a_or_b = invert(&a_or_b).vortex_unwrap();
325✔
786
        let not_a_and_not_b = and(&not_a, &not_b).vortex_unwrap();
325✔
787

788
        for i in 0..not_a_or_b.len() {
7,066✔
789
            let left = not_a_or_b.scalar_at(i).vortex_unwrap();
7,066✔
790
            let right = not_a_and_not_b.scalar_at(i).vortex_unwrap();
7,066✔
791
            assert_eq!(
7,066✔
792
                left, right,
793
                "De Morgan's second law failed at index {i}: \
×
794
                 NOT(A OR B) = {left:?}, (NOT A) AND (NOT B) = {right:?}"
×
795
            );
796
        }
797
    }
×
798
}
5,266✔
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) {
5,266✔
816
    use vortex_dtype::DType;
817

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

820
    let len = array.len();
5,266✔
821
    if len < 5 {
5,266✔
822
        return; // Need enough elements for meaningful slice
1,037✔
823
    }
4,229✔
824

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

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

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

845
    // Test sum for numeric types
846
    if !matches!(array.dtype(), DType::Primitive(..)) {
4,229✔
847
        return;
818✔
848
    }
3,411✔
849

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

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

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

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

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

920
    // Get canonical form of the original array
921
    let canonical = array.to_canonical().vortex_unwrap();
4,229✔
922

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

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

1025
    // Test each target dtype
1026
    for target_dtype in target_dtypes {
14,667✔
1027
        // Slice the array
1028
        let sliced = array.slice(start, end).vortex_unwrap();
10,438✔
1029

1030
        // Try to cast the sliced array
1031
        let slice_then_cast = match cast(&sliced, &target_dtype) {
10,438✔
1032
            Ok(result) => result,
9,506✔
1033
            Err(_) => continue, // Skip if cast fails
932✔
1034
        };
1035

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

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

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

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

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

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

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

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

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

1148
    // Boolean operations
1149
    test_boolean_demorgan_consistency(array);
5,266✔
1150

1151
    // Comparison operations
1152
    test_comparison_inverse_consistency(array);
5,266✔
1153
    test_comparison_symmetry_consistency(array);
5,266✔
1154

1155
    // Aggregate operations
1156
    test_slice_aggregate_consistency(array);
5,266✔
1157

1158
    // Identity operations
1159
    test_filter_identity(array);
5,266✔
1160
    test_mask_identity(array);
5,266✔
1161
    test_take_preserves_properties(array);
5,266✔
1162

1163
    // Ordering and correctness
1164
    test_filter_preserves_order(array);
5,266✔
1165
    test_take_repeated_indices(array);
5,266✔
1166

1167
    // Null handling
1168
    test_mask_filter_null_consistency(array);
5,266✔
1169
    test_nullable_indices_consistency(array);
5,266✔
1170

1171
    // Edge cases
1172
    test_empty_operations_consistency(array);
5,266✔
1173
    test_large_array_consistency(array);
5,266✔
1174
}
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