Skip to main content

readcon_core/
array.rs

1//! Opaque numeric storage for builders and frames (metatensor v0.2.x shape).
2//!
3//! **Design:** internal data is DLPack-shaped (`shape` / `dtype` / `device` /
4//! `as_dlpack(device, stream, max_version)`), not “AoS structs with a DLPack
5//! export bolt-on.” Callers **query** storage dtype/device, then `as_dlpack`
6//! with a **requested device** (and stream / max version)—same contract as
7//! metatensor `mts_array_t`. Choosing f32 vs f64 is choosing **storage**
8//! (or a future typed builder), not passing a cast-target on every export.
9//!
10//! `ConFrame` keeps row-major `ArcArray` blocks for positions and optional
11//! sections; `atom_data` is the CON-text AoS projection for the writer.
12//!
13//! Implementors can swap dtypes (f32 / f64 / u64 / bool), devices (CPU /
14//! future GPU), and ownership (`ArrayD`, `Arc<RwLock<...>>`, …) without
15//! changing the public surface.
16//!
17//! The default backing is `Arc<RwLock<ndarray::ArrayD<T>>>` --
18//!   * `Arc`     : multiple DLPack views can share the same buffer
19//!     across threads / FFI consumers.
20//!   * `RwLock`  : enforces aliasing soundness; concurrent reads
21//!     are non-blocking, concurrent writes contend.
22//!   * `ndarray::ArrayD<T>` : type-erased dimension, generic dtype,
23//!     ndarray's allocator (8-byte aligned, fine for f64; future
24//!     SIMD-aligned variants implement this trait separately).
25//!
26//! See `docs/orgmode/spec.org` §17 for the public contract.
27
28use std::sync::{Arc, RwLock, RwLockReadGuard, TryLockError};
29
30use dlpk::sys::{DLDataType, DLDevice, DLPackVersion};
31use dlpk::{DLPackPointerCast, DLPackTensor, GetDLPackDataType};
32use ndarray::ArrayD;
33
34use crate::error::ParseError;
35
36/// Storage hook for one per-atom field of a ConFrameBuilder.
37///
38/// Implementors hold the raw bytes for a single field (e.g. all atom
39/// positions as a `(N, 3) f64` block) and expose them via DLPack so
40/// downstream consumers can map a numpy / Eigen / torch view onto
41/// the same memory zero-copy.
42pub trait Array: std::any::Any + Send + Sync {
43    /// `&dyn Any` access for downcast (mirrors metatensor's pattern).
44    fn as_any(&self) -> &dyn std::any::Any;
45
46    /// `&mut dyn Any` access for downcast.
47    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
48
49    /// Shape of the underlying tensor.
50    fn shape(&self) -> Vec<usize>;
51
52    /// DLPack dtype of the elements.
53    fn dtype(&self) -> DLDataType;
54
55    /// Device residency of the storage.
56    fn device(&self) -> DLDevice;
57
58    /// Export a DLPack-managed tensor view of this array.
59    ///
60    /// `device` requests the consumer's preferred device; CPU
61    /// implementors return `Err(ParseError::ValidationError(...))`
62    /// when asked for a non-CPU device they cannot service.
63    /// `stream` is the consumer's stream (CUDA / ROCm / SYCL); CPU
64    /// backings ignore it.
65    fn as_dlpack(
66        &self,
67        device: DLDevice,
68        stream: Option<i64>,
69        max_version: DLPackVersion,
70    ) -> Result<DLPackTensor, ParseError>;
71
72    /// Deep-copy this array (used by ConFrameBuilder::clone +
73    /// `move_data`-style ops). Default impl just `clone`s through
74    /// the implementor's natural mechanism.
75    fn copy(&self) -> Box<dyn Array>;
76}
77
78/// Manager context of a DLPack tensor over an `Arc<RwLock<ArrayD<T>>>`:
79/// the buffer stays read-locked, so no writer can change or move it, until
80/// the tensor is deleted.
81struct ReadLockedArray<T: 'static> {
82    // Declared before `_array` so it unlocks before the Arc that owns the
83    // lock is released.
84    _guard: RwLockReadGuard<'static, ArrayD<T>>,
85    _array: Arc<RwLock<ArrayD<T>>>,
86    shape: Vec<i64>,
87    strides: Vec<i64>,
88}
89
90unsafe extern "C" fn read_locked_deleter<T: 'static>(
91    managed: *mut dlpk::sys::DLManagedTensorVersioned,
92) {
93    if managed.is_null() {
94        return;
95    }
96    // `DLPackTensor::from_raw` frees `managed` itself; only the context is ours.
97    unsafe {
98        let ctx = (*managed).manager_ctx;
99        if !ctx.is_null() {
100            drop(Box::from_raw(ctx.cast::<ReadLockedArray<T>>()));
101            (*managed).manager_ctx = std::ptr::null_mut();
102        }
103    }
104}
105
106/// Default Rust backing for the Array trait: shared, lockable,
107/// dynamic-rank ndarray. Matches metatensor v2's
108/// `Arc<RwLock<ArrayD<T>>>` choice and inherits its DLPack +
109/// concurrency semantics.
110///
111/// `as_dlpack` shares the buffer and holds a read lock until the tensor is
112/// deleted: other exports and reads proceed, `try_write` fails and `write`
113/// blocks meanwhile. A `write` on a thread that still holds a live tensor
114/// therefore never returns. Once a writer is waiting, std's `RwLock` lets no
115/// new reader in, so `as_dlpack` returns an error until that writer is done.
116/// Delete each tensor exactly once: the deleter frees the tensor, so a second
117/// call is a use-after-free. Like dlpk's own lock-holding tensors, a tensor
118/// handed through C must be deleted on a thread where releasing a std
119/// `RwLock` read lock is allowed; std's futex and queue locks allow any
120/// thread.
121impl<T> Array for Arc<RwLock<ArrayD<T>>>
122where
123    T: 'static + Send + Sync + Clone + Default + GetDLPackDataType + DLPackPointerCast,
124{
125    fn as_any(&self) -> &dyn std::any::Any {
126        self
127    }
128
129    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
130        self
131    }
132
133    fn shape(&self) -> Vec<usize> {
134        match self.try_read() {
135            Ok(lock) => lock.shape().to_vec(),
136            Err(TryLockError::Poisoned(_)) => panic!("readcon-core array lock is poisoned"),
137            Err(TryLockError::WouldBlock) => panic!("readcon-core array is already locked"),
138        }
139    }
140
141    fn dtype(&self) -> DLDataType {
142        T::get_dlpack_data_type()
143    }
144
145    fn device(&self) -> DLDevice {
146        DLDevice::cpu()
147    }
148
149    fn as_dlpack(
150        &self,
151        device: DLDevice,
152        _stream: Option<i64>,
153        _max_version: DLPackVersion,
154    ) -> Result<DLPackTensor, ParseError> {
155        if device != DLDevice::cpu() {
156            return Err(ParseError::ValidationError(format!(
157                "Arc<RwLock<ArrayD>> is CPU-only; requested device {device:?} unsupported"
158            )));
159        }
160        let array = Arc::clone(self);
161        let guard = match array.try_read() {
162            Ok(lock) => lock,
163            Err(TryLockError::Poisoned(_)) => {
164                return Err(ParseError::ValidationError(
165                    "readcon-core array lock is poisoned".into(),
166                ));
167            }
168            Err(TryLockError::WouldBlock) => {
169                return Err(ParseError::ValidationError(
170                    "readcon-core array is already locked".into(),
171                ));
172            }
173        };
174        // SAFETY: the guard borrows the RwLock inside the Arc allocation,
175        // which `_array` keeps alive and in place; `ReadLockedArray` drops
176        // the guard before `_array`.
177        let guard: RwLockReadGuard<'static, ArrayD<T>> = unsafe { std::mem::transmute(guard) };
178        let data = guard.as_ptr() as *mut std::ffi::c_void;
179        let mut ctx = Box::new(ReadLockedArray {
180            shape: guard.shape().iter().map(|&d| d as i64).collect(),
181            strides: guard.strides().iter().map(|&s| s as i64).collect(),
182            _guard: guard,
183            _array: array,
184        });
185        let dl_tensor = dlpk::sys::DLTensor {
186            data,
187            device: DLDevice::cpu(),
188            ndim: ctx.shape.len() as i32,
189            dtype: T::get_dlpack_data_type(),
190            shape: ctx.shape.as_mut_ptr(),
191            strides: ctx.strides.as_mut_ptr(),
192            byte_offset: 0,
193        };
194        let managed = dlpk::sys::DLManagedTensorVersioned {
195            version: DLPackVersion::current(),
196            manager_ctx: Box::into_raw(ctx).cast(),
197            deleter: Some(read_locked_deleter::<T>),
198            flags: dlpk::sys::DLPACK_FLAG_BITMASK_READ_ONLY,
199            dl_tensor,
200        };
201        // SAFETY: `managed` points at a live buffer and shape/stride arrays
202        // owned by its context, which the deleter frees.
203        Ok(unsafe { DLPackTensor::from_raw(managed) })
204    }
205
206    fn copy(&self) -> Box<dyn Array> {
207        // Cheap Arc clone, NOT a deep copy of the data buffer. If a
208        // caller needs a true deep copy, materialize via
209        // `Arc::new(RwLock::new(ArrayD::clone(&*lock)))`.
210        Box::new(Arc::clone(self))
211    }
212}
213
214/// Convenience constructor for the default backing.
215pub fn array_from_shape<T>(shape: &[usize]) -> Box<dyn Array>
216where
217    T: 'static + Send + Sync + Clone + Default + GetDLPackDataType + DLPackPointerCast,
218{
219    let arr: ArrayD<T> = ArrayD::default(ndarray::IxDyn(shape));
220    Box::new(Arc::new(RwLock::new(arr)))
221}
222
223/// Allocate a new zeroed array **on** `device`.
224///
225/// Default builds only allocate on CPU. Non-CPU allocation fails with a clear
226/// error (not silent reinterpret as CPU). Callers that already own device
227/// memory should use [`array_from_host_f64_on_device`] / [`from_dlpack_f64`] to
228/// **preserve** device identity without allocating on the GPU in this process.
229pub fn allocate_array_on_device(
230    shape: &[usize],
231    device: DLDevice,
232) -> Result<Box<dyn Array>, ParseError> {
233    if device == DLDevice::cpu() {
234        return Ok(array_from_shape::<f64>(shape));
235    }
236    #[cfg(feature = "cuda")]
237    {
238        use dlpk::sys::DLDeviceType;
239        if device.device_type == DLDeviceType::kDLCUDA {
240            return crate::cuda_array::allocate_cuda_f64(shape, device.device_id);
241        }
242    }
243    Err(ParseError::ValidationError(format!(
244        "no device allocator in this build for {device:?}; use caller-supplied device buffers via from_dlpack / array_from_host_f64_on_device, or build with `--features cuda` for CUDA devices"
245    )))
246}
247
248/// Host-resident `f64` buffer tagged with a DLPack `device` (CPU or non-CPU).
249///
250/// Used for **device-preserving interchange**: callers (or tests) supply
251/// buffers that logically live on CUDA/ROCm/etc. without requiring a CUDA
252/// driver in the default build. [`Array::device`] and matching
253/// [`Array::as_dlpack`] requests preserve the tag; mismatched device requests
254/// fail without `--features cuda`; with that feature, CUDA allocate uses real
255/// device memory (see [`crate::cuda_array`]).
256pub struct DeviceTaggedF64Array {
257    shape: Vec<usize>,
258    device: DLDevice,
259    /// Row-major elements (host-visible for contract tests / zero-copy tag).
260    data: Arc<Vec<f64>>,
261}
262
263impl DeviceTaggedF64Array {
264    /// Build from host `f64` values with an explicit DLPack device tag.
265    pub fn new(shape: &[usize], data: Vec<f64>, device: DLDevice) -> Result<Self, ParseError> {
266        let n: usize = shape.iter().product();
267        if data.len() != n {
268            return Err(ParseError::ValidationError(format!(
269                "device-tagged array: expected {n} f64 values for shape {shape:?}, got {}",
270                data.len()
271            )));
272        }
273        Ok(Self {
274            shape: shape.to_vec(),
275            device,
276            data: Arc::new(data),
277        })
278    }
279}
280
281/// Install a device-tagged f64 array (caller-supplied buffer / logical device).
282pub fn array_from_host_f64_on_device(
283    shape: &[usize],
284    data: Vec<f64>,
285    device: DLDevice,
286) -> Result<Box<dyn Array>, ParseError> {
287    Ok(Box::new(DeviceTaggedF64Array::new(shape, data, device)?))
288}
289
290/// Ingest from a DLPack tensor: preserve `tensor.device()` and copy f64 host
291/// elements when the tensor is CPU-addressable; for non-CPU tensors in this
292/// build we still preserve the **device tag** using host staging only when the
293/// tensor reports f64 data that is readable (host tests tag CUDA with host
294/// bytes). Pure allocate-on-GPU without a backend is [`allocate_array_on_device`].
295pub fn from_dlpack_f64(tensor: &DLPackTensor) -> Result<Box<dyn Array>, ParseError> {
296    let device = tensor.device();
297    let shape: Vec<usize> = tensor.shape().iter().map(|&d| d as usize).collect();
298    let n: usize = shape.iter().product();
299    let dtype = tensor.dtype();
300    if dtype.code != dlpk::sys::DLDataTypeCode::kDLFloat || dtype.bits != 64 {
301        return Err(ParseError::ValidationError(format!(
302            "from_dlpack_f64: expected f64, got dtype code={:?} bits={}",
303            dtype.code, dtype.bits
304        )));
305    }
306    // Read elements via data pointer (host-backed tensors and host-staged
307    // device-tagged tests). Non-readable device memory would fail here.
308    let ptr = tensor
309        .data_ptr::<f64>()
310        .map_err(|e| ParseError::ValidationError(format!("from_dlpack_f64 data_ptr: {e}")))?;
311    let mut data = vec![0.0f64; n];
312    if n > 0 {
313        unsafe {
314            std::ptr::copy_nonoverlapping(ptr, data.as_mut_ptr(), n);
315        }
316    }
317    array_from_host_f64_on_device(&shape, data, device)
318}
319
320struct DeviceTaggedManager {
321    data: Arc<Vec<f64>>,
322    shape: Vec<i64>,
323}
324
325unsafe extern "C" fn device_tagged_deleter(managed: *mut dlpk::sys::DLManagedTensorVersioned) {
326    if managed.is_null() {
327        return;
328    }
329    // Only free our manager_ctx. When constructed via `DLPackTensor::from_raw`,
330    // the outer dlpk deleter restores `manager_ctx`/`deleter` then calls us and
331    // finally frees the managed tensor allocation — we must not free `managed`.
332    unsafe {
333        let ctx = (*managed).manager_ctx;
334        if !ctx.is_null() {
335            let _ = Box::from_raw(ctx as *mut DeviceTaggedManager);
336            (*managed).manager_ctx = std::ptr::null_mut();
337        }
338    }
339}
340
341impl Array for DeviceTaggedF64Array {
342    fn as_any(&self) -> &dyn std::any::Any {
343        self
344    }
345
346    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
347        self
348    }
349
350    fn shape(&self) -> Vec<usize> {
351        self.shape.clone()
352    }
353
354    fn dtype(&self) -> DLDataType {
355        f64::get_dlpack_data_type()
356    }
357
358    fn device(&self) -> DLDevice {
359        self.device
360    }
361
362    fn as_dlpack(
363        &self,
364        device: DLDevice,
365        _stream: Option<i64>,
366        _max_version: DLPackVersion,
367    ) -> Result<DLPackTensor, ParseError> {
368        if device != self.device {
369            return Err(ParseError::ValidationError(format!(
370                "device mismatch: array is on {:?}, requested {:?}",
371                self.device, device
372            )));
373        }
374        // Build a managed tensor that reports `self.device` while holding an
375        // Arc to host-resident f64 storage (device-tag preserving interchange
376        // without a CUDA allocator in the default build).
377        let manager = Box::new(DeviceTaggedManager {
378            data: Arc::clone(&self.data),
379            shape: self.shape.iter().map(|&d| d as i64).collect(),
380        });
381        let data_ptr = manager.data.as_ptr() as *mut std::ffi::c_void;
382        let shape_ptr = manager.shape.as_ptr() as *mut i64;
383        let mut managed = dlpk::sys::DLManagedTensorVersioned {
384            version: dlpk::sys::DLPackVersion {
385                major: dlpk::sys::DLPACK_MAJOR_VERSION,
386                minor: dlpk::sys::DLPACK_MINOR_VERSION,
387            },
388            manager_ctx: std::ptr::null_mut(),
389            deleter: Some(device_tagged_deleter),
390            dl_tensor: dlpk::sys::DLTensor {
391                data: data_ptr,
392                device: self.device,
393                ndim: self.shape.len() as i32,
394                dtype: f64::get_dlpack_data_type(),
395                shape: shape_ptr,
396                strides: std::ptr::null_mut(),
397                byte_offset: 0,
398            },
399            flags: dlpk::sys::DLPACK_FLAG_BITMASK_READ_ONLY,
400        };
401        managed.manager_ctx = Box::into_raw(manager) as *mut std::ffi::c_void;
402        // Safety: valid DLManagedTensorVersioned; deleter frees DeviceTaggedManager
403        // (Arc + shape storage). from_raw re-wraps with a Rust manager that
404        // still invokes our deleter.
405        Ok(unsafe { DLPackTensor::from_raw(managed) })
406    }
407
408    fn copy(&self) -> Box<dyn Array> {
409        Box::new(Self {
410            shape: self.shape.clone(),
411            device: self.device,
412            data: Arc::clone(&self.data),
413        })
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    #[test]
422    fn array_from_shape_reports_shape_and_dtype() {
423        let a: Box<dyn Array> = array_from_shape::<f64>(&[5, 3]);
424        assert_eq!(a.shape(), vec![5, 3]);
425        let dt = a.dtype();
426        assert_eq!(dt.code, dlpk::sys::DLDataTypeCode::kDLFloat);
427        assert_eq!(dt.bits, 64);
428        assert_eq!(dt.lanes, 1);
429        assert_eq!(a.device(), DLDevice::cpu());
430    }
431
432    #[test]
433    fn array_copy_shares_storage_via_arc() {
434        let a = array_from_shape::<f64>(&[2, 3]);
435        let b = a.copy();
436        // shapes match
437        assert_eq!(a.shape(), b.shape());
438    }
439
440    #[test]
441    fn array_dlpack_export_round_trip() {
442        let a = array_from_shape::<f64>(&[4, 3]);
443        let tensor = a
444            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
445            .expect("DLPack export should succeed for CPU array");
446        assert_eq!(tensor.shape(), &[4, 3]);
447    }
448
449    fn shared_f64(values: Vec<f64>, shape: &[usize]) -> Arc<RwLock<ArrayD<f64>>> {
450        Arc::new(RwLock::new(
451            ArrayD::from_shape_vec(ndarray::IxDyn(shape), values).unwrap(),
452        ))
453    }
454
455    #[test]
456    fn locked_array_exports_point_at_its_buffer() {
457        let array = shared_f64((0..6).map(f64::from).collect(), &[2, 3]);
458        let buffer = array.read().unwrap().as_ptr();
459        let first = array
460            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
461            .unwrap();
462        let second = array
463            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
464            .unwrap();
465        for tensor in [&first, &second] {
466            assert_eq!(tensor.data_ptr::<f64>().unwrap(), buffer);
467            assert_eq!(tensor.shape(), &[2, 3]);
468            assert_eq!(tensor.strides(), Some(&[3, 1][..]));
469            assert_ne!(tensor.flags() & dlpk::sys::DLPACK_FLAG_BITMASK_READ_ONLY, 0);
470        }
471        assert_eq!(array.shape(), vec![2, 3]);
472    }
473
474    #[test]
475    fn a_live_export_keeps_writers_out_until_it_is_deleted() {
476        let array = shared_f64(vec![1.0, 2.0, 3.0], &[3]);
477        let tensor = array
478            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
479            .unwrap();
480        assert!(matches!(array.try_write(), Err(TryLockError::WouldBlock)));
481        drop(array.try_read().expect("readers still get in"));
482        drop(tensor);
483        array
484            .try_write()
485            .expect("writers get in after the export is deleted")[0] = 9.0;
486        let again = array
487            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
488            .unwrap();
489        assert_eq!(unsafe { *again.data_ptr::<f64>().unwrap() }, 9.0);
490    }
491
492    #[test]
493    fn an_export_outlives_the_last_array_handle() {
494        let array = shared_f64(vec![4.0, 5.0], &[2]);
495        let tensor = array
496            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
497            .unwrap();
498        drop(array);
499        let values = unsafe { std::slice::from_raw_parts(tensor.data_ptr::<f64>().unwrap(), 2) };
500        assert_eq!(values, &[4.0, 5.0]);
501    }
502
503    #[test]
504    fn exporting_a_write_locked_array_is_an_error() {
505        let array = shared_f64(vec![1.0], &[1]);
506        let _writer = array.write().unwrap();
507        assert!(
508            array
509                .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
510                .is_err()
511        );
512    }
513
514    // std's futex RwLock turns new readers away once a writer is waiting.
515    #[cfg(target_os = "linux")]
516    #[test]
517    fn exports_fail_while_a_writer_waits_on_a_live_export() {
518        let array = shared_f64(vec![1.0], &[1]);
519        let held = array
520            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
521            .unwrap();
522        std::thread::scope(|scope| {
523            let writer = scope.spawn(|| array.write().unwrap()[0] = 2.0);
524            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
525            while array
526                .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
527                .is_ok()
528            {
529                assert!(
530                    std::time::Instant::now() < deadline,
531                    "exports kept succeeding while a writer waited"
532                );
533                std::thread::yield_now();
534            }
535            assert!(!writer.is_finished());
536            drop(held);
537            writer.join().unwrap();
538        });
539        assert_eq!(array.read().unwrap()[0], 2.0);
540    }
541
542    // The deleter frees the tensor it is given, so calling it again reads
543    // freed memory. The double call runs in a child process, which
544    // AddressSanitizer must stop with a use-after-free report.
545    #[cfg(asan_run)]
546    #[test]
547    fn a_second_deleter_call_is_a_use_after_free() {
548        const CHILD: &str = "READCON_DOUBLE_DELETE_CHILD";
549        if std::env::var_os(CHILD).is_some() {
550            let array = shared_f64(vec![1.0], &[1]);
551            let tensor = array
552                .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
553                .unwrap()
554                .into_raw()
555                .as_ptr();
556            unsafe {
557                let deleter = (*tensor).deleter.unwrap();
558                deleter(tensor);
559                deleter(tensor);
560            }
561            return;
562        }
563        let output = std::process::Command::new(std::env::current_exe().unwrap())
564            .args([
565                "--exact",
566                "array::tests::a_second_deleter_call_is_a_use_after_free",
567                "--nocapture",
568                "--test-threads=1",
569            ])
570            .env(CHILD, "1")
571            .output()
572            .unwrap();
573        let stderr = String::from_utf8_lossy(&output.stderr);
574        assert!(!output.status.success(), "{stderr}");
575        assert!(stderr.contains("heap-use-after-free"), "{stderr}");
576    }
577
578    /// Without `--features cuda`, non-CPU allocate must fail with a clear error
579    /// (never panic inside a missing driver loader).
580    #[cfg(not(feature = "cuda"))]
581    #[test]
582    fn allocate_non_cpu_fails_clearly() {
583        match allocate_array_on_device(&[2, 3], DLDevice::cuda(0)) {
584            Ok(_) => panic!("non-CPU allocate must fail without --features cuda"),
585            Err(err) => {
586                let msg = format!("{err:?}");
587                assert!(
588                    msg.contains("no device allocator") || msg.contains("allocator"),
589                    "{msg}"
590                );
591            }
592        }
593        let cpu = allocate_array_on_device(&[2, 3], DLDevice::cpu()).unwrap();
594        assert_eq!(cpu.device(), DLDevice::cpu());
595    }
596
597    /// With `--features cuda` and a working driver, allocate on CUDA must succeed
598    /// and report `kDLCUDA` (real device memory path).
599    #[cfg(feature = "cuda")]
600    #[test]
601    fn allocate_cuda_succeeds_with_feature() {
602        if crate::cuda_array::cuda_device_count().is_err() {
603            return;
604        }
605        let a = allocate_array_on_device(&[2, 3], DLDevice::cuda(0))
606            .expect("CUDA allocate must succeed with --features cuda and a driver");
607        assert_eq!(a.device(), DLDevice::cuda(0));
608        assert_eq!(a.device().device_type, dlpk::sys::DLDeviceType::kDLCUDA);
609        let t = a
610            .as_dlpack(DLDevice::cuda(0), None, DLPackVersion::current())
611            .expect("matching as_dlpack");
612        assert_eq!(t.device().device_type, dlpk::sys::DLDeviceType::kDLCUDA);
613        let cpu = allocate_array_on_device(&[2, 3], DLDevice::cpu()).unwrap();
614        assert_eq!(cpu.device(), DLDevice::cpu());
615    }
616
617    #[test]
618    fn cuda_tagged_preserves_device_and_matching_as_dlpack() {
619        let data: Vec<f64> = (0..6).map(|i| i as f64).collect();
620        let a = array_from_host_f64_on_device(&[2, 3], data.clone(), DLDevice::cuda(0)).unwrap();
621        assert_eq!(a.device(), DLDevice::cuda(0));
622        assert_eq!(a.shape(), vec![2, 3]);
623
624        let mismatch = a
625            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
626            .unwrap_err();
627        assert!(
628            format!("{mismatch:?}").contains("device mismatch"),
629            "{mismatch:?}"
630        );
631
632        let tensor = a
633            .as_dlpack(DLDevice::cuda(0), None, DLPackVersion::current())
634            .expect("matching CUDA device export");
635        assert_eq!(tensor.device(), DLDevice::cuda(0));
636        assert_eq!(tensor.shape(), &[2, 3]);
637
638        // from_dlpack preserves device tag
639        let back = from_dlpack_f64(&tensor).unwrap();
640        assert_eq!(back.device(), DLDevice::cuda(0));
641        assert_eq!(back.shape(), vec![2, 3]);
642        let again = back
643            .as_dlpack(DLDevice::cuda(0), None, DLPackVersion::current())
644            .unwrap();
645        assert_eq!(again.device(), DLDevice::cuda(0));
646    }
647
648    #[test]
649    fn cpu_tagged_path_unchanged() {
650        let a =
651            array_from_host_f64_on_device(&[1, 3], vec![1.0, 2.0, 3.0], DLDevice::cpu()).unwrap();
652        assert_eq!(a.device(), DLDevice::cpu());
653        let t = a
654            .as_dlpack(DLDevice::cpu(), None, DLPackVersion::current())
655            .unwrap();
656        assert_eq!(t.device(), DLDevice::cpu());
657        let back = from_dlpack_f64(&t).unwrap();
658        assert_eq!(back.device(), DLDevice::cpu());
659    }
660}