aprender-db 0.34.0

GPU-first embedded analytics database with SIMD fallback and SQL query interface
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
//! GPU compute kernels (WGSL shaders)
//!
//! Parallel Reduction Algorithm (Harris 2007):
//! 1. Each thread loads one element
//! 2. Workgroup-local reduction using shared memory
//! 3. Global reduction of workgroup results
//!
//! Performance: O(N/P + log P) where P = num threads

use crate::{Error, Result};
use arrow::array::{Array, Float32Array, Int32Array};
use wgpu;
use wgpu::util::DeviceExt;

/// Workgroup size (256 threads = 8 warps on NVIDIA, optimal for most GPUs)
const WORKGROUP_SIZE: u32 = 256;

/// WGSL shader for parallel SUM reduction (i32)
const SUM_I32_SHADER: &str = r"
@group(0) @binding(0) var<storage, read> input: array<i32>;
@group(0) @binding(1) var<storage, read_write> output: array<atomic<i32>>;

var<workgroup> shared_data: array<i32, 256>;

@compute @workgroup_size(256)
fn sum_reduce(@builtin(global_invocation_id) global_id: vec3<u32>,
               @builtin(local_invocation_id) local_id: vec3<u32>,
               @builtin(workgroup_id) workgroup_id: vec3<u32>) {
    let tid = local_id.x;
    let gid = global_id.x;
    let input_size = arrayLength(&input);

    // Load data into shared memory
    if (gid < input_size) {
        shared_data[tid] = input[gid];
    } else {
        shared_data[tid] = 0;
    }
    workgroupBarrier();

    // Parallel reduction in shared memory
    var stride = 128u;
    while (stride > 0u) {
        if (tid < stride && gid + stride < input_size) {
            shared_data[tid] += shared_data[tid + stride];
        }
        workgroupBarrier();
        stride = stride / 2u;
    }

    // First thread writes workgroup result
    if (tid == 0u) {
        atomicAdd(&output[0], shared_data[0]);
    }
}
";

/// WGSL shader for parallel SUM reduction (f32)
#[allow(dead_code)]
const SUM_F32_SHADER: &str = r"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

var<workgroup> shared_data: array<f32, 256>;

@compute @workgroup_size(256)
fn sum_reduce(@builtin(global_invocation_id) global_id: vec3<u32>,
               @builtin(local_invocation_id) local_id: vec3<u32>) {
    let tid = local_id.x;
    let gid = global_id.x;
    let input_size = arrayLength(&input);

    // Load data into shared memory
    if (gid < input_size) {
        shared_data[tid] = input[gid];
    } else {
        shared_data[tid] = 0.0;
    }
    workgroupBarrier();

    // Parallel reduction in shared memory
    var stride = 128u;
    while (stride > 0u) {
        if (tid < stride && gid + stride < input_size) {
            shared_data[tid] += shared_data[tid + stride];
        }
        workgroupBarrier();
        stride = stride / 2u;
    }

    // First thread writes workgroup result
    if (tid == 0u) {
        output[0] += shared_data[0];
    }
}
";

/// WGSL shader for COUNT
#[allow(dead_code)]
const COUNT_SHADER: &str = r"
@group(0) @binding(0) var<storage, read_write> output: array<atomic<u32>>;

@compute @workgroup_size(256)
fn count_kernel(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let array_size: u32 = @ARRAY_SIZE@;

    if (global_id.x < array_size) {
        atomicAdd(&output[0], 1u);
    }
}
";

/// WGSL shader for MIN reduction (i32)
#[allow(dead_code)]
const MIN_I32_SHADER: &str = r"
@group(0) @binding(0) var<storage, read> input: array<i32>;
@group(0) @binding(1) var<storage, read_write> output: array<atomic<i32>>;

var<workgroup> shared_data: array<i32, 256>;

@compute @workgroup_size(256)
fn min_reduce(@builtin(global_invocation_id) global_id: vec3<u32>,
              @builtin(local_invocation_id) local_id: vec3<u32>) {
    let tid = local_id.x;
    let gid = global_id.x;
    let input_size = arrayLength(&input);

    // Load data into shared memory
    if (gid < input_size) {
        shared_data[tid] = input[gid];
    } else {
        shared_data[tid] = 2147483647; // i32::MAX
    }
    workgroupBarrier();

    // Parallel reduction in shared memory
    var stride = 128u;
    while (stride > 0u) {
        if (tid < stride && gid + stride < input_size) {
            shared_data[tid] = min(shared_data[tid], shared_data[tid + stride]);
        }
        workgroupBarrier();
        stride = stride / 2u;
    }

    // First thread writes workgroup result
    if (tid == 0u) {
        atomicMin(&output[0], shared_data[0]);
    }
}
";

