sochdb-query 2.0.4

SochDB query engine (sync-first execution and vector query planning)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! SIMD Vectorized Query Filters
//!
//! From mm.md Task 5.3: AVX-512/NEON Vectorized Filters (VQE)
//!
//! ## Problem
//!
//! Current filtering is scalar. LLM context queries often filter millions of rows
//! (e.g., "events from last 7 days"). SIMD can evaluate 8-16 predicates per instruction.
//!
//! ## Solution
//!
//! Column-oriented data layout + compiled filter expressions + runtime SIMD feature detection
//!
//! ## Throughput Analysis
//!
//! ```text
//! Scalar: 1 comparison/cycle × 3GHz = 3B comparisons/sec
//! AVX-512: 8 comparisons/instruction × ~1 CPI × 3GHz = 24B/sec
//! AVX-256: 4 comparisons/instruction = 12B/sec
//! NEON: 4 comparisons/instruction = 12B/sec
//!
//! 100M rows @ 24B/sec = 4.2ms (AVX-512)
//! 100M rows @ 3B/sec = 33ms (scalar)
//!
//! Speedup: 8× (AVX-512), 4× (AVX-256/NEON)
//! ```

/// Result bitmap - bit per row indicating pass/fail
pub type FilterBitmap = Vec<u64>;

/// Filter comparison operation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterOp {
    Equal,
    NotEqual,
    LessThan,
    LessEqual,
    GreaterThan,
    GreaterEqual,
    IsNull,
    IsNotNull,
}

/// Allocate a bitmap for the given number of rows
#[inline]
pub fn allocate_bitmap(num_rows: usize) -> FilterBitmap {
    vec![0u64; (num_rows + 63) / 64]
}

/// Set a bit in the bitmap
#[inline]
pub fn set_bit(bitmap: &mut FilterBitmap, idx: usize) {
    let word_idx = idx / 64;
    let bit_idx = idx % 64;
    if word_idx < bitmap.len() {
        bitmap[word_idx] |= 1u64 << bit_idx;
    }
}

/// Check if a bit is set
#[inline]
pub fn get_bit(bitmap: &FilterBitmap, idx: usize) -> bool {
    let word_idx = idx / 64;
    let bit_idx = idx % 64;
    if word_idx < bitmap.len() {
        (bitmap[word_idx] >> bit_idx) & 1 == 1
    } else {
        false
    }
}

/// Count set bits in bitmap
pub fn popcount(bitmap: &FilterBitmap) -> usize {
    bitmap.iter().map(|w| w.count_ones() as usize).sum()
}

/// AND two bitmaps together
pub fn bitmap_and(a: &FilterBitmap, b: &FilterBitmap) -> FilterBitmap {
    a.iter().zip(b.iter()).map(|(x, y)| x & y).collect()
}

/// OR two bitmaps together
pub fn bitmap_or(a: &FilterBitmap, b: &FilterBitmap) -> FilterBitmap {
    a.iter().zip(b.iter()).map(|(x, y)| x | y).collect()
}

/// NOT a bitmap
pub fn bitmap_not(a: &FilterBitmap) -> FilterBitmap {
    a.iter().map(|x| !x).collect()
}

// =============================================================================
// Scalar Implementations (Fallback)
// =============================================================================

