sochdb-vector 2.0.6

Streaming elimination vector search engine for SochDB - CPU-first ANN with RDF + BPS
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
//! MVCC Visibility Check Kernel
//!
//! This module provides SIMD-accelerated visibility checking for MVCC
//! (Multi-Version Concurrency Control) operations.
//!
//! # Algorithm
//!
//! A row is visible if:
//! ```text
//! visible[i] = (commit_ts[i] != 0) && (commit_ts[i] < snapshot_ts)
//! ```
//!
//! With transaction ID awareness:
//! ```text
//! visible[i] = ((commit_ts[i] != 0) && (commit_ts[i] < snapshot_ts)) || (txn_id[i] == current_txn)
//! ```
//!
//! # Boolean Logic
//!
//! ```text
//! visible = (commit ≠ 0) ∧ (commit < snapshot)
//!         = ¬(commit = 0) ∧ (commit < snapshot)
//! ```
//!
//! # SIMD Strategy
//!
//! - **AVX2**: Process 4 u64 timestamps per 256-bit register
//! - **NEON**: Process 2 u64 timestamps per 128-bit register

use super::dispatch::cpu_features;

/// Check visibility for a batch of rows based on commit timestamps.
///
/// # Arguments
/// * `commit_timestamps` - Array of commit timestamps (0 = uncommitted)
/// * `snapshot_ts` - The snapshot timestamp for visibility check
/// * `visible_mask` - Output: 1 if visible, 0 if not visible
///
/// # Panics
/// Panics if `visible_mask.len() < commit_timestamps.len()`
#[inline]
pub fn visibility_check(commit_timestamps: &[u64], snapshot_ts: u64, visible_mask: &mut [u8]) {
    let n_rows = commit_timestamps.len();
    assert!(
        visible_mask.len() >= n_rows,
        "visible_mask buffer too small"
    );

    if n_rows == 0 {
        return;
    }

    let features = cpu_features();

    #[cfg(target_arch = "x86_64")]
    {
        if features.has_avx2 {
            unsafe { visibility_check_avx2(commit_timestamps, snapshot_ts, visible_mask) };
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        if features.has_neon {
            unsafe { visibility_check_neon(commit_timestamps, snapshot_ts, visible_mask) };
            return;
        }
    }

    visibility_check_scalar(commit_timestamps, snapshot_ts, visible_mask);
}

/// Check visibility with transaction ID awareness (for self-visibility).
///
/// A row is visible if:
/// - `(commit_ts != 0 && commit_ts < snapshot_ts)`, OR
/// - `txn_id == current_txn_id` (self-visibility)
///
/// # Arguments
/// * `commit_timestamps` - Array of commit timestamps (0 = uncommitted)
/// * `txn_ids` - Array of transaction IDs that wrote each row
/// * `snapshot_ts` - The snapshot timestamp for visibility check
/// * `current_txn_id` - The current transaction's ID
/// * `visible_mask` - Output: 1 if visible, 0 if not visible
#[inline]
pub fn visibility_check_with_txn(
    commit_timestamps: &[u64],
    txn_ids: &[u64],
    snapshot_ts: u64,
    current_txn_id: u64,
    visible_mask: &mut [u8],
) {
    let n_rows = commit_timestamps.len();
    assert_eq!(txn_ids.len(), n_rows, "txn_ids length mismatch");
    assert!(
        visible_mask.len() >= n_rows,
        "visible_mask buffer too small"
    );

    if n_rows == 0 {
        return;
    }

    let features = cpu_features();

    #[cfg(target_arch = "x86_64")]
    {
        if features.has_avx2 {
            unsafe {
                visibility_check_with_txn_avx2(
                    commit_timestamps,
                    txn_ids,
                    snapshot_ts,
                    current_txn_id,
                    visible_mask,
                )
            };
            return;
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        if features.has_neon {
            unsafe {
                visibility_check_with_txn_neon(
                    commit_timestamps,
                    txn_ids,
                    snapshot_ts,
                    current_txn_id,
                    visible_mask,
                )
            };
            return;
        }
    }

    visibility_check_with_txn_scalar(
        commit_timestamps,
        txn_ids,
        snapshot_ts,
        current_txn_id,
        visible_mask,
    );
}

// ============================================================================
// x86_64 AVX2 Implementation
// ============================================================================

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn visibility_check_avx2(
    commit_timestamps: &[u64],
    snapshot_ts: u64,
    visible_mask: &mut [u8],
) {
    use std::arch::x86_64::*;

    unsafe {
        let n_rows = commit_timestamps.len();
        let snapshot_vec = _mm256_set1_epi64x(snapshot_ts as i64);
        let zero_vec = _mm256_setzero_si256();

        let mut i = 0;

        // Process 4 rows at a time (256 bits / 64 bits = 4)
        while i + 4 <= n_rows {
            // Load 4 commit timestamps
            let commits = _mm256_loadu_si256(commit_timestamps.as_ptr().add(i) as *const __m256i);

            // Check: commit_ts != 0
            let eq_zero = _mm256_cmpeq_epi64(commits, zero_vec);
            // Invert: not_zero = ~eq_zero
            let not_zero = _mm256_xor_si256(eq_zero, _mm256_set1_epi64x(-1));

            // Check: commit_ts < snapshot_ts (using snapshot > commit)
            let less_than = _mm256_cmpgt_epi64(snapshot_vec, commits);

            // Combine: not_zero AND less_than
            let visible = _mm256_and_si256(not_zero, less_than);

            // Extract to mask bytes: take bit 63 of each 64-bit lane
            let mask_bits = _mm256_movemask_pd(_mm256_castsi256_pd(visible));

            visible_mask[i] = if mask_bits & 1 != 0 { 1 } else { 0 };
            visible_mask[i + 1] = if mask_bits & 2 != 0 { 1 } else { 0 };
            visible_mask[i + 2] = if mask_bits & 4 != 0 { 1 } else { 0 };
            visible_mask[i + 3] = if mask_bits & 8 != 0 { 1 } else { 0 };

            i += 4;
        }

        // Scalar tail
        while i < n_rows {
            let commit = commit_timestamps[i];
            visible_mask[i] = if commit != 0 && commit < snapshot_ts {
                1
            } else {
                0
            };
            i += 1;
        }
    }
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn visibility_check_with_txn_avx2(
    commit_timestamps: &[u64],
    txn_ids: &[u64],
    snapshot_ts: u64,
    current_txn_id: u64,
    visible_mask: &mut [u8],
) {
    use std::arch::x86_64::*;

    unsafe {
        let n_rows = commit_timestamps.len();
        let snapshot_vec = _mm256_set1_epi64x(snapshot_ts as i64);
        let zero_vec = _mm256_setzero_si256();
        let current_txn_vec = _mm256_set1_epi64x(current_txn_id as i64);

        let mut i = 0;

        while i + 4 <= n_rows {
            // Load 4 commit timestamps and txn IDs
            let commits = _mm256_loadu_si256(commit_timestamps.as_ptr().add(i) as *const __m256i);
            let txns = _mm256_loadu_si256(txn_ids.as_ptr().add(i) as *const __m256i);

            // Check: txn_id == current_txn_id (own writes always visible)
            let own_write = _mm256_cmpeq_epi64(txns, current_txn_vec);

            // Check: commit_ts != 0
            let eq_zero = _mm256_cmpeq_epi64(commits, zero_vec);
            let not_zero = _mm256_xor_si256(eq_zero, _mm256_set1_epi64x(-1));

            // Check: commit_ts < snapshot_ts
            let less_than = _mm256_cmpgt_epi64(snapshot_vec, commits);

            // Combine: (not_zero AND less_than) OR own_write
            let committed_visible = _mm256_and_si256(not_zero, less_than);
            let visible = _mm256_or_si256(committed_visible, own_write);

            // Extract to mask bytes
            let mask_bits = _mm256_movemask_pd(_mm256_castsi256_pd(visible));

            visible_mask[i] = if mask_bits & 1 != 0 { 1 } else { 0 };
            visible_mask[i + 1] = if mask_bits & 2 != 0 { 1 } else { 0 };
            visible_mask[i + 2] = if mask_bits & 4 != 0 { 1 } else { 0 };
            visible_mask[i + 3] = if mask_bits & 8 != 0 { 1 } else { 0 };

            i += 4;
        }

        // Scalar tail
        while i < n_rows {
            let commit = commit_timestamps[i];
            let txn = txn_ids[i];
            let visible = (commit != 0 && commit < snapshot_ts) || txn == current_txn_id;
            visible_mask[i] = if visible { 1 } else { 0 };
            i += 1;
        }
    }
}

// ============================================================================
// aarch64 NEON Implementation
// ============================================================================

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn visibility_check_neon(
    commit_timestamps: &[u64],
    snapshot_ts: u64,
    visible_mask: &mut [u8],
) {
    use std::arch::aarch64::*;

    unsafe {
        let n_rows = commit_timestamps.len();
        let snapshot_vec = vdupq_n_u64(snapshot_ts);
        let zero_vec = vdupq_n_u64(0);

        let mut i = 0;

        // Process 2 rows at a time (128 bits / 64 bits = 2)
        while i + 2 <= n_rows {
            // Load 2 commit timestamps
            let commits = vld1q_u64(commit_timestamps.as_ptr().add(i));

            // Check: commit_ts != 0
            let eq_zero = vceqq_u64(commits, zero_vec);
            // not_zero via bitwise NOT on the bytes
            let not_zero = vmvnq_u8(vreinterpretq_u8_u64(eq_zero));

            // Check: commit_ts < snapshot_ts
            // NEON doesn't have vcltq_u64, use subtraction trick
            // If commit < snapshot, then (commit - snapshot) will have high bit set (underflow)
            let diff = vsubq_u64(commits, snapshot_vec);
            let less_than = vshrq_n_u64(diff, 63); // Get sign bit (1 if underflowed)

            // Combine: not_zero AND (less_than == 1)
            let visible = vandq_u64(
                vreinterpretq_u64_u8(not_zero),
                vceqq_u64(less_than, vdupq_n_u64(1)),
            );

            // Extract to mask bytes
            visible_mask[i] = if vgetq_lane_u64(visible, 0) != 0 {
                1
            } else {
                0
            };
            visible_mask[i + 1] = if vgetq_lane_u64(visible, 1) != 0 {
                1
            } else {
                0
            };

            i += 2;
        }

        // Scalar tail
        while i < n_rows {
            let commit = commit_timestamps[i];
            visible_mask[i] = if commit != 0 && commit < snapshot_ts {
                1
            } else {
                0
            };
            i += 1;
        }
    }
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn visibility_check_with_txn_neon(
    commit_timestamps: &[u64],
    txn_ids: &[u64],
    snapshot_ts: u64,
    current_txn_id: u64,
    visible_mask: &mut [u8],
) {
    use std::arch::aarch64::*;

    unsafe {
        let n_rows = commit_timestamps.len();
        let snapshot_vec = vdupq_n_u64(snapshot_ts);
        let zero_vec = vdupq_n_u64(0);
        let current_txn_vec = vdupq_n_u64(current_txn_id);

        let mut i = 0;

        while i + 2 <= n_rows {
            let commits = vld1q_u64(commit_timestamps.as_ptr().add(i));
            let txns = vld1q_u64(txn_ids.as_ptr().add(i));

            // Check: txn_id == current_txn_id
            let own_write = vceqq_u64(txns, current_txn_vec);

            // Check: commit_ts != 0
            let eq_zero = vceqq_u64(commits, zero_vec);
            let not_zero = vmvnq_u8(vreinterpretq_u8_u64(eq_zero));

            // Check: commit_ts < snapshot_ts
            let diff = vsubq_u64(commits, snapshot_vec);
            let less_than = vshrq_n_u64(diff, 63);

            // Combine
            let committed_visible = vandq_u64(
                vreinterpretq_u64_u8(not_zero),
                vceqq_u64(less_than, vdupq_n_u64(1)),
            );
            let visible = vorrq_u64(committed_visible, own_write);

            visible_mask[i] = if vgetq_lane_u64(visible, 0) != 0 {
                1
            } else {
                0
            };
            visible_mask[i + 1] = if vgetq_lane_u64(visible, 1) != 0 {
                1
            } else {
                0
            };

            i += 2;
        }

        // Scalar tail
        while i < n_rows {
            let commit = commit_timestamps[i];
            let txn = txn_ids[i];
            let visible = (commit != 0 && commit < snapshot_ts) || txn == current_txn_id;
            visible_mask[i] = if visible { 1 } else { 0 };
            i += 1;
        }
    }
}

// ============================================================================
// Scalar Fallback
// ============================================================================

/// Scalar fallback for visibility check
#[inline]
fn visibility_check_scalar(commit_timestamps: &[u64], snapshot_ts: u64, visible_mask: &mut [u8]) {
    for (i, &commit) in commit_timestamps.iter().enumerate() {
        visible_mask[i] = if commit != 0 && commit < snapshot_ts {
            1
        } else {
            0
        };
    }
}

/// Scalar fallback for visibility check with txn
#[inline]
fn visibility_check_with_txn_scalar(
    commit_timestamps: &[u64],
    txn_ids: &[u64],
    snapshot_ts: u64,
    current_txn_id: u64,
    visible_mask: &mut [u8],
) {
    for i in 0..commit_timestamps.len() {
        let commit = commit_timestamps[i];
        let txn = txn_ids[i];
        let visible = (commit != 0 && commit < snapshot_ts) || txn == current_txn_id;
        visible_mask[i] = if visible { 1 } else { 0 };
    }
}

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

    #[test]
    fn test_visibility_basic() {
        let commits = vec![0, 100, 200, 300, 400];
        let snapshot = 250;
        let mut mask = vec![0u8; 5];

        visibility_check(&commits, snapshot, &mut mask);

        // Expected:
        // 0: commit=0 (uncommitted) -> not visible
        // 100: 100 < 250 -> visible
        // 200: 200 < 250 -> visible
        // 300: 300 >= 250 -> not visible
        // 400: 400 >= 250 -> not visible
        assert_eq!(mask, vec![0, 1, 1, 0, 0]);
    }

    #[test]
    fn test_visibility_with_txn() {
        let commits = vec![0, 100, 200, 300, 0];
        let txn_ids = vec![10, 20, 30, 40, 50];
        let snapshot = 250;
        let current_txn = 50;
        let mut mask = vec![0u8; 5];

        visibility_check_with_txn(&commits, &txn_ids, snapshot, current_txn, &mut mask);

        // Expected:
        // 0: commit=0, txn=10 != 50 -> not visible
        // 100: commit < snapshot -> visible
        // 200: commit < snapshot -> visible
        // 300: commit >= snapshot, txn=40 != 50 -> not visible
        // 0: commit=0, txn=50 == 50 -> visible (self-visibility)
        assert_eq!(mask, vec![0, 1, 1, 0, 1]);
    }

    #[test]
    fn test_visibility_alignment() {
        // Test with sizes that don't align to SIMD width
        for n_rows in [1, 2, 3, 4, 5, 7, 9, 15, 17] {
            let commits: Vec<u64> = (0..n_rows).map(|i| (i * 100) as u64).collect();
            let snapshot = 500;
            let mut mask = vec![0u8; n_rows];

            visibility_check(&commits, snapshot, &mut mask);

            // Verify against scalar
            let mut expected = vec![0u8; n_rows];
            visibility_check_scalar(&commits, snapshot, &mut expected);

            assert_eq!(mask, expected, "Mismatch for n_rows={}", n_rows);
        }
    }

    #[test]
    fn test_visibility_edge_cases() {
        // All zeros
        let commits = vec![0u64; 10];
        let mut mask = vec![1u8; 10];
        visibility_check(&commits, 100, &mut mask);
        assert!(mask.iter().all(|&m| m == 0));

        // All equal to snapshot
        let commits = vec![100u64; 10];
        let mut mask = vec![1u8; 10];
        visibility_check(&commits, 100, &mut mask);
        assert!(mask.iter().all(|&m| m == 0));

        // All less than snapshot
        let commits = vec![99u64; 10];
        let mut mask = vec![0u8; 10];
        visibility_check(&commits, 100, &mut mask);
        assert!(mask.iter().all(|&m| m == 1));
    }
}