/// WGSL shader for MAX reduction (i32)
#[allow(dead_code)]
const MAX_I32_SHADER: &str = r"
@group(0) @binding(0) var<storage, read> input: array<i32>;
@group(0) @binding(1) var<storage, read_write> output: array<atomic<i32>>;

var<workgroup> shared_data: array<i32, 256>;

@compute @workgroup_size(256)
fn max_reduce(@builtin(global_invocation_id) global_id: vec3<u32>,
              @builtin(local_invocation_id) local_id: vec3<u32>) {
    let tid = local_id.x;
    let gid = global_id.x;
    let input_size = arrayLength(&input);

    // Load data into shared memory
    if (gid < input_size) {
        shared_data[tid] = input[gid];
    } else {
        shared_data[tid] = -2147483648; // i32::MIN
    }
    workgroupBarrier();

    // Parallel reduction in shared memory
    var stride = 128u;
    while (stride > 0u) {
        if (tid < stride && gid + stride < input_size) {
            shared_data[tid] = max(shared_data[tid], shared_data[tid + stride]);
        }
        workgroupBarrier();
        stride = stride / 2u;
    }

    // First thread writes workgroup result
    if (tid == 0u) {
        atomicMax(&output[0], shared_data[0]);
    }
}
";

/// Execute SUM aggregation on GPU (i32)
///
/// # Errors
/// Returns error if GPU execution fails
///
/// # Panics
/// May panic if buffer mapping fails (internal GPU error)
#[allow(clippy::too_many_lines)]
#[allow(clippy::cast_possible_truncation)]
pub async fn sum_i32(device: &wgpu::Device, queue: &wgpu::Queue, data: &Int32Array) -> Result<i32> {
    let input_data: Vec<i32> = data.values().to_vec();
    let input_size = input_data.len();

    if input_size == 0 {
        return Ok(0);
    }

    // Create input buffer
    let input_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("Input Buffer"),
        contents: bytemuck::cast_slice(&input_data),
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
    });

    // Create output buffer (initialized to 0)
    let output_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("Output Buffer"),
        contents: bytemuck::cast_slice(&[0i32]),
        usage: wgpu::BufferUsages::STORAGE
            | wgpu::BufferUsages::COPY_SRC
            | wgpu::BufferUsages::COPY_DST,
    });

    // Create compute pipeline
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("SUM i32 Shader"),
        source: wgpu::ShaderSource::Wgsl(SUM_I32_SHADER.into()),
    });

    let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("Bind Group Layout"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("Pipeline Layout"),
        bind_group_layouts: &[&bind_group_layout],
        push_constant_ranges: &[],
    });

    let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("SUM i32 Pipeline"),
        layout: Some(&pipeline_layout),
        module: &shader,
        entry_point: "sum_reduce",
        compilation_options: wgpu::PipelineCompilationOptions::default(),
        cache: None,
    });

    // Create bind group
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("Bind Group"),
        layout: &bind_group_layout,
        entries: &[
            wgpu::BindGroupEntry { binding: 0, resource: input_buffer.as_entire_binding() },
            wgpu::BindGroupEntry { binding: 1, resource: output_buffer.as_entire_binding() },
        ],
    });

    // Execute compute shader
    let mut encoder = device
        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Compute Encoder") });

    {
        let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("Compute Pass"),
            timestamp_writes: None,
        });
        compute_pass.set_pipeline(&compute_pipeline);
        compute_pass.set_bind_group(0, &bind_group, &[]);

        let workgroup_count = (input_size as u32).div_ceil(WORKGROUP_SIZE);
        compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
    }

    // Read result buffer
    let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("Staging Buffer"),
        size: 4, // i32 = 4 bytes
        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });

    encoder.copy_buffer_to_buffer(&output_buffer, 0, &staging_buffer, 0, 4);
    queue.submit(Some(encoder.finish()));

    // Map buffer and read result
    let buffer_slice = staging_buffer.slice(..);
    let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
        sender.send(result).expect("Failed to send buffer mapping result through channel");
    });
    device.poll(wgpu::Maintain::Wait);

    receiver
        .receive()
        .await
        .ok_or_else(|| Error::Other("Failed to receive mapping result".to_string()))?
        .map_err(|e| Error::Other(format!("Buffer mapping failed: {e:?}")))?;

    let data = buffer_slice.get_mapped_range();
    let result = i32::from_le_bytes(
        data[0..4].try_into().expect("Buffer must contain at least 4 bytes for i32 result"),
    );
    drop(data);
    staging_buffer.unmap();

    Ok(result)
}

