1use 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
36pub trait Array: std::any::Any + Send + Sync {
43 fn as_any(&self) -> &dyn std::any::Any;
45
46 fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
48
49 fn shape(&self) -> Vec<usize>;
51
52 fn dtype(&self) -> DLDataType;
54
55 fn device(&self) -> DLDevice;
57
58 fn as_dlpack(
66 &self,
67 device: DLDevice,
68 stream: Option<i64>,
69 max_version: DLPackVersion,
70 ) -> Result<DLPackTensor, ParseError>;
71
72 fn copy(&self) -> Box<dyn Array>;
76}
77
78struct ReadLockedArray<T: 'static> {
82 _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 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
106impl<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 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 Ok(unsafe { DLPackTensor::from_raw(managed) })
204 }
205
206 fn copy(&self) -> Box<dyn Array> {
207 Box::new(Arc::clone(self))
211 }
212}
213
214pub 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
223pub 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
248pub struct DeviceTaggedF64Array {
257 shape: Vec<usize>,
258 device: DLDevice,
259 data: Arc<Vec<f64>>,
261}
262
263impl DeviceTaggedF64Array {
264 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
281pub 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
290pub 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 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 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 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 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 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 #[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 #[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 #[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 #[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 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}