primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Async Submission System for `BarraCuda`
//!
//! Provides non-blocking GPU submission with operation batching.
//!
//! ## Design Philosophy
//!
//! Instead of Vulkan-style timeline semaphores (not directly exposed in wgpu),
//! we use idiomatic wgpu patterns:
//!
//! 1. **Deferred Execution**: Queue multiple operations before submission
//! 2. **Batch Submission**: Submit many command buffers in one call
//! 3. **Async Readback**: Non-blocking buffer reads with futures
//! 4. **Submission Index**: Track work completion without explicit fences
//!
//! ## Deep Debt Evolution (Feb 16, 2026)
//!
//! - Fixed async methods that were blocking inside async context
//! - Added `poll_until_ready()` helper for cooperative async polling
//! - Uses `tokio::task::yield_now()` to avoid starving the executor
//!
//! ## Usage
//!
//! ```rust,ignore
//! use barracuda::device::async_submit::AsyncSubmitter;
//!
//! let submitter = AsyncSubmitter::new(device.clone());
//!
//! // Queue multiple operations (no GPU work yet)
//! submitter.queue_operation(|encoder| {
//!     // ... encode first operation
//! });
//! submitter.queue_operation(|encoder| {
//!     // ... encode second operation  
//! });
//!
//! // Submit all at once (single driver call)
//! let index = submitter.submit_all();
//!
//! // Optionally wait for completion
//! submitter.wait_for(index);
//! ```

use super::WgpuDevice;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// Async GPU submission manager
///
/// Batches GPU operations and provides non-blocking submission tracking.
/// wgpu's `Queue` and `Device` are thread-safe — no external lock needed.
pub struct AsyncSubmitter {
    device: Arc<WgpuDevice>,
    /// Pending command buffers to be submitted
    pending: Mutex<Vec<wgpu::CommandBuffer>>,
    /// Submission counter for tracking work
    submission_index: AtomicU64,
    /// Index of last completed submission (approximate)
    completed_index: AtomicU64,
}

impl AsyncSubmitter {
    /// Create a new async submitter
    #[must_use]
    pub fn new(device: Arc<WgpuDevice>) -> Self {
        Self {
            device,
            pending: Mutex::new(Vec::with_capacity(16)),
            submission_index: AtomicU64::new(0),
            completed_index: AtomicU64::new(0),
        }
    }

    /// Queue a command buffer for deferred submission
    /// The command buffer will be submitted when `submit_all()` is called.
    /// This allows batching multiple operations into a single driver call.
    /// # Panics
    /// Panics if the pending mutex is poisoned.
    pub fn queue(&self, command_buffer: wgpu::CommandBuffer) {
        let mut pending = self
            .pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        pending.push(command_buffer);
    }