/// Execute SUM aggregation on GPU (f32)
/// Placeholder - not yet implemented
///
/// # Errors
/// Returns error (not yet implemented)
#[allow(clippy::unused_async)]
pub async fn sum_f32(
    _device: &wgpu::Device,
    _queue: &wgpu::Queue,
    _data: &Float32Array,
) -> Result<f32> {
    // Placeholder implementation
    Err(Error::Other("f32 SUM not yet implemented".to_string()))
}

/// Execute COUNT aggregation on GPU
/// Trivial implementation - just returns array length
///
/// # Errors
/// Does not return errors in current implementation
#[allow(clippy::unused_async)]
pub async fn count(
    _device: &wgpu::Device,
    _queue: &wgpu::Queue,
    data: &dyn Array,
) -> Result<usize> {
    // COUNT is trivial - just return array length
    Ok(data.len())
}

/// Execute MIN aggregation on GPU (i32)
///
/// # Errors
/// Returns error if GPU execution fails
///
/// # Panics
/// May panic if buffer mapping fails (internal GPU error)
#[allow(clippy::too_many_lines)]
#[allow(clippy::cast_possible_truncation)]
pub async fn min_i32(device: &wgpu::Device, queue: &wgpu::Queue, data: &Int32Array) -> Result<i32> {
    let input_data: Vec<i32> = data.values().to_vec();
    let input_size = input_data.len();

    if input_size == 0 {
        return Ok(i32::MAX); // Empty array minimum is i32::MAX
    }

    // Create input buffer
    let input_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("MIN Input Buffer"),
        contents: bytemuck::cast_slice(&input_data),
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
    });

    // Create output buffer (initialized to i32::MAX)
    let output_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("MIN Output Buffer"),
        contents: bytemuck::cast_slice(&[i32::MAX]),
        usage: wgpu::BufferUsages::STORAGE
            | wgpu::BufferUsages::COPY_SRC
            | wgpu::BufferUsages::COPY_DST,
    });

    // Create compute pipeline
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("MIN i32 Shader"),
        source: wgpu::ShaderSource::Wgsl(MIN_I32_SHADER.into()),
    });

    let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("MIN Bind Group Layout"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("MIN Pipeline Layout"),
        bind_group_layouts: &[&bind_group_layout],
        push_constant_ranges: &[],
    });

    let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("MIN i32 Pipeline"),
        layout: Some(&pipeline_layout),
        module: &shader,
        entry_point: "min_reduce",
        compilation_options: wgpu::PipelineCompilationOptions::default(),
        cache: None,
    });

    // Create bind group
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("MIN Bind Group"),
        layout: &bind_group_layout,
        entries: &[
            wgpu::BindGroupEntry { binding: 0, resource: input_buffer.as_entire_binding() },
            wgpu::BindGroupEntry { binding: 1, resource: output_buffer.as_entire_binding() },
        ],
    });

    // Execute compute shader
    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("MIN Compute Encoder"),
    });

    {
        let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("MIN Compute Pass"),
            timestamp_writes: None,
        });
        compute_pass.set_pipeline(&compute_pipeline);
        compute_pass.set_bind_group(0, &bind_group, &[]);

        let workgroup_count = (input_size as u32).div_ceil(WORKGROUP_SIZE);
        compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
    }

    // Read result buffer
    let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("MIN Staging Buffer"),
        size: 4, // i32 = 4 bytes
        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });

    encoder.copy_buffer_to_buffer(&output_buffer, 0, &staging_buffer, 0, 4);
    queue.submit(Some(encoder.finish()));

    // Map buffer and read result
    let buffer_slice = staging_buffer.slice(..);
    let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
        sender.send(result).expect("Failed to send buffer mapping result through channel");
    });
    device.poll(wgpu::Maintain::Wait);

    receiver
        .receive()
        .await
        .ok_or_else(|| Error::Other("Failed to receive mapping result".to_string()))?
        .map_err(|e| Error::Other(format!("Buffer mapping failed: {e:?}")))?;

    let data = buffer_slice.get_mapped_range();
    let result = i32::from_le_bytes(
        data[0..4].try_into().expect("Buffer must contain at least 4 bytes for i32 result"),
    );
    drop(data);
    staging_buffer.unmap();

    Ok(result)
}

