vibesql-executor 0.2.0

Query execution engine for vibesql SQL database
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
//! Auto-vectorized columnar aggregation operations
//!
//! This module provides high-performance aggregate computations for Int64 and Float64
//! columns using auto-vectorized operations that achieve equivalent performance to
//! explicit SIMD (e.g., the `wide` crate).
//!
//! See `simd_ops.rs` for documentation on why the 4-accumulator pattern is used.

use vibesql_types::SqlValue;

use super::{aggregate::AggregateOp, scan::ColumnarScan, simd_ops};
use crate::{errors::ExecutorError, select::vectorized::DEFAULT_BATCH_SIZE};

// Re-export optimized SIMD operations from simd_ops module
// DO NOT replace these with .iter().sum() - see simd_ops.rs for why
#[inline]
fn simd_sum_i64(values: &[i64]) -> i64 {
    simd_ops::sum_i64(values)
}

#[inline]
fn simd_min_i64(values: &[i64]) -> Option<i64> {
    simd_ops::min_i64(values)
}

#[inline]
fn simd_max_i64(values: &[i64]) -> Option<i64> {
    simd_ops::max_i64(values)
}

#[inline]
fn simd_sum_f64(values: &[f64]) -> f64 {
    simd_ops::sum_f64(values)
}

#[inline]
fn simd_min_f64(values: &[f64]) -> Option<f64> {
    simd_ops::min_f64(values)
}

#[inline]
fn simd_max_f64(values: &[f64]) -> Option<f64> {
    simd_ops::max_f64(values)
}

/// Compute aggregate for Int64 columns using streaming batches
///
/// Processes values in fixed-size batches to avoid allocating entire column in memory.
///
/// # Arguments
///
/// * `scan` - Columnar scan over the data
/// * `column_idx` - Index of the column to aggregate
/// * `op` - Aggregate operation (SUM, AVG, MIN, MAX, COUNT)
/// * `filter_bitmap` - Optional bitmap of which rows to include
///
/// # Returns
///
/// The aggregated SqlValue or an error if the column contains non-i64 values
pub fn simd_aggregate_i64(
    scan: &ColumnarScan,
    column_idx: usize,
    op: AggregateOp,
    filter_bitmap: Option<&[bool]>,
) -> Result<SqlValue, ExecutorError> {
    // DEFAULT_BATCH_SIZE (1024) provides good SIMD throughput while fitting in cache
    let mut batch = Vec::with_capacity(DEFAULT_BATCH_SIZE);
    let mut original_type: Option<SqlValue> = None;
    let mut count = 0i64;

    // Accumulators for different operations
    let mut sum = 0i64;
    let mut min = i64::MAX;
    let mut max = i64::MIN;

    for (row_idx, value_opt) in scan.column(column_idx).enumerate() {
        // Check filter bitmap
        if let Some(bitmap) = filter_bitmap {
            if !bitmap.get(row_idx).copied().unwrap_or(false) {
                continue;
            }
        }

        // Extract i64 value, skip NULLs
        if let Some(value) = value_opt {
            let i64_value = match value {
                SqlValue::Integer(v) => {
                    if original_type.is_none() {
                        original_type = Some(SqlValue::Integer(0));
                    }
                    *v
                }
                SqlValue::Bigint(v) => {
                    if original_type.is_none() {
                        original_type = Some(SqlValue::Bigint(0));
                    }
                    *v
                }
                SqlValue::Smallint(v) => {
                    if original_type.is_none() {
                        original_type = Some(SqlValue::Smallint(0));
                    }
                    *v as i64
                }
                SqlValue::Null => continue,
                _ => {
                    return Err(ExecutorError::UnsupportedExpression(format!(
                        "Cannot compute SIMD aggregate on non-integer value: {:?}",
                        value
                    )))
                }
            };

            batch.push(i64_value);
            count += 1;

            // Process batch when full
            if batch.len() >= DEFAULT_BATCH_SIZE {
                match op {
                    AggregateOp::Sum | AggregateOp::Avg => {
                        sum += simd_sum_i64(&batch);
                    }
                    AggregateOp::Min => {
                        if let Some(batch_min) = simd_min_i64(&batch) {
                            min = min.min(batch_min);
                        }
                    }
                    AggregateOp::Max => {
                        if let Some(batch_max) = simd_max_i64(&batch) {
                            max = max.max(batch_max);
                        }
                    }
                    AggregateOp::Count => {} // Just count, no SIMD needed
                }
                batch.clear();
            }
        }
    }

    // Process final partial batch
    if !batch.is_empty() {
        match op {
            AggregateOp::Sum | AggregateOp::Avg => {
                sum += simd_sum_i64(&batch);
            }
            AggregateOp::Min => {
                if let Some(batch_min) = simd_min_i64(&batch) {
                    min = min.min(batch_min);
                }
            }
            AggregateOp::Max => {
                if let Some(batch_max) = simd_max_i64(&batch) {
                    max = max.max(batch_max);
                }
            }
            AggregateOp::Count => {}
        }
    }

    // Handle empty result set
    if count == 0 {
        return Ok(match op {
            AggregateOp::Count => SqlValue::Integer(0),
            _ => SqlValue::Null,
        });
    }

    // Return aggregated result
    match op {
        AggregateOp::Sum => {
            // SQLite's SUM() preserves integer type for integer inputs
            Ok(SqlValue::Integer(sum))
        }
        AggregateOp::Avg => Ok(SqlValue::Double(sum as f64 / count as f64)),
        AggregateOp::Min => Ok(match original_type.unwrap_or(SqlValue::Bigint(0)) {
            SqlValue::Integer(_) => SqlValue::Integer(min),
            SqlValue::Smallint(_) => SqlValue::Smallint(min as i16),
            _ => SqlValue::Bigint(min),
        }),
        AggregateOp::Max => Ok(match original_type.unwrap_or(SqlValue::Bigint(0)) {
            SqlValue::Integer(_) => SqlValue::Integer(max),
            SqlValue::Smallint(_) => SqlValue::Smallint(max as i16),
            _ => SqlValue::Bigint(max),
        }),
        AggregateOp::Count => Ok(SqlValue::Integer(count)),
    }
}