    /// Queue an operation using a callback that receives an encoder
    /// Convenience method that creates an encoder, runs the callback,
    /// and queues the finished command buffer.
    pub fn queue_operation<F>(&self, f: F)
    where
        F: FnOnce(&mut wgpu::CommandEncoder),
    {
        let mut encoder =
            self.device
                .device()
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("AsyncSubmitter encoder"),
                });
        f(&mut encoder);
        self.queue(encoder.finish());
    }

    /// Submit all pending command buffers
    /// Returns a submission index that can be used to track completion.
    /// Serialized via `gpu_lock` to prevent wgpu-core storage races.
    /// # Panics
    /// Panics if the pending mutex is poisoned.
    pub fn submit_all(&self) -> u64 {
        let mut pending = self
            .pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if pending.is_empty() {
            return self.submission_index.load(Ordering::SeqCst);
        }

        let index = self.submission_index.fetch_add(1, Ordering::SeqCst) + 1;

        let buffers: Vec<_> = pending.drain(..).collect();
        let lock = self.device.gpu_lock_arc();
        let _guard = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.device.brief_encoder_wait();
        self.device.queue().submit(buffers);

        // Register a callback to update completed index when done
        let completed = Arc::new(AtomicU64::new(0));
        let completed_clone = completed;
        let idx = index;

        self.device.queue().on_submitted_work_done(move || {
            completed_clone.store(idx, Ordering::SeqCst);
        });

        index
    }

    /// Submit a single command buffer immediately
    /// Serialized via `gpu_lock` to prevent wgpu-core storage races.
    pub fn submit_immediate(&self, command_buffer: wgpu::CommandBuffer) -> u64 {
        let index = self.submission_index.fetch_add(1, Ordering::SeqCst) + 1;
        let lock = self.device.gpu_lock_arc();
        let _guard = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.device.brief_encoder_wait();
        self.device.queue().submit(Some(command_buffer));
        index
    }

    /// Get the current submission index
    /// All work with index <= this value has been submitted to the GPU.
    pub fn current_index(&self) -> u64 {
        self.submission_index.load(Ordering::SeqCst)
    }

    /// Check if work at the given index is complete
    /// Note: This is approximate. For precise synchronization, use `wait_for()`.
    pub fn is_complete(&self, index: u64) -> bool {
        self.device.poll_nonblocking();
        self.completed_index.load(Ordering::SeqCst) >= index
    }

    /// Wait for work at the given index to complete
    /// Blocks until all GPU work up to and including the given index is done.
    /// Uses `poll_safe()` to respect the device lock.
    pub fn wait_for(&self, index: u64) {
        if self.completed_index.load(Ordering::SeqCst) >= index {
            return;
        }
        let _ = self.device.poll_safe();
    }

    /// Wait for all pending work to complete
    pub fn wait_all(&self) {
        let current = self.submission_index.load(Ordering::SeqCst);
        self.wait_for(current);
    }

    /// Get the number of pending command buffers
    /// # Panics
    /// Panics if the pending mutex is poisoned.
    pub fn pending_count(&self) -> usize {
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    /// Clear all pending command buffers without submitting
    /// Use with caution - discards queued work.
    /// # Panics
    /// Panics if the pending mutex is poisoned.
    pub fn clear_pending(&self) {
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clear();
    }
}

/// Async buffer read operation
///
/// Wraps a wgpu buffer read that can be awaited without blocking.
/// wgpu's `Device::poll` is thread-safe — no external lock needed.
///
/// Uses `std::sync::mpsc` (stdlib) instead of `futures::channel::oneshot`
/// — no external async runtime required for the channel itself.
pub struct AsyncReadback {
    device: Arc<WgpuDevice>,
    staging_buffer: wgpu::Buffer,
    size_bytes: u64,
    receiver: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
}

impl AsyncReadback {
    /// Create a new async readback operation
    /// Copies from source buffer to staging and initiates async map.
    /// Thread-safe: wgpu's `Queue::submit` handles internal synchronization.
    #[must_use]
    pub fn new(device: &WgpuDevice, source: &wgpu::Buffer, size_bytes: u64) -> Self {
        Self::with_device(Arc::new(device.clone()), source, size_bytes)
    }