/// Execute MAX aggregation on GPU (i32)
///
/// # Errors
/// Returns error if GPU execution fails
///
/// # Panics
/// May panic if buffer mapping fails (internal GPU error)
#[allow(clippy::too_many_lines)]
#[allow(clippy::cast_possible_truncation)]
pub async fn max_i32(device: &wgpu::Device, queue: &wgpu::Queue, data: &Int32Array) -> Result<i32> {
    let input_data: Vec<i32> = data.values().to_vec();
    let input_size = input_data.len();

    if input_size == 0 {
        return Ok(i32::MIN); // Empty array maximum is i32::MIN
    }

    // Create input buffer
    let input_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("MAX Input Buffer"),
        contents: bytemuck::cast_slice(&input_data),
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
    });

    // Create output buffer (initialized to i32::MIN)
    let output_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("MAX Output Buffer"),
        contents: bytemuck::cast_slice(&[i32::MIN]),
        usage: wgpu::BufferUsages::STORAGE
            | wgpu::BufferUsages::COPY_SRC
            | wgpu::BufferUsages::COPY_DST,
    });

    // Create compute pipeline
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("MAX i32 Shader"),
        source: wgpu::ShaderSource::Wgsl(MAX_I32_SHADER.into()),
    });

    let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("MAX Bind Group Layout"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("MAX Pipeline Layout"),
        bind_group_layouts: &[&bind_group_layout],
        push_constant_ranges: &[],
    });

    let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("MAX i32 Pipeline"),
        layout: Some(&pipeline_layout),
        module: &shader,
        entry_point: "max_reduce",
        compilation_options: wgpu::PipelineCompilationOptions::default(),
        cache: None,
    });

    // Create bind group
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("MAX Bind Group"),
        layout: &bind_group_layout,
        entries: &[
            wgpu::BindGroupEntry { binding: 0, resource: input_buffer.as_entire_binding() },
            wgpu::BindGroupEntry { binding: 1, resource: output_buffer.as_entire_binding() },
        ],
    });

    // Execute compute shader
    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("MAX Compute Encoder"),
    });

    {
        let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("MAX Compute Pass"),
            timestamp_writes: None,
        });
        compute_pass.set_pipeline(&compute_pipeline);
        compute_pass.set_bind_group(0, &bind_group, &[]);

        let workgroup_count = (input_size as u32).div_ceil(WORKGROUP_SIZE);
        compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
    }

    // Read result buffer
    let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("MAX Staging Buffer"),
        size: 4, // i32 = 4 bytes
        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });

    encoder.copy_buffer_to_buffer(&output_buffer, 0, &staging_buffer, 0, 4);
    queue.submit(Some(encoder.finish()));

    // Map buffer and read result
    let buffer_slice = staging_buffer.slice(..);
    let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
        sender.send(result).expect("Failed to send buffer mapping result through channel");
    });
    device.poll(wgpu::Maintain::Wait);

    receiver
        .receive()
        .await
        .ok_or_else(|| Error::Other("Failed to receive mapping result".to_string()))?
        .map_err(|e| Error::Other(format!("Buffer mapping failed: {e:?}")))?;

    let data = buffer_slice.get_mapped_range();
    let result = i32::from_le_bytes(
        data[0..4].try_into().expect("Buffer must contain at least 4 bytes for i32 result"),
    );
    drop(data);
    staging_buffer.unmap();

    Ok(result)
}

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

    #[tokio::test]
    async fn test_count_returns_array_length() {
        // COUNT is trivial - doesn't need GPU
        let data = Int32Array::from(vec![1, 2, 3, 4, 5]);

        // Create mock device/queue (not used by count())
        let instance = wgpu::Instance::default();
        let Some(adapter) = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await
        else {
            eprintln!("Skipping GPU test (no GPU available)");
            return;
        };
        let Ok((device, queue)) =
            adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await
        else {
            eprintln!("Skipping GPU test (failed to create device)");
            return;
        };

        let result = count(&device, &queue, &data).await.unwrap();
        assert_eq!(result, 5);
    }

    #[tokio::test]
    async fn test_count_empty_array() {
        let data = Int32Array::from(vec![] as Vec<i32>);

        let instance = wgpu::Instance::default();
        let Some(adapter) = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await
        else {
            eprintln!("Skipping GPU test (no GPU available)");
            return;
        };
        let Ok((device, queue)) =
            adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await
        else {
            eprintln!("Skipping GPU test (failed to create device)");
            return;
        };

        let result = count(&device, &queue, &data).await.unwrap();
        assert_eq!(result, 0);
    }

    #[tokio::test]
    async fn test_sum_f32_not_implemented() {
        // sum_f32 is placeholder - should return error
        let data = Float32Array::from(vec![1.0, 2.0, 3.0]);

        let instance = wgpu::Instance::default();
        let Some(adapter) = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await
        else {
            eprintln!("Skipping GPU test (no GPU available)");
            return;
        };
        let Ok((device, queue)) =
            adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await
        else {
            eprintln!("Skipping GPU test (failed to create device)");
            return;
        };

        let result = sum_f32(&device, &queue, &data).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not yet implemented"));
    }
}