From cb3cdc4fe38f34ee31829a13c0660133a436fc62 Mon Sep 17 00:00:00 2001
From: Andreas Kloeckner <inform@tiker.net>
Date: Mon, 5 Sep 2022 20:28:28 -0500
Subject: [PATCH] Array constructor: warn about SVM queue inconsistencies

---
 pyopencl/array.py | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/pyopencl/array.py b/pyopencl/array.py
index e09f9e3a..851a0bb4 100644
--- a/pyopencl/array.py
+++ b/pyopencl/array.py
@@ -50,6 +50,11 @@ from numbers import Number
 
 SCALAR_CLASSES = (Number, np.bool_, bool)
 
+if cl.get_cl_header_version() >= (2, 0):
+    _SVMPointer_or_nothing = cl.SVMPointer
+else:
+    _SVMPointer_or_nothing = ()
+
 
 _COMMON_DTYPE_CACHE = {}
 
@@ -254,6 +259,7 @@ class _copy_queue:  # noqa
 
 _ARRAY_GET_SIZES_CACHE = {}
 _BOOL_DTYPE = np.dtype(np.int8)
+_NOT_PRESENT = object()
 
 
 class Array:
@@ -590,6 +596,16 @@ class Array:
         self.context = context
         self._flags = _flags
 
+        if __debug__:
+            if queue is not None and isinstance(
+                    self.base_data, _SVMPointer_or_nothing):
+                mem_queue = getattr(self.base_data, "_queue", _NOT_PRESENT)
+                if mem_queue is not _NOT_PRESENT and mem_queue != queue:
+                    warn("Array has different queue from backing SVM memory. "
+                         "This may lead to the array getting deallocated sooner "
+                         "than expected, potentially leading to crashes.",
+                         InconsistentOpenCLQueueWarning, stacklevel=2)
+
     @property
     def ndim(self):
         return len(self.shape)
-- 
GitLab