    /// Create a new async readback with an explicit device `Arc`.
    #[must_use]
    pub fn with_device(device: Arc<WgpuDevice>, source: &wgpu::Buffer, size_bytes: u64) -> Self {
        let (staging_buffer, commands) = {
            device.encoding_guard();
            let staging = device.device().create_buffer(&wgpu::BufferDescriptor {
                label: Some("AsyncReadback staging"),
                size: size_bytes,
                usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });

            let mut encoder =
                device
                    .device()
                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                        label: Some("AsyncReadback copy"),
                    });
            encoder.copy_buffer_to_buffer(source, 0, &staging, 0, size_bytes);
            let cmds = encoder.finish();
            device.encoding_complete();
            (staging, cmds)
        };

        {
            let lock = device.gpu_lock_arc();
            let _guard = lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            device.brief_encoder_wait();
            device.queue().submit(Some(commands));
        }

        let (sender, receiver) =
            std::sync::mpsc::sync_channel::<std::result::Result<(), wgpu::BufferAsyncError>>(1);
        {
            device.encoding_guard();
            staging_buffer
                .slice(..)
                .map_async(wgpu::MapMode::Read, move |result| {
                    sender.send(result).ok();
                });
            device.encoding_complete();
        }

        Self {
            device,
            staging_buffer,
            size_bytes,
            receiver,
        }
    }

    /// Poll the device and check if data is ready (non-blocking).
    #[must_use]
    pub fn poll(&self) -> bool {
        self.device.poll_nonblocking();
        self.receiver.try_recv().is_ok()
    }

    /// Poll the device until the buffer is ready (async-safe cooperative poll).
    /// Yields to the Tokio executor between device polls to avoid starving
    /// other tasks. Poll is serialized via `poll_lock` to prevent wgpu-core
    /// cleanup races.
    async fn poll_until_ready(&self) -> crate::error::Result<()> {
        use crate::error::BarracudaError;
        loop {
            let poll_ok = !self.device.is_lost();
            if poll_ok {
                self.device.poll_nonblocking();
            }

            if !poll_ok {
                return Err(BarracudaError::device_lost(
                    "GPU device lost during async poll",
                ));
            }

            match self.receiver.try_recv() {
                Ok(result) => {
                    return result.map_err(|e| BarracudaError::gpu(format!("buffer map: {e:?}")));
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => {
                    tokio::task::yield_now().await;
                }
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    return Err(BarracudaError::gpu("readback cancelled — sender dropped"));
                }
            }
        }
    }

    /// Wait for data and read as f32 (async-safe)
    /// Uses cooperative polling that yields to the async executor.
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub async fn read_f32(self) -> crate::error::Result<Vec<f32>> {
        self.poll_until_ready().await?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result: Vec<f32> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        self.staging_buffer.unmap();

        Ok(result)
    }

    /// Wait for data and read as f64 (async-safe)
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub async fn read_f64(self) -> crate::error::Result<Vec<f64>> {
        self.poll_until_ready().await?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result: Vec<f64> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        self.staging_buffer.unmap();

        Ok(result)
    }

    /// Wait for data and read as u32 (async-safe)
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub async fn read_u32(self) -> crate::error::Result<Vec<u32>> {
        self.poll_until_ready().await?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result: Vec<u32> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        self.staging_buffer.unmap();

        Ok(result)
    }

    /// Wait for data and read as raw bytes (async-safe)
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub async fn read_bytes(self) -> crate::error::Result<bytes::Bytes> {
        self.poll_until_ready().await?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result = bytes::Bytes::copy_from_slice(&data);

        drop(data);
        self.staging_buffer.unmap();

        Ok(result)
    }

    /// Blocking read as f32 (for sync contexts).
    /// Uses `poll_safe()` so the map callback fires before `recv()` — no async runtime needed.
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub fn read_f32_blocking(self) -> crate::error::Result<Vec<f32>> {
        use crate::error::BarracudaError;
        self.device
            .poll_safe()
            .map_err(|_| BarracudaError::device_lost("GPU device lost during blocking poll"))?;

        self.receiver
            .recv()
            .map_err(|_| BarracudaError::gpu("readback cancelled — sender dropped"))?
            .map_err(|e| BarracudaError::gpu(format!("buffer map: {e:?}")))?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result = bytemuck::cast_slice::<u8, f32>(&data).to_vec();
        drop(data);
        self.staging_buffer.unmap();
        Ok(result)
    }

    /// Blocking read as f64 (for sync contexts).
    /// # Errors
    /// Returns [`Err`] if the GPU device is lost during poll, buffer mapping fails,
    /// or the readback is cancelled (sender dropped).
    pub fn read_f64_blocking(self) -> crate::error::Result<Vec<f64>> {
        use crate::error::BarracudaError;
        self.device
            .poll_safe()
            .map_err(|_| BarracudaError::device_lost("GPU device lost during blocking poll"))?;

        self.receiver
            .recv()
            .map_err(|_| BarracudaError::gpu("readback cancelled — sender dropped"))?
            .map_err(|e| BarracudaError::gpu(format!("buffer map: {e:?}")))?;

        let data = self.staging_buffer.slice(..).get_mapped_range();
        let result = bytemuck::cast_slice::<u8, f64>(&data).to_vec();
        drop(data);
        self.staging_buffer.unmap();
        Ok(result)
    }

    /// Get the size in bytes
    #[must_use]
    pub fn size_bytes(&self) -> u64 {
        self.size_bytes
    }
}

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

    #[tokio::test]
    async fn test_submitter_creation() {
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let submitter = AsyncSubmitter::new(Arc::clone(&wgpu_device));
        assert_eq!(submitter.pending_count(), 0);
        assert_eq!(submitter.current_index(), 0);
    }

    #[test]
    fn test_submission_index_increment() {
        let index = AtomicU64::new(0);
        assert_eq!(index.fetch_add(1, Ordering::SeqCst) + 1, 1);
        assert_eq!(index.fetch_add(1, Ordering::SeqCst) + 1, 2);
    }

    #[tokio::test]
    async fn test_submitter_queue_and_submit() {
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let submitter = AsyncSubmitter::new(Arc::clone(&wgpu_device));

        submitter.queue_operation(|encoder| {
            let _ = encoder; // noop command buffer
        });
        assert_eq!(submitter.pending_count(), 1);

        submitter.queue_operation(|encoder| {
            let _ = encoder;
        });
        assert_eq!(submitter.pending_count(), 2);

        let idx = submitter.submit_all();
        assert_eq!(idx, 1);
        assert_eq!(submitter.pending_count(), 0);
    }

    #[tokio::test]
    async fn test_submitter_multiple_submissions() {
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let submitter = AsyncSubmitter::new(Arc::clone(&wgpu_device));

        submitter.queue_operation(|_| {});
        let idx1 = submitter.submit_all();

        submitter.queue_operation(|_| {});
        let idx2 = submitter.submit_all();

        assert_eq!(idx1, 1);
        assert_eq!(idx2, 2);
        assert_eq!(submitter.current_index(), 2);
    }

    #[tokio::test]
    async fn test_submitter_empty_submit() {
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let submitter = AsyncSubmitter::new(Arc::clone(&wgpu_device));
        let idx = submitter.submit_all();
        assert_eq!(idx, 0, "empty submit should not increment index");
    }

    #[tokio::test]
    async fn test_readback_creation_and_f32_roundtrip() {
        use wgpu::util::DeviceExt;
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let data: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0];
        wgpu_device.encoding_guard();
        let buffer = wgpu_device
            .device()
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("test_readback_src"),
                contents: bytemuck::cast_slice(&data),
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            });
        wgpu_device.encoding_complete();

        let readback = AsyncReadback::new(&wgpu_device, &buffer, buffer.size());
        assert_eq!(readback.size_bytes(), buffer.size());

        match readback.read_f32().await {
            Ok(result) => assert_eq!(result, data),
            Err(e) if e.is_retriable() => return,
            Err(e) => panic!("readback failed: {e}"),
        }
    }

    #[tokio::test]
    async fn test_readback_bytes_roundtrip() {
        use wgpu::util::DeviceExt;
        let Some(wgpu_device) = crate::device::test_pool::get_test_device_if_gpu_available().await
        else {
            return;
        };

        let data: Vec<f32> = vec![42.0, 99.0];
        wgpu_device.encoding_guard();
        let buffer = wgpu_device
            .device()
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("test_readback_bytes"),
                contents: bytemuck::cast_slice(&data),
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            });
        wgpu_device.encoding_complete();

        let readback = AsyncReadback::new(&wgpu_device, &buffer, buffer.size());
        match readback.read_bytes().await {
            Ok(result) => assert_eq!(result.len(), std::mem::size_of::<f32>() * 2),
            Err(e) if e.is_retriable() => return,
            Err(e) => panic!("readback failed: {e}"),
        }
    }
}