/// Compute SIMD aggregate for Float64 columns using streaming batches
///
/// Processes values in fixed-size batches to avoid allocating entire column in memory.
///
/// # Arguments
///
/// * `scan` - Columnar scan over the data
/// * `column_idx` - Index of the column to aggregate
/// * `op` - Aggregate operation (SUM, AVG, MIN, MAX, COUNT)
/// * `filter_bitmap` - Optional bitmap of which rows to include
///
/// # Returns
///
/// The aggregated SqlValue or an error if the column contains non-f64 values
pub fn simd_aggregate_f64(
    scan: &ColumnarScan,
    column_idx: usize,
    op: AggregateOp,
    filter_bitmap: Option<&[bool]>,
) -> Result<SqlValue, ExecutorError> {
    // DEFAULT_BATCH_SIZE (1024) provides good SIMD throughput while fitting in cache
    let mut batch = Vec::with_capacity(DEFAULT_BATCH_SIZE);
    let mut count = 0i64;

    // Accumulators for different operations
    let mut sum = 0.0f64;
    let mut min = f64::INFINITY;
    let mut max = f64::NEG_INFINITY;

    for (row_idx, value_opt) in scan.column(column_idx).enumerate() {
        // Check filter bitmap
        if let Some(bitmap) = filter_bitmap {
            if !bitmap.get(row_idx).copied().unwrap_or(false) {
                continue;
            }
        }

        // Extract f64 value, skip NULLs
        if let Some(value) = value_opt {
            let f64_value = match value {
                SqlValue::Double(v) => *v,
                SqlValue::Float(v) => *v as f64,
                SqlValue::Numeric(v) => *v,
                SqlValue::Integer(v) => *v as f64,
                SqlValue::Bigint(v) => *v as f64,
                SqlValue::Smallint(v) => *v as f64,
                SqlValue::Null => continue,
                _ => {
                    return Err(ExecutorError::UnsupportedExpression(format!(
                        "Cannot compute SIMD aggregate on non-numeric value: {:?}",
                        value
                    )))
                }
            };

            batch.push(f64_value);
            count += 1;

            // Process batch when full
            if batch.len() >= DEFAULT_BATCH_SIZE {
                match op {
                    AggregateOp::Sum | AggregateOp::Avg => {
                        sum += simd_sum_f64(&batch);
                    }
                    AggregateOp::Min => {
                        if let Some(batch_min) = simd_min_f64(&batch) {
                            min = min.min(batch_min);
                        }
                    }
                    AggregateOp::Max => {
                        if let Some(batch_max) = simd_max_f64(&batch) {
                            max = max.max(batch_max);
                        }
                    }
                    AggregateOp::Count => {} // Just count, no SIMD needed
                }
                batch.clear();
            }
        }
    }

    // Process final partial batch
    if !batch.is_empty() {
        match op {
            AggregateOp::Sum | AggregateOp::Avg => {
                sum += simd_sum_f64(&batch);
            }
            AggregateOp::Min => {
                if let Some(batch_min) = simd_min_f64(&batch) {
                    min = min.min(batch_min);
                }
            }
            AggregateOp::Max => {
                if let Some(batch_max) = simd_max_f64(&batch) {
                    max = max.max(batch_max);
                }
            }
            AggregateOp::Count => {}
        }
    }

    // Handle empty result set
    if count == 0 {
        return Ok(match op {
            AggregateOp::Count => SqlValue::Integer(0),
            _ => SqlValue::Null,
        });
    }

    // Return aggregated result
    match op {
        AggregateOp::Sum => Ok(SqlValue::Double(sum)), // SUM of floats returns Double
        AggregateOp::Avg => Ok(SqlValue::Double(sum / count as f64)),
        AggregateOp::Min => Ok(SqlValue::Double(min)),
        AggregateOp::Max => Ok(SqlValue::Double(max)),
        AggregateOp::Count => Ok(SqlValue::Integer(count)),
    }
}

