oxiphysics-gpu 0.1.0

GPU acceleration backends for the OxiPhysics engine
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
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Error types for oxiphysics-gpu

#![allow(dead_code)]

use thiserror::Error;

/// Main error type for the gpu module.
#[derive(Debug, Error)]
pub enum Error {
    /// Generic error with a free-form message.
    #[error("{0}")]
    General(String),

    /// A GPU buffer allocation failed.
    #[error(
        "buffer allocation failed: requested {requested_bytes} bytes (available {available_bytes})"
    )]
    BufferAllocationFailed {
        /// Bytes requested.
        requested_bytes: usize,
        /// Bytes actually available.
        available_bytes: usize,
    },

    /// An invalid buffer handle was used.
    #[error("invalid buffer handle: {0}")]
    InvalidBufferHandle(usize),

    /// A shader compilation error (mock).
    #[error("shader compilation error in '{shader}': {message}")]
    ShaderCompilationError {
        /// Name of the offending shader.
        shader: String,
        /// Compiler message.
        message: String,
    },

    /// A dispatch exceeded the hardware work-group limit.
    #[error("dispatch size {dispatch_size} exceeds hardware limit {limit}")]
    DispatchLimitExceeded {
        /// Requested dispatch size (number of work-groups).
        dispatch_size: usize,
        /// Hardware maximum.
        limit: usize,
    },

    /// Out-of-bounds grid access.
    #[error("grid index ({i}, {j}, {k}) out of bounds for grid ({nx}, {ny}, {nz})")]
    GridIndexOutOfBounds {
        /// Requested x index.
        i: usize,
        /// Requested y index.
        j: usize,
        /// Requested z index.
        k: usize,
        /// Grid x dimension.
        nx: usize,
        /// Grid y dimension.
        ny: usize,
        /// Grid z dimension.
        nz: usize,
    },

    /// A kernel argument count mismatch.
    #[error("kernel '{kernel}' expects {expected} arguments but got {got}")]
    KernelArgCountMismatch {
        /// Kernel name.
        kernel: String,
        /// Expected number of arguments.
        expected: usize,
        /// Provided number of arguments.
        got: usize,
    },

    /// An unsupported backend feature was requested.
    #[error("unsupported feature: {feature}")]
    UnsupportedFeature {
        /// Description of the unsupported feature.
        feature: String,
    },
}

/// A pipeline-stage error: carries the stage name plus the underlying cause.
#[derive(Debug, Error)]
#[error("pipeline stage '{stage}' failed: {source}")]
pub struct PipelineStageError {
    /// Name of the pipeline stage (e.g. `"vertex_fetch"`, `"sph_density"`).
    pub stage: String,
    /// Root cause.
    pub source: Box<Error>,
}

/// Severity level for a GPU error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ErrorSeverity {
    /// Informational — execution can continue.
    Info,
    /// Warning — partial results may be degraded.
    Warning,
    /// Fatal — must abort current dispatch.
    Fatal,
}

impl std::fmt::Display for ErrorSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorSeverity::Info => write!(f, "INFO"),
            ErrorSeverity::Warning => write!(f, "WARNING"),
            ErrorSeverity::Fatal => write!(f, "FATAL"),
        }
    }
}

/// An error annotated with severity and an optional kernel name.
#[derive(Debug)]
pub struct AnnotatedError {
    /// The underlying error.
    pub error: Error,
    /// Severity classification.
    pub severity: ErrorSeverity,
    /// Optional kernel that triggered the error.
    pub kernel: Option<String>,
}

impl std::fmt::Display for AnnotatedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref k) = self.kernel {
            write!(f, "[{}] kernel '{}': {}", self.severity, k, self.error)
        } else {
            write!(f, "[{}] {}", self.severity, self.error)
        }
    }
}

impl AnnotatedError {
    /// Wrap an error as fatal with an optional kernel label.
    pub fn fatal(error: Error, kernel: Option<&str>) -> Self {
        Self {
            error,
            severity: ErrorSeverity::Fatal,
            kernel: kernel.map(str::to_string),
        }
    }

    /// Wrap an error as a warning.
    pub fn warning(error: Error, kernel: Option<&str>) -> Self {
        Self {
            error,
            severity: ErrorSeverity::Warning,
            kernel: kernel.map(str::to_string),
        }
    }
}