/// Scalar filter: i64 > threshold
pub fn filter_i64_gt_scalar(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value > threshold {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: i64 >= threshold
pub fn filter_i64_ge_scalar(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value >= threshold {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: i64 < threshold
pub fn filter_i64_lt_scalar(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value < threshold {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: i64 == value
pub fn filter_i64_eq_scalar(data: &[i64], target: i64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value == target {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: i64 between low and high (inclusive)
pub fn filter_i64_between_scalar(data: &[i64], low: i64, high: i64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value >= low && value <= high {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: f64 > threshold
pub fn filter_f64_gt_scalar(data: &[f64], threshold: f64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value > threshold {
            set_bit(result, idx);
        }
    }
}

/// Scalar filter: f64 < threshold
pub fn filter_f64_lt_scalar(data: &[f64], threshold: f64, result: &mut FilterBitmap) {
    for (idx, &value) in data.iter().enumerate() {
        if value < threshold {
            set_bit(result, idx);
        }
    }
}

// =============================================================================
// AVX2 SIMD Implementations (x86_64)
// =============================================================================

#[cfg(target_arch = "x86_64")]
mod avx2 {
    use super::*;
    use std::arch::x86_64::*;

    /// Check if AVX2 is available
    #[inline]
    pub fn is_available() -> bool {
        is_x86_feature_detected!("avx2")
    }

    /// AVX2 filter: i64 > threshold
    ///
    /// Processes 4 i64 values per iteration using 256-bit vectors.
    #[target_feature(enable = "avx2")]
    pub unsafe fn filter_i64_gt_avx2(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
        let threshold_vec = _mm256_set1_epi64x(threshold);
        let len = data.len();
        let chunks = len / 4;

        for chunk_idx in 0..chunks {
            let offset = chunk_idx * 4;
            let data_vec = _mm256_loadu_si256(data.as_ptr().add(offset) as *const __m256i);

            // Compare greater than
            let cmp = _mm256_cmpgt_epi64(data_vec, threshold_vec);

            // Extract mask
            let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp)) as u64;

            // Set bits in result
            let word_idx = offset / 64;
            let bit_offset = offset % 64;
            if word_idx < result.len() {
                result[word_idx] |= mask << bit_offset;
                // Handle overflow to next word
                if bit_offset > 60 && word_idx + 1 < result.len() {
                    result[word_idx + 1] |= mask >> (64 - bit_offset);
                }
            }
        }

        // Handle remainder with scalar
        let remainder_start = chunks * 4;
        for idx in remainder_start..len {
            if data[idx] > threshold {
                set_bit(result, idx);
            }
        }
    }

    /// AVX2 filter: i64 < threshold
    #[target_feature(enable = "avx2")]
    pub unsafe fn filter_i64_lt_avx2(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
        let threshold_vec = _mm256_set1_epi64x(threshold);
        let len = data.len();
        let chunks = len / 4;

        for chunk_idx in 0..chunks {
            let offset = chunk_idx * 4;
            let data_vec = _mm256_loadu_si256(data.as_ptr().add(offset) as *const __m256i);

            // Compare: data < threshold is equivalent to threshold > data
            let cmp = _mm256_cmpgt_epi64(threshold_vec, data_vec);
            let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp)) as u64;

            let word_idx = offset / 64;
            let bit_offset = offset % 64;
            if word_idx < result.len() {
                result[word_idx] |= mask << bit_offset;
                if bit_offset > 60 && word_idx + 1 < result.len() {
                    result[word_idx + 1] |= mask >> (64 - bit_offset);
                }
            }
        }

        let remainder_start = chunks * 4;
        for idx in remainder_start..len {
            if data[idx] < threshold {
                set_bit(result, idx);
            }
        }
    }

    /// AVX2 filter: i64 == value
    #[target_feature(enable = "avx2")]
    pub unsafe fn filter_i64_eq_avx2(data: &[i64], target: i64, result: &mut FilterBitmap) {
        let target_vec = _mm256_set1_epi64x(target);
        let len = data.len();
        let chunks = len / 4;

        for chunk_idx in 0..chunks {
            let offset = chunk_idx * 4;
            let data_vec = _mm256_loadu_si256(data.as_ptr().add(offset) as *const __m256i);

            let cmp = _mm256_cmpeq_epi64(data_vec, target_vec);
            let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp)) as u64;

            let word_idx = offset / 64;
            let bit_offset = offset % 64;
            if word_idx < result.len() {
                result[word_idx] |= mask << bit_offset;
                if bit_offset > 60 && word_idx + 1 < result.len() {
                    result[word_idx + 1] |= mask >> (64 - bit_offset);
                }
            }
        }

        let remainder_start = chunks * 4;
        for idx in remainder_start..len {
            if data[idx] == target {
                set_bit(result, idx);
            }
        }
    }

    /// AVX2 filter: i64 between low and high
    #[target_feature(enable = "avx2")]
    pub unsafe fn filter_i64_between_avx2(
        data: &[i64],
        low: i64,
        high: i64,
        result: &mut FilterBitmap,
    ) {
        let low_vec = _mm256_set1_epi64x(low - 1); // For >= comparison
        let high_vec = _mm256_set1_epi64x(high);
        let len = data.len();
        let chunks = len / 4;

        for chunk_idx in 0..chunks {
            let offset = chunk_idx * 4;
            let data_vec = _mm256_loadu_si256(data.as_ptr().add(offset) as *const __m256i);

            // data > (low - 1) AND data <= high
            let cmp_low = _mm256_cmpgt_epi64(data_vec, low_vec);
            let cmp_high = _mm256_cmpgt_epi64(high_vec, data_vec);
            let cmp_high_eq = _mm256_cmpeq_epi64(data_vec, high_vec);
            let cmp_high_final = _mm256_or_si256(cmp_high, cmp_high_eq);
            let cmp = _mm256_and_si256(cmp_low, cmp_high_final);

            let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp)) as u64;

            let word_idx = offset / 64;
            let bit_offset = offset % 64;
            if word_idx < result.len() {
                result[word_idx] |= mask << bit_offset;
                if bit_offset > 60 && word_idx + 1 < result.len() {
                    result[word_idx + 1] |= mask >> (64 - bit_offset);
                }
            }
        }

        let remainder_start = chunks * 4;
        for idx in remainder_start..len {
            let v = data[idx];
            if v >= low && v <= high {
                set_bit(result, idx);
            }
        }
    }

    /// AVX2 filter: f64 > threshold
    #[target_feature(enable = "avx2")]
    pub unsafe fn filter_f64_gt_avx2(data: &[f64], threshold: f64, result: &mut FilterBitmap) {
        let threshold_vec = _mm256_set1_pd(threshold);
        let len = data.len();
        let chunks = len / 4;

        for chunk_idx in 0..chunks {
            let offset = chunk_idx * 4;
            let data_vec = _mm256_loadu_pd(data.as_ptr().add(offset));

            let cmp = _mm256_cmp_pd(data_vec, threshold_vec, _CMP_GT_OQ);
            let mask = _mm256_movemask_pd(cmp) as u64;

            let word_idx = offset / 64;
            let bit_offset = offset % 64;
            if word_idx < result.len() {
                result[word_idx] |= mask << bit_offset;
                if bit_offset > 60 && word_idx + 1 < result.len() {
                    result[word_idx + 1] |= mask >> (64 - bit_offset);
                }
            }
        }

        let remainder_start = chunks * 4;
        for idx in remainder_start..len {
            if data[idx] > threshold {
                set_bit(result, idx);
            }
        }
    }
}

// =============================================================================
// NEON SIMD Implementations (aarch64)
// =============================================================================

#[cfg(target_arch = "aarch64")]
mod neon {
    use super::*;
    use std::arch::aarch64::*;

    /// NEON is always available on aarch64
    #[inline]
    #[allow(dead_code)]
    pub fn is_available() -> bool {
        true
    }

    /// NEON filter: i64 > threshold
    ///
    /// Processes 2 i64 values per iteration using 128-bit vectors.
    #[target_feature(enable = "neon")]
    pub unsafe fn filter_i64_gt_neon(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
        unsafe {
            let threshold_vec = vdupq_n_s64(threshold);
            let len = data.len();
            let chunks = len / 2;

            for chunk_idx in 0..chunks {
                let offset = chunk_idx * 2;
                let data_vec = vld1q_s64(data.as_ptr().add(offset));

                // Compare greater than (returns uint64x2_t)
                let cmp = vcgtq_s64(data_vec, threshold_vec);

                // Extract mask (2 bits) - cmp is already uint64x2_t
                let mask_low = vgetq_lane_u64(cmp, 0);
                let mask_high = vgetq_lane_u64(cmp, 1);
                let mask = ((mask_low != 0) as u64) | (((mask_high != 0) as u64) << 1);

                let word_idx = offset / 64;
                let bit_offset = offset % 64;
                if word_idx < result.len() {
                    result[word_idx] |= mask << bit_offset;
                }
            }

            // Handle remainder
            let remainder_start = chunks * 2;
            for idx in remainder_start..len {
                if data[idx] > threshold {
                    set_bit(result, idx);
                }
            }
        }
    }

    /// NEON filter: i64 < threshold
    #[target_feature(enable = "neon")]
    pub unsafe fn filter_i64_lt_neon(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
        unsafe {
            let threshold_vec = vdupq_n_s64(threshold);
            let len = data.len();
            let chunks = len / 2;

            for chunk_idx in 0..chunks {
                let offset = chunk_idx * 2;
                let data_vec = vld1q_s64(data.as_ptr().add(offset));

                let cmp = vcltq_s64(data_vec, threshold_vec);

                // cmp is already uint64x2_t
                let mask_low = vgetq_lane_u64(cmp, 0);
                let mask_high = vgetq_lane_u64(cmp, 1);
                let mask = ((mask_low != 0) as u64) | (((mask_high != 0) as u64) << 1);

                let word_idx = offset / 64;
                let bit_offset = offset % 64;
                if word_idx < result.len() {
                    result[word_idx] |= mask << bit_offset;
                }
            }

            let remainder_start = chunks * 2;
            for idx in remainder_start..len {
                if data[idx] < threshold {
                    set_bit(result, idx);
                }
            }
        }
    }

    /// NEON filter: i64 == value
    #[target_feature(enable = "neon")]
    pub unsafe fn filter_i64_eq_neon(data: &[i64], target: i64, result: &mut FilterBitmap) {
        unsafe {
            let target_vec = vdupq_n_s64(target);
            let len = data.len();
            let chunks = len / 2;

            for chunk_idx in 0..chunks {
                let offset = chunk_idx * 2;
                let data_vec = vld1q_s64(data.as_ptr().add(offset));

                let cmp = vceqq_s64(data_vec, target_vec);

                // cmp is already uint64x2_t
                let mask_low = vgetq_lane_u64(cmp, 0);
                let mask_high = vgetq_lane_u64(cmp, 1);
                let mask = ((mask_low != 0) as u64) | (((mask_high != 0) as u64) << 1);

                let word_idx = offset / 64;
                let bit_offset = offset % 64;
                if word_idx < result.len() {
                    result[word_idx] |= mask << bit_offset;
                }
            }

            let remainder_start = chunks * 2;
            for idx in remainder_start..len {
                if data[idx] == target {
                    set_bit(result, idx);
                }
            }
        }
    }

    /// NEON filter: f64 > threshold
    #[target_feature(enable = "neon")]
    pub unsafe fn filter_f64_gt_neon(data: &[f64], threshold: f64, result: &mut FilterBitmap) {
        unsafe {
            let threshold_vec = vdupq_n_f64(threshold);
            let len = data.len();
            let chunks = len / 2;

            for chunk_idx in 0..chunks {
                let offset = chunk_idx * 2;
                let data_vec = vld1q_f64(data.as_ptr().add(offset));

                let cmp = vcgtq_f64(data_vec, threshold_vec);

                let mask_low = vgetq_lane_u64(cmp, 0);
                let mask_high = vgetq_lane_u64(cmp, 1);
                let mask = ((mask_low != 0) as u64) | (((mask_high != 0) as u64) << 1);

                let word_idx = offset / 64;
                let bit_offset = offset % 64;
                if word_idx < result.len() {
                    result[word_idx] |= mask << bit_offset;
                }
            }

            let remainder_start = chunks * 2;
            for idx in remainder_start..len {
                if data[idx] > threshold {
                    set_bit(result, idx);
                }
            }
        }
    }
}

// =============================================================================
// Public API with Automatic Dispatch
// =============================================================================

/// Filter i64 column: value > threshold
pub fn filter_i64_gt(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
    #[cfg(target_arch = "x86_64")]
    {
        if avx2::is_available() {
            unsafe {
                avx2::filter_i64_gt_avx2(data, threshold, result);
            }
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        unsafe {
            neon::filter_i64_gt_neon(data, threshold, result);
        }
        return;
    }

    #[allow(unreachable_code)]
    filter_i64_gt_scalar(data, threshold, result);
}

/// Filter i64 column: value < threshold
pub fn filter_i64_lt(data: &[i64], threshold: i64, result: &mut FilterBitmap) {
    #[cfg(target_arch = "x86_64")]
    {
        if avx2::is_available() {
            unsafe {
                avx2::filter_i64_lt_avx2(data, threshold, result);
            }
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        unsafe {
            neon::filter_i64_lt_neon(data, threshold, result);
        }
        return;
    }

    #[allow(unreachable_code)]
    filter_i64_lt_scalar(data, threshold, result);
}

/// Filter i64 column: value == target
pub fn filter_i64_eq(data: &[i64], target: i64, result: &mut FilterBitmap) {
    #[cfg(target_arch = "x86_64")]
    {
        if avx2::is_available() {
            unsafe {
                avx2::filter_i64_eq_avx2(data, target, result);
            }
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        unsafe {
            neon::filter_i64_eq_neon(data, target, result);
        }
        return;
    }

    #[allow(unreachable_code)]
    filter_i64_eq_scalar(data, target, result);
}

/// Filter i64 column: low <= value <= high
pub fn filter_i64_between(data: &[i64], low: i64, high: i64, result: &mut FilterBitmap) {
    #[cfg(target_arch = "x86_64")]
    {
        if avx2::is_available() {
            unsafe {
                avx2::filter_i64_between_avx2(data, low, high, result);
            }
            return;
        }
    }

    // Fallback to scalar
    filter_i64_between_scalar(data, low, high, result);
}

/// Filter f64 column: value > threshold
pub fn filter_f64_gt(data: &[f64], threshold: f64, result: &mut FilterBitmap) {
    #[cfg(target_arch = "x86_64")]
    {
        if avx2::is_available() {
            unsafe {
                avx2::filter_f64_gt_avx2(data, threshold, result);
            }
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        unsafe {
            neon::filter_f64_gt_neon(data, threshold, result);
        }
        return;
    }

    #[allow(unreachable_code)]
    filter_f64_gt_scalar(data, threshold, result);
}

/// Get information about SIMD support
pub fn simd_info() -> SimdInfo {
    SimdInfo {
        #[cfg(target_arch = "x86_64")]
        has_avx2: is_x86_feature_detected!("avx2"),
        #[cfg(target_arch = "x86_64")]
        has_avx512f: is_x86_feature_detected!("avx512f"),
        #[cfg(not(target_arch = "x86_64"))]
        has_avx2: false,
        #[cfg(not(target_arch = "x86_64"))]
        has_avx512f: false,
        #[cfg(target_arch = "aarch64")]
        has_neon: true,
        #[cfg(not(target_arch = "aarch64"))]
        has_neon: false,
    }
}

/// SIMD capability information
#[derive(Debug, Clone)]
pub struct SimdInfo {
    pub has_avx2: bool,
    pub has_avx512f: bool,
    pub has_neon: bool,
}

impl SimdInfo {
    /// Get expected speedup factor for i64 filters
    pub fn expected_speedup_i64(&self) -> f64 {
        if self.has_avx512f {
            8.0
        } else if self.has_avx2 {
            4.0
        } else if self.has_neon {
            2.0
        } else {
            1.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_filter_i64_gt() {
        let data: Vec<i64> = (0..100).collect();
        let mut result = allocate_bitmap(data.len());

        filter_i64_gt(&data, 50, &mut result);

        // Values 51-99 should pass (49 values)
        assert_eq!(popcount(&result), 49);

        for i in 0..100 {
            assert_eq!(get_bit(&result, i), i > 50, "Failed at index {}", i);
        }
    }

    #[test]
    fn test_filter_i64_lt() {
        let data: Vec<i64> = (0..100).collect();
        let mut result = allocate_bitmap(data.len());

        filter_i64_lt(&data, 50, &mut result);

        // Values 0-49 should pass (50 values)
        assert_eq!(popcount(&result), 50);

        for i in 0..100 {
            assert_eq!(get_bit(&result, i), i < 50, "Failed at index {}", i);
        }
    }

    #[test]
    fn test_filter_i64_eq() {
        let data: Vec<i64> = (0..100).collect();
        let mut result = allocate_bitmap(data.len());

        filter_i64_eq(&data, 42, &mut result);

        assert_eq!(popcount(&result), 1);
        assert!(get_bit(&result, 42));
    }

    #[test]
    fn test_filter_i64_between() {
        let data: Vec<i64> = (0..100).collect();
        let mut result = allocate_bitmap(data.len());

        filter_i64_between(&data, 25, 75, &mut result);

        // Values 25-75 inclusive (51 values)
        assert_eq!(popcount(&result), 51);

        for i in 0..100 {
            assert_eq!(
                get_bit(&result, i),
                i >= 25 && i <= 75,
                "Failed at index {}",
                i
            );
        }
    }

    #[test]
    fn test_filter_f64_gt() {
        let data: Vec<f64> = (0..100).map(|x| x as f64).collect();
        let mut result = allocate_bitmap(data.len());

        filter_f64_gt(&data, 50.0, &mut result);

        assert_eq!(popcount(&result), 49);
    }

    #[test]
    fn test_bitmap_operations() {
        let mut a = allocate_bitmap(64);
        let mut b = allocate_bitmap(64);

        for i in 0..32 {
            set_bit(&mut a, i);
        }
        for i in 16..48 {
            set_bit(&mut b, i);
        }

        let and_result = bitmap_and(&a, &b);
        assert_eq!(popcount(&and_result), 16); // 16-31

        let or_result = bitmap_or(&a, &b);
        assert_eq!(popcount(&or_result), 48); // 0-47
    }

    #[test]
    fn test_simd_info() {
        let info = simd_info();
        println!("SIMD capabilities: {:?}", info);
        println!("Expected speedup: {}x", info.expected_speedup_i64());
    }

    #[test]
    fn test_large_dataset() {
        // Test with 1M rows
        let data: Vec<i64> = (0..1_000_000).collect();
        let mut result = allocate_bitmap(data.len());

        let start = std::time::Instant::now();
        filter_i64_gt(&data, 500_000, &mut result);
        let elapsed = start.elapsed();

        assert_eq!(popcount(&result), 499_999);
        println!("Filtered 1M rows in {:?}", elapsed);
    }
}