/// Determine if a column can use SIMD path based on its data type
///
/// Checks the first non-NULL value in the column to determine if it's
/// an integer or float type suitable for SIMD operations.
///
/// # Returns
///
/// - `Some(true)` if column is i64-compatible (Integer, Bigint, Smallint)
/// - `Some(false)` if column is f64-compatible (Double, Float, Numeric)
/// - `None` if column is not numeric (String, Date, etc.) or all NULL
pub fn can_use_simd_for_column(scan: &ColumnarScan, column_idx: usize) -> Option<bool> {
    // Check first non-NULL value to determine column type
    // IMPORTANT: Only check first 100 rows to avoid materializing huge columns
    for (idx, value_opt) in scan.column(column_idx).enumerate() {
        if idx >= 100 {
            break; // Stop after checking 100 rows
        }

        if let Some(value) = value_opt {
            return match value {
                SqlValue::Integer(_) | SqlValue::Bigint(_) | SqlValue::Smallint(_) => Some(true),
                SqlValue::Double(_) | SqlValue::Float(_) | SqlValue::Numeric(_) => Some(false),
                SqlValue::Null => continue, // Skip NULLs
                _ => None,                  // Not SIMD-compatible
            };
        }
    }

    None // All NULL or empty column
}

#[cfg(test)]
mod tests {
    use vibesql_storage::Row;

    use super::*;