/// Result type alias
pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    /// Construct a [`Error::General`] from any `Display`-able value.
    pub fn general(msg: impl std::fmt::Display) -> Self {
        Error::General(msg.to_string())
    }

    /// True when this is a recoverable allocation error.
    pub fn is_allocation_error(&self) -> bool {
        matches!(self, Error::BufferAllocationFailed { .. })
    }

    /// True when this is a shader compilation error.
    pub fn is_shader_error(&self) -> bool {
        matches!(self, Error::ShaderCompilationError { .. })
    }

    /// True when this is an out-of-bounds grid error.
    pub fn is_grid_error(&self) -> bool {
        matches!(self, Error::GridIndexOutOfBounds { .. })
    }

    /// True when this is a kernel argument mismatch error.
    pub fn is_arg_mismatch(&self) -> bool {
        matches!(self, Error::KernelArgCountMismatch { .. })
    }

    /// True when this is an unsupported feature error.
    pub fn is_unsupported(&self) -> bool {
        matches!(self, Error::UnsupportedFeature { .. })
    }

    /// Wrap this error in a [`PipelineStageError`].
    pub fn in_stage(self, stage: impl Into<String>) -> PipelineStageError {
        PipelineStageError {
            stage: stage.into(),
            source: Box::new(self),
        }
    }

    /// Annotate with fatal severity.
    pub fn fatal(self, kernel: Option<&str>) -> AnnotatedError {
        AnnotatedError::fatal(self, kernel)
    }

    /// Annotate with warning severity.
    pub fn warning(self, kernel: Option<&str>) -> AnnotatedError {
        AnnotatedError::warning(self, kernel)
    }

    /// Convert into a `Result::Err`.
    pub fn into_err<T>(self) -> Result<T> {
        Err(self)
    }
}

// ── Convenience constructors ─────────────────────────────────────────────────

/// Build a [`Error::BufferAllocationFailed`] error.
pub fn alloc_err(requested_bytes: usize, available_bytes: usize) -> Error {
    Error::BufferAllocationFailed {
        requested_bytes,
        available_bytes,
    }
}

/// Build a [`Error::KernelArgCountMismatch`] error.
pub fn arg_mismatch_err(kernel: impl Into<String>, expected: usize, got: usize) -> Error {
    Error::KernelArgCountMismatch {
        kernel: kernel.into(),
        expected,
        got,
    }
}

/// Build a [`Error::GridIndexOutOfBounds`] error.
#[allow(clippy::too_many_arguments)]
pub fn grid_oob_err(i: usize, j: usize, k: usize, nx: usize, ny: usize, nz: usize) -> Error {
    Error::GridIndexOutOfBounds {
        i,
        j,
        k,
        nx,
        ny,
        nz,
    }
}

/// Build a [`Error::DispatchLimitExceeded`] error.
pub fn dispatch_limit_err(dispatch_size: usize, limit: usize) -> Error {
    Error::DispatchLimitExceeded {
        dispatch_size,
        limit,
    }
}

/// Build a [`Error::ShaderCompilationError`].
pub fn shader_err(shader: impl Into<String>, message: impl Into<String>) -> Error {
    Error::ShaderCompilationError {
        shader: shader.into(),
        message: message.into(),
    }
}

/// Build an [`Error::UnsupportedFeature`].
pub fn unsupported_err(feature: impl Into<String>) -> Error {
    Error::UnsupportedFeature {
        feature: feature.into(),
    }
}

// ── Error collection ─────────────────────────────────────────────────────────

/// Collect multiple errors from a batch dispatch.  Returns `Ok(())` if the
/// vec is empty, or `Err` containing the first error otherwise.
pub fn collect_errors(errors: Vec<Error>) -> Result<()> {
    errors.into_iter().next().map_or(Ok(()), Err)
}

