1mod callback;
4mod capture;
5mod context;
6mod raw;
7mod scope;
8
9pub mod memory;
10
11mod cleanup;
12
13mod sealed {
14 #[expect(
15 unnameable_types,
16 reason = "sealed supertrait that other crates must not name or implement"
17 )]
18 pub trait Sealed {}
19}
20
21use std::{
22 collections::HashMap,
23 fmt::{self, Display, Formatter},
24 hash::{Hash, Hasher},
25 mem, ptr,
26 sync::{Arc, Mutex, MutexGuard, OnceLock, Weak},
27};
28
29use bitflags::parser;
30use singe_core::{abort_after_cleanup_failure, report_cleanup_failure};
31use singe_cuda_sys::runtime;
32
33use crate::{
34 context::Context,
35 device::Device,
36 error::{Error, Result, Status},
37 event::{Event, EventFlags, EventRecordFlags, EventWaitFlags},
38 memory::DeferredFree,
39 try_ffi,
40 utility::lock_for_cleanup,
41 view::DeviceRegion,
42};
43
44use self::raw::ForeignOwner;
45pub use self::{
46 capture::{
47 StreamCaptureDependencyUpdate, StreamCaptureInfo, StreamCaptureMode, StreamCaptureScope,
48 StreamCaptureStatus, exchange_capture_mode,
49 },
50 raw::{RawStream, RawStreamOwnership},
51 scope::StreamScope,
52};
53
54bitflags::bitflags! {
55 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57 pub struct StreamFlags: u32 {
58 const DEFAULT = runtime::cudaStreamDefault;
60 const NON_BLOCKING = runtime::cudaStreamNonBlocking;
62 }
63}
64
65impl Display for StreamFlags {
66 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
67 parser::to_writer(self, f)
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct StreamOptions {
74 pub flags: StreamFlags,
76 pub priority: i32,
80}
81
82impl Default for StreamOptions {
83 fn default() -> Self {
84 Self {
85 flags: StreamFlags::DEFAULT,
86 priority: 0,
87 }
88 }
89}
90
91#[derive(Debug, Clone)]
97pub struct Stream {
98 inner: Arc<StreamInner>,
99}
100
101#[derive(Debug)]
102struct StreamInner {
103 handle: runtime::cudaStream_t,
104 context: Arc<Context>,
105 capture_cleanup: Arc<Mutex<CaptureCleanup>>,
106 foreign_owner: Option<ForeignOwner>,
107}
108
109impl PartialEq for Stream {
110 fn eq(&self, other: &Self) -> bool {
111 self.identity() == other.identity()
112 }
113}
114
115impl Eq for Stream {}
116
117impl Hash for Stream {
118 fn hash<H: Hasher>(&self, state: &mut H) {
119 Hash::hash(&self.identity(), state);
120 }
121}
122
123#[derive(Debug, Clone)]
128pub struct BorrowedStream {
129 handle: runtime::cudaStream_t,
130 context: Arc<Context>,
131 _owner: Option<Stream>,
132}
133
134#[derive(Debug, Clone)]
136#[non_exhaustive]
137pub enum StreamBinding {
138 Default(Arc<Context>),
140 Borrowed(BorrowedStream),
142}
143
144pub trait AsStream: sealed::Sealed {
149 fn context(&self) -> &Arc<Context>;
151
152 fn as_raw(&self) -> runtime::cudaStream_t;
154
155 fn synchronize(&self) -> Result<()> {
161 self.context().bind()?;
162 unsafe { try_ffi!(runtime::cudaStreamSynchronize(self.as_raw())) }
164 }
165
166 fn synchronize_or_abort(&self) {
170 if let Err(error) = self.synchronize() {
171 abort_after_cleanup_failure("synchronize", "cuda stream", &error);
172 }
173 }
174
175 fn capture_status(&self) -> Result<StreamCaptureStatus> {
181 self.context().bind()?;
182 let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
183 unsafe {
185 try_ffi!(runtime::cudaStreamIsCapturing(
186 self.as_raw(),
187 &raw mut status
188 ))?;
189 }
190 Ok(status.try_into()?)
191 }
192
193 fn ensure_not_capturing(&self) -> Result<()> {
199 match self.capture_status()? {
200 StreamCaptureStatus::None => Ok(()),
201 StreamCaptureStatus::Active => Err(Status::StreamCaptureUnsupported.into()),
202 StreamCaptureStatus::Invalidated => Err(Status::StreamCaptureInvalidated.into()),
203 }
204 }
205
206 fn wait_event(&self, event: &Event, flags: EventWaitFlags) -> Result<()> {
214 self.context().bind()?;
215 unsafe {
217 try_ffi!(runtime::cudaStreamWaitEvent(
218 self.as_raw(),
219 event.as_raw(),
220 flags.bits(),
221 ))
222 }
223 }
224
225 fn join_regions(&self, regions: &[DeviceRegion<'_>]) -> Result<()> {
234 if regions
235 .iter()
236 .any(|region| region.context() != self.context())
237 {
238 return Err(Error::MemoryContextMismatch);
239 }
240
241 let identity = StreamIdentity::new(self.context(), self.as_raw());
242 for (index, region) in regions.iter().enumerate() {
243 if let Some(producer) = region.stream()
244 && producer.identity() != identity
245 && !regions[..index]
246 .iter()
247 .any(|earlier| earlier.stream() == Some(producer))
248 {
249 let event = producer
250 .context()
251 .create_event(EventFlags::DISABLE_TIMING)?;
252 event.record(producer, EventRecordFlags::DEFAULT)?;
253 self.wait_event(&event, EventWaitFlags::DEFAULT)?;
254 }
255 }
256 Ok(())
257 }
258}
259
260const LEGACY_STREAM: usize = 1;
261const PER_THREAD_STREAM: usize = 2;
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265pub(crate) struct StreamIdentity {
266 context: usize,
267 handle: usize,
268}
269
270impl StreamIdentity {
271 pub(crate) fn new(context: &Context, handle: runtime::cudaStream_t) -> Self {
272 let handle = handle.addr();
273 Self {
274 context: context.as_raw().addr(),
275 handle: if handle == LEGACY_STREAM { 0 } else { handle },
276 }
277 }
278}
279
280#[derive(Debug, Default)]
281pub(crate) struct CaptureCleanup {
282 owners: Vec<Arc<dyn fmt::Debug + Send + Sync>>,
283 frees: Vec<DeferredFree>,
284 foreign: Vec<ForeignOwner>,
285}
286
287impl CaptureCleanup {
288 fn for_stream(key: StreamIdentity) -> Result<Arc<Mutex<Self>>> {
289 type Registry = HashMap<StreamIdentity, Weak<Mutex<CaptureCleanup>>>;
290
291 static LIFECYCLES: OnceLock<Mutex<Registry>> = OnceLock::new();
292 let mut lifecycles = LIFECYCLES
293 .get_or_init(Mutex::default)
294 .lock()
295 .map_err(|_| Error::lock_poisoned("stream lifecycles"))?;
296 lifecycles.retain(|_, lifecycle| lifecycle.strong_count() != 0);
297 if let Some(lifecycle) = lifecycles.get(&key).and_then(Weak::upgrade) {
298 return Ok(lifecycle);
299 }
300
301 let lifecycle = Arc::new(Mutex::new(Self::default()));
302 lifecycles.insert(key, Arc::downgrade(&lifecycle));
303 drop(lifecycles);
304 Ok(lifecycle)
305 }
306
307 fn is_empty(&self) -> bool {
308 self.owners.is_empty() && self.frees.is_empty() && self.foreign.is_empty()
309 }
310
311 fn flush_frees(&mut self, stream: runtime::cudaStream_t) -> Result<()> {
312 while let Some(free) = self.frees.last() {
313 free.enqueue(stream)?;
314 self.frees.pop();
315 }
316
317 self.foreign.clear();
318 Ok(())
319 }
320}
321
322impl Stream {
323 pub(crate) fn identity(&self) -> StreamIdentity {
324 StreamIdentity::new(self.context(), self.as_raw())
325 }
326
327 pub fn defer_drop_until_capture_end<T>(&self, owner: Arc<T>) -> Result<()>
338 where
339 T: fmt::Debug + Send + Sync + 'static,
340 {
341 let mut cleanup = lock_for_cleanup(&self.inner.capture_cleanup);
342 if self.capture_status()? != StreamCaptureStatus::None {
343 cleanup.owners.push(owner);
344 }
345
346 drop(cleanup);
347 Ok(())
348 }
349
350 fn capture_cleanup_lock(&self) -> Result<MutexGuard<'_, CaptureCleanup>> {
351 self.inner
352 .capture_cleanup
353 .lock()
354 .map_err(|_| Error::lock_poisoned("stream capture cleanup"))
355 }
356
357 pub(crate) fn allocation_guard(&self) -> Result<MutexGuard<'_, CaptureCleanup>> {
358 let mut cleanup = self.capture_cleanup_lock()?;
359 self.ensure_not_capturing()?;
360 cleanup.flush_frees(self.as_raw())?;
361 Ok(cleanup)
362 }
363
364 pub(crate) fn defer_free(&self, free: DeferredFree) -> Result<()> {
365 let mut cleanup = lock_for_cleanup(&self.inner.capture_cleanup);
366 cleanup.frees.push(free);
367 if self.capture_status()? == StreamCaptureStatus::None {
368 cleanup.flush_frees(self.as_raw())?;
369 }
370
371 drop(cleanup);
372 Ok(())
373 }
374
375 #[must_use]
377 pub fn to_borrowed(&self) -> BorrowedStream {
378 BorrowedStream {
379 handle: self.as_raw(),
380 context: Arc::clone(&self.inner.context),
381 _owner: Some(self.clone()),
382 }
383 }
384
385 #[must_use]
393 pub unsafe fn to_unretained(&self) -> BorrowedStream {
394 BorrowedStream {
395 handle: self.as_raw(),
396 context: Arc::clone(&self.inner.context),
397 _owner: None,
398 }
399 }
400
401 pub fn synchronize(&self) -> Result<()> {
412 AsStream::synchronize(self)
413 }
414
415 pub fn synchronize_or_abort(&self) {
419 AsStream::synchronize_or_abort(self);
420 }
421
422 pub fn shutdown(self) -> Result<()> {
435 let lifecycle = Arc::clone(&self.inner.capture_cleanup);
436 let mut cleanup = lifecycle
437 .lock()
438 .map_err(|_| Error::lock_poisoned("stream capture cleanup"))?;
439 self.ensure_not_capturing()?;
440 cleanup.flush_frees(self.as_raw())?;
441 let mut inner = match Arc::try_unwrap(self.inner) {
442 Ok(inner) => inner,
443 Err(inner) => {
444 drop(cleanup);
446 drop(inner);
447 return Err(Error::ownership_shared("stream"));
448 }
449 };
450 let result = if inner.foreign_owner.is_some() {
451 inner
452 .context
453 .bind()
454 .and_then(|()| unsafe { try_ffi!(runtime::cudaStreamSynchronize(inner.handle)) })
456 } else {
457 Self::destroy_handle(inner.context.as_ref(), inner.handle)
458 };
459 inner.handle = ptr::null_mut();
460 let owner = inner.foreign_owner.take();
461 drop(cleanup);
463 drop(owner);
464 result
465 }
466
467 pub fn query(&self) -> Result<bool> {
479 self.inner.context.bind()?;
480 let error = unsafe { runtime::cudaStreamQuery(self.as_raw()) };
482 match error {
483 runtime::cudaError_t::CUDA_SUCCESS => Ok(true),
484 runtime::cudaError_t::CUDA_ERROR_NOT_READY => Ok(false),
485 _ => Err(error.into()),
486 }
487 }
488
489 pub fn wait_event(&self, event: &Event, flags: EventWaitFlags) -> Result<()> {
499 AsStream::wait_event(self, event, flags)
500 }
501
502 pub fn fork(&self) -> Result<Self> {
513 let branch = self.context().create_stream(StreamOptions {
514 flags: StreamFlags::NON_BLOCKING,
515 priority: self.priority()?,
516 })?;
517 branch.join(self)?;
518 Ok(branch)
519 }
520
521 pub fn join(&self, other: &Self) -> Result<()> {
531 if self == other {
532 return Ok(());
533 }
534
535 let event = other.context().create_event(EventFlags::DISABLE_TIMING)?;
536 event.record(other, EventRecordFlags::DEFAULT)?;
537 self.wait_event(&event, EventWaitFlags::DEFAULT)
538 }
539
540 pub fn join_regions(&self, regions: &[DeviceRegion<'_>]) -> Result<()> {
551 AsStream::join_regions(self, regions)
552 }
553
554 pub fn flags(&self) -> Result<StreamFlags> {
566 self.inner.context.bind()?;
567 let mut flags_raw = 0u32;
568 unsafe {
570 try_ffi!(runtime::cudaStreamGetFlags(
571 self.as_raw(),
572 &raw mut flags_raw
573 ))?;
574 }
575 Ok(StreamFlags::from_bits_retain(flags_raw))
576 }
577
578 pub fn priority(&self) -> Result<i32> {
587 self.inner.context.bind()?;
588 let mut priority = 0i32;
589 unsafe {
591 try_ffi!(runtime::cudaStreamGetPriority(
592 self.as_raw(),
593 &raw mut priority
594 ))?;
595 }
596 Ok(priority)
597 }
598
599 pub fn id(&self) -> Result<u64> {
612 self.inner.context.bind()?;
613 let mut id = 0u64;
614 unsafe {
616 try_ffi!(runtime::cudaStreamGetId(self.as_raw(), &raw mut id))?;
617 }
618 Ok(id)
619 }
620
621 pub fn device(&self) -> Result<Device> {
627 self.inner.context.bind()?;
628 let mut device = 0i32;
629 unsafe {
631 try_ffi!(runtime::cudaStreamGetDevice(self.as_raw(), &raw mut device))?;
632 }
633 Ok(Device::new(device))
634 }
635
636 #[must_use]
638 pub fn context(&self) -> &Arc<Context> {
639 &self.inner.context
640 }
641
642 #[must_use]
644 pub fn as_raw(&self) -> runtime::cudaStream_t {
645 self.inner.handle
646 }
647}
648
649impl BorrowedStream {
650 pub const unsafe fn from_raw(handle: runtime::cudaStream_t, context: Arc<Context>) -> Self {
656 Self {
657 handle,
658 context,
659 _owner: None,
660 }
661 }
662}
663
664impl StreamBinding {
665 #[must_use]
667 pub fn is_default(&self) -> bool {
668 matches!(self, Self::Default(..))
669 }
670}
671
672impl sealed::Sealed for Stream {}
673
674impl AsStream for Stream {
675 fn context(&self) -> &Arc<Context> {
676 &self.inner.context
677 }
678
679 fn as_raw(&self) -> runtime::cudaStream_t {
680 self.inner.handle
681 }
682}
683
684impl sealed::Sealed for BorrowedStream {}
685
686impl AsStream for BorrowedStream {
687 fn context(&self) -> &Arc<Context> {
688 &self.context
689 }
690
691 fn as_raw(&self) -> runtime::cudaStream_t {
692 self.handle
693 }
694}
695
696impl sealed::Sealed for StreamBinding {}
697
698impl AsStream for StreamBinding {
699 fn context(&self) -> &Arc<Context> {
700 match self {
701 Self::Default(context) => context,
702 Self::Borrowed(stream) => &stream.context,
703 }
704 }
705
706 fn as_raw(&self) -> runtime::cudaStream_t {
707 match self {
708 Self::Default(_) => ptr::null_mut(),
709 Self::Borrowed(stream) => stream.handle,
710 }
711 }
712}
713
714unsafe impl Send for StreamInner {}
716
717unsafe impl Sync for StreamInner {}
719
720impl Drop for StreamInner {
721 fn drop(&mut self) {
722 if self.handle.is_null() && self.foreign_owner.is_none() {
723 return;
724 }
725
726 let mut cleanup = lock_for_cleanup(&self.capture_cleanup);
727 if Arc::strong_count(&self.capture_cleanup) == 1 && !cleanup.is_empty() {
728 let ended = self.context.bind().and_then(|()| unsafe {
730 let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
731 try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
732 if status != runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
733 let mut graph = ptr::null_mut();
734 if let Err(error) =
736 try_ffi!(runtime::cudaStreamEndCapture(self.handle, &raw mut graph))
737 {
738 report_cleanup_failure("end", "cuda stream capture", &error);
739 }
740
741 if !graph.is_null()
742 && let Err(error) = try_ffi!(runtime::cudaGraphDestroy(graph))
743 {
744 report_cleanup_failure("destroy", "cuda graph", &error);
745 }
746
747 try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
748 if status != runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
749 return Err(Error::out_of_range("stream capture status"));
750 }
751 }
752 Ok(())
753 });
754 if let Err(error) = ended {
755 report_cleanup_failure(
757 "end the capture to release deferred owners of",
758 "cuda stream",
759 &error,
760 );
761 mem::forget(mem::take(&mut *cleanup));
762 } else {
763 if let Err(error) = cleanup.flush_frees(self.handle) {
764 report_cleanup_failure("enqueue", "deferred cuda frees", &error);
765 mem::forget(mem::take(&mut cleanup.frees));
766 }
767
768 cleanup.owners.clear();
769 }
770 }
771
772 drop(cleanup);
773 if self.foreign_owner.is_some() {
774 let result = self.context.bind().and_then(|()| unsafe {
776 let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
777 try_ffi!(runtime::cudaStreamIsCapturing(self.handle, &raw mut status))?;
778 if status == runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE {
779 try_ffi!(runtime::cudaStreamSynchronize(self.handle))?;
780 }
781 Ok(())
782 });
783 if let Err(error) = result {
784 report_cleanup_failure("synchronize", "foreign cuda stream", &error);
785 }
786 } else {
787 if let Err(error) = self.context.bind() {
788 report_cleanup_failure("bind the cuda context to destroy", "cuda stream", &error);
789 return;
790 }
791
792 if let Err(error) = Stream::destroy_handle(self.context.as_ref(), self.handle) {
793 report_cleanup_failure("destroy", "cuda stream", &error);
794 }
795 }
796 }
797}
798
799#[cfg(all(test, feature = "testing"))]
800mod tests {
801 use std::{
802 panic,
803 sync::{
804 Arc,
805 atomic::{AtomicBool, Ordering},
806 },
807 thread,
808 };
809
810 use super::*;
811 use crate::{
812 context::ContextFlags,
813 event::EventRecordFlags,
814 graph::{GraphDependency, GraphEdgeAttributes, GraphInstantiateFlags, GraphNode},
815 memory::{DeviceMemory, MemoryCopyKind},
816 testing,
817 };
818
819 #[test]
820 fn test_it_works() -> Result<()> {
821 let test_device = testing::bootstrap()?;
822 let context = Arc::clone(test_device.context());
823 let stream1 = context.create_stream(StreamOptions::default())?;
824 let _stream2 = context.create_stream(StreamOptions {
825 flags: StreamFlags::NON_BLOCKING,
826 ..StreamOptions::default()
827 })?;
828
829 let stream1_called = Arc::new(AtomicBool::new(false));
830 stream1.add_callback(Box::new({
831 let stream1_called = Arc::clone(&stream1_called);
832 move |_status| {
833 stream1_called.store(true, Ordering::SeqCst);
834 }
835 }))?;
836
837 let is_done = stream1.query()?;
838 assert!(!is_done);
839
840 stream1.synchronize()?;
841
842 let is_done_after = stream1.query()?;
843 assert!(is_done_after);
844
845 assert!(stream1_called.load(Ordering::SeqCst));
846
847 Ok(())
848 }
849
850 #[test]
851 fn test_event_query_uses_event_context() -> Result<()> {
852 let test_device = testing::bootstrap()?;
853 let context = Arc::clone(test_device.context());
854 let stream = context.create_stream(StreamOptions::default())?;
855 let event = context.create_event(EventFlags::DEFAULT)?;
856
857 event.record(&stream, EventRecordFlags::DEFAULT)?;
858 stream.synchronize()?;
859
860 assert!(event.query()?);
861 Ok(())
862 }
863
864 #[test]
865 fn test_shutdown_synchronizes_and_destroys_stream() -> Result<()> {
866 let test_device = testing::bootstrap()?;
867 let context = Arc::clone(test_device.context());
868 let stream = context.create_stream(StreamOptions::default())?;
869
870 let called = Arc::new(AtomicBool::new(false));
871 stream.add_callback(Box::new({
872 let called = Arc::clone(&called);
873 move |_status| {
874 called.store(true, Ordering::SeqCst);
875 }
876 }))?;
877
878 stream.shutdown()?;
879 assert!(called.load(Ordering::SeqCst));
880 Ok(())
881 }
882
883 #[test]
884 fn test_launch_host_func_runs_after_stream_work() -> Result<()> {
885 let test_device = testing::bootstrap()?;
886 let context = Arc::clone(test_device.context());
887 let stream = context.create_stream(StreamOptions::default())?;
888
889 let called = Arc::new(AtomicBool::new(false));
890 stream.launch_host_func({
891 let called = Arc::clone(&called);
892 move || {
893 called.store(true, Ordering::SeqCst);
894 }
895 })?;
896 stream.synchronize()?;
897
898 assert!(called.load(Ordering::SeqCst));
899 Ok(())
900 }
901
902 #[test]
903 fn test_scoped_capture_returns_context_associated_graph() -> Result<()> {
904 let test_device = testing::bootstrap()?;
905 let context = Arc::clone(test_device.context());
906 let stream = context.create_stream(StreamOptions::default())?;
907
908 let graph = stream.capture(StreamCaptureMode::Relaxed, |scope| {
909 assert_eq!(scope.stream().context(), &context);
910 Ok(())
911 })?;
912
913 assert_eq!(graph.context(), &context);
914 Ok(())
915 }
916
917 #[test]
918 fn test_capture_to_graph_rejects_graph_from_different_context() -> Result<()> {
919 let test_device = testing::bootstrap()?;
920 let context = Arc::clone(test_device.context());
921 let other_context = Context::create_dedicated(context.device(), ContextFlags::empty())?;
922
923 let stream = context.create_stream(StreamOptions::default())?;
924 let graph = other_context.create_graph()?;
925
926 assert!(matches!(
927 unsafe { stream.begin_capture_to_graph(&graph, &[], StreamCaptureMode::Relaxed) },
929 Err(Error::ContextMismatch { .. })
930 ));
931 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
932 Ok(())
933 }
934
935 #[test]
936 fn test_capture_to_graph_rejects_node_from_different_graph() -> Result<()> {
937 let test_device = testing::bootstrap()?;
938 let context = Arc::clone(test_device.context());
939
940 let stream = context.create_stream(StreamOptions::default())?;
941 let graph = context.create_graph()?;
942 let mut other_graph = context.create_graph()?;
943 let other_node = other_graph.add_empty_node(&[])?;
944
945 assert!(matches!(
946 unsafe {
948 stream.begin_capture_to_graph(
949 &graph,
950 &[GraphDependency {
951 node: other_node,
952 data: GraphEdgeAttributes::default(),
953 }],
954 StreamCaptureMode::Relaxed,
955 )
956 },
957 Err(Error::GraphNodeMismatch)
958 ));
959 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
960 Ok(())
961 }
962
963 #[test]
964 fn test_capture_to_graph_rejects_unassociated_raw_dependency_node() -> Result<()> {
965 let test_device = testing::bootstrap()?;
966 let context = Arc::clone(test_device.context());
967
968 let stream = context.create_stream(StreamOptions::default())?;
969 let graph = context.create_graph()?;
970 let raw_node = unsafe { GraphNode::from_raw(0x1usize as _) };
972
973 assert!(matches!(
974 unsafe {
976 stream.begin_capture_to_graph(
977 &graph,
978 &[GraphDependency {
979 node: raw_node,
980 data: GraphEdgeAttributes::default(),
981 }],
982 StreamCaptureMode::Relaxed,
983 )
984 },
985 Err(Error::GraphNodeMismatch)
986 ));
987 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
988 Ok(())
989 }
990
991 #[test]
992 fn test_capture_dependency_update_rejects_node_from_different_context() -> Result<()> {
993 let test_device = testing::bootstrap()?;
994 let context = Arc::clone(test_device.context());
995 let other_context = Context::create_dedicated(context.device(), ContextFlags::empty())?;
996
997 let stream = context.create_stream(StreamOptions::default())?;
998 let mut other_graph = other_context.create_graph()?;
999 let other_node = other_graph.add_empty_node(&[])?;
1000
1001 let result = stream.capture(StreamCaptureMode::Relaxed, |_scope| {
1002 stream.update_capture_dependencies(
1003 &[GraphDependency {
1004 node: other_node,
1005 data: GraphEdgeAttributes::default(),
1006 }],
1007 StreamCaptureDependencyUpdate::Add,
1008 )
1009 });
1010
1011 assert!(matches!(result, Err(Error::ContextMismatch { .. })));
1012 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1013 Ok(())
1014 }
1015
1016 #[test]
1017 fn test_capture_dependency_update_rejects_node_from_different_graph() -> Result<()> {
1018 let test_device = testing::bootstrap()?;
1019 let context = Arc::clone(test_device.context());
1020
1021 let stream = context.create_stream(StreamOptions::default())?;
1022 let mut other_graph = context.create_graph()?;
1023 let other_node = other_graph.add_empty_node(&[])?;
1024
1025 stream.begin_capture(StreamCaptureMode::Relaxed)?;
1026 assert!(matches!(
1027 stream.update_capture_dependencies(
1028 &[GraphDependency {
1029 node: other_node,
1030 data: GraphEdgeAttributes::default(),
1031 }],
1032 StreamCaptureDependencyUpdate::Add,
1033 ),
1034 Err(Error::GraphNodeMismatch)
1035 ));
1036 drop(stream.end_capture());
1037 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1038 Ok(())
1039 }
1040
1041 #[test]
1042 fn test_capture_dependency_update_rejects_unassociated_raw_node() -> Result<()> {
1043 let test_device = testing::bootstrap()?;
1044 let context = Arc::clone(test_device.context());
1045
1046 let stream = context.create_stream(StreamOptions::default())?;
1047 let raw_node = unsafe { GraphNode::from_raw(0x1usize as _) };
1049
1050 stream.begin_capture(StreamCaptureMode::Relaxed)?;
1051 assert!(matches!(
1052 stream.update_capture_dependencies(
1053 &[GraphDependency {
1054 node: raw_node,
1055 data: GraphEdgeAttributes::default(),
1056 }],
1057 StreamCaptureDependencyUpdate::Add,
1058 ),
1059 Err(Error::GraphNodeMismatch)
1060 ));
1061 drop(stream.end_capture());
1062 assert_eq!(stream.capture_status()?, StreamCaptureStatus::None);
1063 Ok(())
1064 }
1065
1066 #[test]
1067 fn test_captures_on_separate_streams_can_overlap() -> Result<()> {
1068 let test_device = testing::bootstrap()?;
1069 let context = Arc::clone(test_device.context());
1070 let stream_a = context.create_stream(StreamOptions::default())?;
1071 let stream_b = context.create_stream(StreamOptions::default())?;
1072
1073 thread::scope(|scope| {
1074 let a = scope.spawn(|| {
1075 let graph = stream_a.capture(StreamCaptureMode::Relaxed, |_scope| Ok(()))?;
1076 assert_eq!(graph.context(), &context);
1077 Result::<()>::Ok(())
1078 });
1079 let b = scope.spawn(|| {
1080 let graph = stream_b.capture(StreamCaptureMode::Relaxed, |_scope| Ok(()))?;
1081 assert_eq!(graph.context(), &context);
1082 Result::<()>::Ok(())
1083 });
1084
1085 a.join().expect("capture thread panicked")?;
1086 b.join().expect("capture thread panicked")?;
1087 Result::<()>::Ok(())
1088 })?;
1089
1090 Ok(())
1091 }
1092
1093 #[test]
1094 fn test_scoped_capture_error_leaves_stream_usable() -> Result<()> {
1095 let test_device = testing::bootstrap()?;
1096 let context = Arc::clone(test_device.context());
1097 let stream = context.create_stream(StreamOptions::default())?;
1098
1099 let result = stream.capture(StreamCaptureMode::Relaxed, |_scope| {
1100 Err(Error::out_of_range("capture body"))
1101 });
1102
1103 assert!(matches!(result, Err(Error::OutOfRange { .. })));
1104 stream.synchronize()?;
1105 Ok(())
1106 }
1107
1108 #[test]
1109 fn test_scoped_capture_panic_leaves_stream_usable() -> Result<()> {
1110 let test_device = testing::bootstrap()?;
1111 let context = Arc::clone(test_device.context());
1112 let stream = context.create_stream(StreamOptions::default())?;
1113
1114 let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1115 let _ = stream.capture(StreamCaptureMode::Relaxed, |_scope| -> Result<()> {
1116 panic!("capture body panic");
1117 });
1118 }));
1119
1120 assert!(result.is_err());
1121 stream.synchronize()?;
1122 Ok(())
1123 }
1124
1125 #[test]
1126 fn test_scoped_capture_records_memory_operations() -> Result<()> {
1127 let test_device = testing::bootstrap()?;
1128 let context = Arc::clone(test_device.context());
1129 let stream = context.create_stream(StreamOptions::default())?;
1130
1131 let input = [1u8, 2, 3, 4];
1132 let source = DeviceMemory::from_slice(&context, &input)?;
1133 let copied = DeviceMemory::<u8>::zeroed(&context, input.len())?;
1134 let filled = DeviceMemory::<u8>::zeroed(&context, input.len())?;
1135
1136 let graph = stream.capture(StreamCaptureMode::Relaxed, |scope| {
1137 unsafe {
1139 DeviceMemory::copy_async(
1140 copied.as_mut_ptr(),
1141 source.as_ptr(),
1142 input.len(),
1143 MemoryCopyKind::DeviceToDevice,
1144 scope.stream(),
1145 )?;
1146 DeviceMemory::<u8>::set_async(
1147 filled.as_mut_ptr(),
1148 0xab,
1149 input.len(),
1150 scope.stream(),
1151 )
1152 }
1153 })?;
1154
1155 let executable = graph.instantiate(GraphInstantiateFlags::empty())?;
1156 unsafe {
1158 executable.launch_async(&stream)?;
1159 }
1160 stream.synchronize()?;
1161
1162 assert_eq!(copied.copy_to_host_vec()?, input);
1163 assert_eq!(filled.copy_to_host_vec()?, [0xab; 4]);
1164 Ok(())
1165 }
1166}