    #[test]
    fn test_simd_aggregate_i64_sum() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Integer(20)]),
            Row::new(vec![SqlValue::Integer(30)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Sum, None).unwrap();
        // SQLite's SUM() always returns REAL (Numeric)
        assert_eq!(result, SqlValue::Integer(60));
    }

    #[test]
    fn test_simd_aggregate_i64_avg() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Integer(20)]),
            Row::new(vec![SqlValue::Integer(30)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Avg, None).unwrap();
        assert!(matches!(result, SqlValue::Double(avg) if (avg - 20.0).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_i64_min_max() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(30)]),
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Integer(20)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let min_result = simd_aggregate_i64(&scan, 0, AggregateOp::Min, None).unwrap();
        // MIN/MAX preserve original type
        assert_eq!(min_result, SqlValue::Integer(10));

        let max_result = simd_aggregate_i64(&scan, 0, AggregateOp::Max, None).unwrap();
        assert_eq!(max_result, SqlValue::Integer(30));
    }

    #[test]
    fn test_simd_aggregate_i64_count() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Integer(20)]),
            Row::new(vec![SqlValue::Integer(30)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Count, None).unwrap();
        assert_eq!(result, SqlValue::Integer(3));
    }

    #[test]
    fn test_simd_aggregate_i64_with_nulls() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Null]),
            Row::new(vec![SqlValue::Integer(30)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Sum, None).unwrap();
        // SQLite's SUM() always returns REAL (Numeric)
        assert_eq!(result, SqlValue::Integer(40));

        let count_result = simd_aggregate_i64(&scan, 0, AggregateOp::Count, None).unwrap();
        assert_eq!(count_result, SqlValue::Integer(2));
    }

    #[test]
    fn test_simd_aggregate_i64_with_filter() {
        let rows = vec![
            Row::new(vec![SqlValue::Integer(10)]),
            Row::new(vec![SqlValue::Integer(20)]),
            Row::new(vec![SqlValue::Integer(30)]),
        ];
        let scan = ColumnarScan::new(&rows);
        let filter = vec![true, false, true]; // Include rows 0 and 2

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Sum, Some(&filter)).unwrap();
        // SQLite's SUM() always returns REAL (Numeric)
        assert_eq!(result, SqlValue::Integer(40));
    }

    #[test]
    fn test_simd_aggregate_f64_sum() {
        let rows = vec![
            Row::new(vec![SqlValue::Double(1.5)]),
            Row::new(vec![SqlValue::Double(2.5)]),
            Row::new(vec![SqlValue::Double(3.5)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_f64(&scan, 0, AggregateOp::Sum, None).unwrap();
        assert!(matches!(result, SqlValue::Double(sum) if (sum - 7.5).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_f64_avg() {
        let rows = vec![
            Row::new(vec![SqlValue::Double(1.0)]),
            Row::new(vec![SqlValue::Double(2.0)]),
            Row::new(vec![SqlValue::Double(3.0)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_f64(&scan, 0, AggregateOp::Avg, None).unwrap();
        assert!(matches!(result, SqlValue::Double(avg) if (avg - 2.0).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_f64_min_max() {
        let rows = vec![
            Row::new(vec![SqlValue::Double(3.0)]),
            Row::new(vec![SqlValue::Double(1.0)]),
            Row::new(vec![SqlValue::Double(2.0)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let min_result = simd_aggregate_f64(&scan, 0, AggregateOp::Min, None).unwrap();
        assert!(matches!(min_result, SqlValue::Double(min) if (min - 1.0).abs() < 0.001));

        let max_result = simd_aggregate_f64(&scan, 0, AggregateOp::Max, None).unwrap();
        assert!(matches!(max_result, SqlValue::Double(max) if (max - 3.0).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_f64_with_nulls() {
        let rows = vec![
            Row::new(vec![SqlValue::Double(1.5)]),
            Row::new(vec![SqlValue::Null]),
            Row::new(vec![SqlValue::Double(3.5)]),
        ];
        let scan = ColumnarScan::new(&rows);

        let result = simd_aggregate_f64(&scan, 0, AggregateOp::Sum, None).unwrap();
        assert!(matches!(result, SqlValue::Double(sum) if (sum - 5.0).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_f64_with_filter() {
        let rows = vec![
            Row::new(vec![SqlValue::Double(1.5)]),
            Row::new(vec![SqlValue::Double(2.5)]),
            Row::new(vec![SqlValue::Double(3.5)]),
        ];
        let scan = ColumnarScan::new(&rows);
        let filter = vec![true, false, true]; // Include rows 0 and 2

        let result = simd_aggregate_f64(&scan, 0, AggregateOp::Sum, Some(&filter)).unwrap();
        assert!(matches!(result, SqlValue::Double(sum) if (sum - 5.0).abs() < 0.001));
    }

    #[test]
    fn test_simd_aggregate_empty_result() {
        let rows =
            vec![Row::new(vec![SqlValue::Integer(10)]), Row::new(vec![SqlValue::Integer(20)])];
        let scan = ColumnarScan::new(&rows);
        let filter = vec![false, false]; // Filter everything out

        let result = simd_aggregate_i64(&scan, 0, AggregateOp::Sum, Some(&filter)).unwrap();
        assert_eq!(result, SqlValue::Null);

        let count_result = simd_aggregate_i64(&scan, 0, AggregateOp::Count, Some(&filter)).unwrap();
        assert_eq!(count_result, SqlValue::Integer(0));
    }

    #[test]
    fn test_can_use_simd_for_column() {
        // Integer column
        let rows =
            vec![Row::new(vec![SqlValue::Integer(10)]), Row::new(vec![SqlValue::Integer(20)])];
        let scan = ColumnarScan::new(&rows);
        assert_eq!(can_use_simd_for_column(&scan, 0), Some(true));

        // Float column
        let rows =
            vec![Row::new(vec![SqlValue::Double(1.5)]), Row::new(vec![SqlValue::Double(2.5)])];
        let scan = ColumnarScan::new(&rows);
        assert_eq!(can_use_simd_for_column(&scan, 0), Some(false));

        // String column (not SIMD-compatible)
        let rows = vec![
            Row::new(vec![SqlValue::Varchar(arcstr::ArcStr::from("hello"))]),
            Row::new(vec![SqlValue::Varchar(arcstr::ArcStr::from("world"))]),
        ];
        let scan = ColumnarScan::new(&rows);
        assert_eq!(can_use_simd_for_column(&scan, 0), None);

        // All NULL column
        let rows = vec![Row::new(vec![SqlValue::Null]), Row::new(vec![SqlValue::Null])];
        let scan = ColumnarScan::new(&rows);
        assert_eq!(can_use_simd_for_column(&scan, 0), None);
    }
}