/// Check a boolean condition; return `Err(Error::General(msg))` if false.
pub fn check(condition: bool, msg: impl std::fmt::Display) -> Result<()> {
    if condition {
        Ok(())
    } else {
        Err(Error::general(msg))
    }
}

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

    #[test]
    fn test_general_error_message() {
        let e = Error::general("something went wrong");
        assert_eq!(e.to_string(), "something went wrong");
    }

    #[test]
    fn test_buffer_allocation_failed_message() {
        let e = Error::BufferAllocationFailed {
            requested_bytes: 1024,
            available_bytes: 512,
        };
        let msg = e.to_string();
        assert!(msg.contains("1024"), "should mention requested bytes");
        assert!(msg.contains("512"), "should mention available bytes");
        assert!(e.is_allocation_error());
    }

    #[test]
    fn test_invalid_buffer_handle() {
        let e = Error::InvalidBufferHandle(42);
        assert!(e.to_string().contains("42"));
    }

    #[test]
    fn test_shader_compilation_error() {
        let e = Error::ShaderCompilationError {
            shader: "sph_density".to_string(),
            message: "undefined symbol".to_string(),
        };
        let msg = e.to_string();
        assert!(msg.contains("sph_density"));
        assert!(msg.contains("undefined symbol"));
        assert!(e.is_shader_error());
    }

    #[test]
    fn test_dispatch_limit_exceeded() {
        let e = Error::DispatchLimitExceeded {
            dispatch_size: 100_000,
            limit: 65535,
        };
        let msg = e.to_string();
        assert!(msg.contains("100000"));
        assert!(msg.contains("65535"));
    }

    #[test]
    fn test_grid_index_out_of_bounds() {
        let e = Error::GridIndexOutOfBounds {
            i: 10,
            j: 5,
            k: 3,
            nx: 8,
            ny: 8,
            nz: 8,
        };
        let msg = e.to_string();
        assert!(msg.contains("10"));
        assert!(msg.contains('8'.to_string().as_str()));
    }

    #[test]
    fn test_is_not_shader_error() {
        let e = Error::general("not a shader error");
        assert!(!e.is_shader_error());
    }

    #[test]
    fn test_unsupported_feature() {
        let e = Error::UnsupportedFeature {
            feature: "ray_tracing".to_string(),
        };
        assert!(e.to_string().contains("ray_tracing"));
    }

    // ── New error variant / helper tests ─────────────────────────────────

    #[test]
    fn test_is_grid_error() {
        let e = grid_oob_err(1, 2, 3, 4, 5, 6);
        assert!(e.is_grid_error());
        assert!(!e.is_allocation_error());
    }

    #[test]
    fn test_is_arg_mismatch() {
        let e = arg_mismatch_err("test_kernel", 3, 2);
        assert!(e.is_arg_mismatch());
        assert!(!e.is_shader_error());
    }

    #[test]
    fn test_is_unsupported() {
        let e = unsupported_err("ray_tracing");
        assert!(e.is_unsupported());
    }

    #[test]
    fn test_in_stage_wraps_error() {
        let e = Error::general("boom");
        let wrapped = e.in_stage("sph_density");
        assert!(wrapped.to_string().contains("sph_density"));
        assert!(wrapped.to_string().contains("boom"));
    }

    #[test]
    fn test_alloc_err_convenience() {
        let e = alloc_err(512, 256);
        assert!(e.is_allocation_error());
        assert!(e.to_string().contains("512"));
    }

    #[test]
    fn test_dispatch_limit_err_convenience() {
        let e = dispatch_limit_err(99999, 65535);
        assert!(e.to_string().contains("99999"));
    }

    #[test]
    fn test_shader_err_convenience() {
        let e = shader_err("my_shader", "syntax error");
        assert!(e.is_shader_error());
        assert!(e.to_string().contains("syntax error"));
    }

    #[test]
    fn test_into_err() {
        let result: Result<i32> = Error::general("nope").into_err();
        assert!(result.is_err());
    }

    #[test]
    fn test_collect_errors_empty() {
        assert!(collect_errors(vec![]).is_ok());
    }

    #[test]
    fn test_collect_errors_nonempty() {
        let errs = vec![Error::general("first"), Error::general("second")];
        let result = collect_errors(errs);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("first"));
    }

    #[test]
    fn test_check_passes() {
        assert!(check(true, "should not fail").is_ok());
    }

    #[test]
    fn test_check_fails() {
        let r = check(false, "condition violated");
        assert!(r.is_err());
        assert!(r.unwrap_err().to_string().contains("condition violated"));
    }

    #[test]
    fn test_annotated_error_fatal_display() {
        let e = Error::general("crash");
        let ann = e.fatal(Some("sph_kernel"));
        let s = ann.to_string();
        assert!(s.contains("FATAL"));
        assert!(s.contains("sph_kernel"));
        assert!(s.contains("crash"));
    }

    #[test]
    fn test_annotated_error_warning_no_kernel() {
        let e = Error::general("degraded");
        let ann = e.warning(None);
        let s = ann.to_string();
        assert!(s.contains("WARNING"));
        assert!(s.contains("degraded"));
    }

    #[test]
    fn test_error_severity_ordering() {
        assert!(ErrorSeverity::Info < ErrorSeverity::Warning);
        assert!(ErrorSeverity::Warning < ErrorSeverity::Fatal);
    }

    #[test]
    fn test_error_severity_display() {
        assert_eq!(ErrorSeverity::Info.to_string(), "INFO");
        assert_eq!(ErrorSeverity::Warning.to_string(), "WARNING");
        assert_eq!(ErrorSeverity::Fatal.to_string(), "FATAL");
    }
}